LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 2aa98e37cd3250b9a68c97ef6050b16fe702ab33.info Lines: 80.1 % 6435 5154
Test Date: 2024-08-29 11:33:10 Functions: 59.2 % 375 222

            Line data    Source code
       1              : //!
       2              : //! Timeline repository implementation that keeps old data in files on disk, and
       3              : //! the recent changes in memory. See tenant/*_layer.rs files.
       4              : //! The functions here are responsible for locating the correct layer for the
       5              : //! get/put call, walking back the timeline branching history as needed.
       6              : //!
       7              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       8              : //! directory. See docs/pageserver-storage.md for how the files are managed.
       9              : //! In addition to the layer files, there is a metadata file in the same
      10              : //! directory that contains information about the timeline, in particular its
      11              : //! parent timeline, and the last LSN that has been written to disk.
      12              : //!
      13              : 
      14              : use anyhow::{bail, Context};
      15              : use arc_swap::ArcSwap;
      16              : use camino::Utf8Path;
      17              : use camino::Utf8PathBuf;
      18              : use enumset::EnumSet;
      19              : use futures::stream::FuturesUnordered;
      20              : use futures::FutureExt;
      21              : use futures::StreamExt;
      22              : use pageserver_api::models;
      23              : use pageserver_api::models::AuxFilePolicy;
      24              : use pageserver_api::models::TimelineArchivalState;
      25              : use pageserver_api::models::TimelineState;
      26              : use pageserver_api::models::TopTenantShardItem;
      27              : use pageserver_api::models::WalRedoManagerStatus;
      28              : use pageserver_api::shard::ShardIdentity;
      29              : use pageserver_api::shard::ShardStripeSize;
      30              : use pageserver_api::shard::TenantShardId;
      31              : use remote_storage::DownloadError;
      32              : use remote_storage::GenericRemoteStorage;
      33              : use remote_storage::TimeoutOrCancel;
      34              : use std::collections::BTreeMap;
      35              : use std::fmt;
      36              : use std::sync::Weak;
      37              : use std::time::SystemTime;
      38              : use storage_broker::BrokerClientChannel;
      39              : use tokio::io::BufReader;
      40              : use tokio::sync::watch;
      41              : use tokio::task::JoinSet;
      42              : use tokio_util::sync::CancellationToken;
      43              : use tracing::*;
      44              : use upload_queue::NotInitialized;
      45              : use utils::backoff;
      46              : use utils::circuit_breaker::CircuitBreaker;
      47              : use utils::completion;
      48              : use utils::crashsafe::path_with_suffix_extension;
      49              : use utils::failpoint_support;
      50              : use utils::fs_ext;
      51              : use utils::pausable_failpoint;
      52              : use utils::sync::gate::Gate;
      53              : use utils::sync::gate::GateGuard;
      54              : use utils::timeout::timeout_cancellable;
      55              : use utils::timeout::TimeoutCancellableError;
      56              : use utils::zstd::create_zst_tarball;
      57              : use utils::zstd::extract_zst_tarball;
      58              : 
      59              : use self::config::AttachedLocationConfig;
      60              : use self::config::AttachmentMode;
      61              : use self::config::LocationConf;
      62              : use self::config::TenantConf;
      63              : use self::metadata::TimelineMetadata;
      64              : use self::mgr::GetActiveTenantError;
      65              : use self::mgr::GetTenantError;
      66              : use self::remote_timeline_client::upload::upload_index_part;
      67              : use self::remote_timeline_client::RemoteTimelineClient;
      68              : use self::timeline::uninit::TimelineCreateGuard;
      69              : use self::timeline::uninit::TimelineExclusionError;
      70              : use self::timeline::uninit::UninitializedTimeline;
      71              : use self::timeline::EvictionTaskTenantState;
      72              : use self::timeline::GcCutoffs;
      73              : use self::timeline::TimelineResources;
      74              : use self::timeline::WaitLsnError;
      75              : use crate::config::PageServerConf;
      76              : use crate::context::{DownloadBehavior, RequestContext};
      77              : use crate::deletion_queue::DeletionQueueClient;
      78              : use crate::deletion_queue::DeletionQueueError;
      79              : use crate::import_datadir;
      80              : use crate::is_uninit_mark;
      81              : use crate::l0_flush::L0FlushGlobalState;
      82              : use crate::metrics::TENANT;
      83              : use crate::metrics::{
      84              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
      85              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
      86              : };
      87              : use crate::repository::GcResult;
      88              : use crate::task_mgr;
      89              : use crate::task_mgr::TaskKind;
      90              : use crate::tenant::config::LocationMode;
      91              : use crate::tenant::config::TenantConfOpt;
      92              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      93              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
      94              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
      95              : use crate::tenant::remote_timeline_client::INITDB_PATH;
      96              : use crate::tenant::storage_layer::DeltaLayer;
      97              : use crate::tenant::storage_layer::ImageLayer;
      98              : use crate::walredo;
      99              : use crate::InitializationOrder;
     100              : use std::collections::hash_map::Entry;
     101              : use std::collections::HashMap;
     102              : use std::collections::HashSet;
     103              : use std::fmt::Debug;
     104              : use std::fmt::Display;
     105              : use std::fs;
     106              : use std::fs::File;
     107              : use std::sync::atomic::{AtomicU64, Ordering};
     108              : use std::sync::Arc;
     109              : use std::sync::Mutex;
     110              : use std::time::{Duration, Instant};
     111              : 
     112              : use crate::span;
     113              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     114              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     115              : use crate::virtual_file::VirtualFile;
     116              : use crate::walredo::PostgresRedoManager;
     117              : use crate::TEMP_FILE_SUFFIX;
     118              : use once_cell::sync::Lazy;
     119              : pub use pageserver_api::models::TenantState;
     120              : use tokio::sync::Semaphore;
     121              : 
     122            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     123              : use utils::{
     124              :     crashsafe,
     125              :     generation::Generation,
     126              :     id::TimelineId,
     127              :     lsn::{Lsn, RecordLsn},
     128              : };
     129              : 
     130              : pub mod blob_io;
     131              : pub mod block_io;
     132              : pub mod vectored_blob_io;
     133              : 
     134              : pub mod disk_btree;
     135              : pub(crate) mod ephemeral_file;
     136              : pub mod layer_map;
     137              : 
     138              : pub mod metadata;
     139              : pub mod remote_timeline_client;
     140              : pub mod storage_layer;
     141              : 
     142              : pub mod config;
     143              : pub mod mgr;
     144              : pub mod secondary;
     145              : pub mod tasks;
     146              : pub mod upload_queue;
     147              : 
     148              : pub(crate) mod timeline;
     149              : 
     150              : pub mod size;
     151              : 
     152              : mod gc_block;
     153              : pub(crate) mod throttle;
     154              : 
     155              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     156              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     157              : 
     158              : // re-export for use in walreceiver
     159              : pub use crate::tenant::timeline::WalReceiverInfo;
     160              : 
     161              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     162              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     163              : 
     164              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     165              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     166              : 
     167              : /// References to shared objects that are passed into each tenant, such
     168              : /// as the shared remote storage client and process initialization state.
     169              : #[derive(Clone)]
     170              : pub struct TenantSharedResources {
     171              :     pub broker_client: storage_broker::BrokerClientChannel,
     172              :     pub remote_storage: GenericRemoteStorage,
     173              :     pub deletion_queue_client: DeletionQueueClient,
     174              :     pub l0_flush_global_state: L0FlushGlobalState,
     175              : }
     176              : 
     177              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     178              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     179              : /// in this struct.
     180              : pub(super) struct AttachedTenantConf {
     181              :     tenant_conf: TenantConfOpt,
     182              :     location: AttachedLocationConfig,
     183              : }
     184              : 
     185              : impl AttachedTenantConf {
     186            0 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     187            0 :         Self {
     188            0 :             tenant_conf,
     189            0 :             location,
     190            0 :         }
     191            0 :     }
     192              : 
     193          588 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     194          588 :         match &location_conf.mode {
     195          588 :             LocationMode::Attached(attach_conf) => Ok(Self {
     196          588 :                 tenant_conf: location_conf.tenant_conf,
     197          588 :                 location: *attach_conf,
     198          588 :             }),
     199              :             LocationMode::Secondary(_) => {
     200            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     201              :             }
     202              :         }
     203          588 :     }
     204              : }
     205              : struct TimelinePreload {
     206              :     timeline_id: TimelineId,
     207              :     client: RemoteTimelineClient,
     208              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     209              : }
     210              : 
     211              : pub(crate) struct TenantPreload {
     212              :     timelines: HashMap<TimelineId, TimelinePreload>,
     213              : }
     214              : 
     215              : /// When we spawn a tenant, there is a special mode for tenant creation that
     216              : /// avoids trying to read anything from remote storage.
     217              : pub(crate) enum SpawnMode {
     218              :     /// Activate as soon as possible
     219              :     Eager,
     220              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     221              :     Lazy,
     222              : }
     223              : 
     224              : ///
     225              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     226              : ///
     227              : pub struct Tenant {
     228              :     // Global pageserver config parameters
     229              :     pub conf: &'static PageServerConf,
     230              : 
     231              :     /// The value creation timestamp, used to measure activation delay, see:
     232              :     /// <https://github.com/neondatabase/neon/issues/4025>
     233              :     constructed_at: Instant,
     234              : 
     235              :     state: watch::Sender<TenantState>,
     236              : 
     237              :     // Overridden tenant-specific config parameters.
     238              :     // We keep TenantConfOpt sturct here to preserve the information
     239              :     // about parameters that are not set.
     240              :     // This is necessary to allow global config updates.
     241              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     242              : 
     243              :     tenant_shard_id: TenantShardId,
     244              : 
     245              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     246              :     shard_identity: ShardIdentity,
     247              : 
     248              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     249              :     /// Does not change over the lifetime of the [`Tenant`] object.
     250              :     ///
     251              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     252              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     253              :     generation: Generation,
     254              : 
     255              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     256              : 
     257              :     /// During timeline creation, we first insert the TimelineId to the
     258              :     /// creating map, then `timelines`, then remove it from the creating map.
     259              :     /// **Lock order**: if acquring both, acquire`timelines` before `timelines_creating`
     260              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     261              : 
     262              :     // This mutex prevents creation of new timelines during GC.
     263              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     264              :     // `timelines` mutex during all GC iteration
     265              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     266              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     267              :     // timeout...
     268              :     gc_cs: tokio::sync::Mutex<()>,
     269              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     270              : 
     271              :     // provides access to timeline data sitting in the remote storage
     272              :     pub(crate) remote_storage: GenericRemoteStorage,
     273              : 
     274              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     275              :     deletion_queue_client: DeletionQueueClient,
     276              : 
     277              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     278              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     279              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     280              : 
     281              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     282              : 
     283              :     /// Track repeated failures to compact, so that we can back off.
     284              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     285              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     286              : 
     287              :     /// If the tenant is in Activating state, notify this to encourage it
     288              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     289              :     /// background warmup.
     290              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     291              : 
     292              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     293              :     // Timelines' cancellation token.
     294              :     pub(crate) cancel: CancellationToken,
     295              : 
     296              :     // Users of the Tenant such as the page service must take this Gate to avoid
     297              :     // trying to use a Tenant which is shutting down.
     298              :     pub(crate) gate: Gate,
     299              : 
     300              :     /// Throttle applied at the top of [`Timeline::get`].
     301              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     302              :     pub(crate) timeline_get_throttle:
     303              :         Arc<throttle::Throttle<&'static crate::metrics::tenant_throttling::TimelineGet>>,
     304              : 
     305              :     /// An ongoing timeline detach concurrency limiter.
     306              :     ///
     307              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     308              :     /// to have two running at the same time. A different one can be started if an earlier one
     309              :     /// has failed for whatever reason.
     310              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     311              : 
     312              :     /// `index_part.json` based gc blocking reason tracking.
     313              :     ///
     314              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     315              :     /// proceeding.
     316              :     pub(crate) gc_block: gc_block::GcBlock,
     317              : 
     318              :     l0_flush_global_state: L0FlushGlobalState,
     319              : }
     320              : 
     321              : impl std::fmt::Debug for Tenant {
     322            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     323            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     324            0 :     }
     325              : }
     326              : 
     327              : pub(crate) enum WalRedoManager {
     328              :     Prod(WalredoManagerId, PostgresRedoManager),
     329              :     #[cfg(test)]
     330              :     Test(harness::TestRedoManager),
     331              : }
     332              : 
     333            0 : #[derive(thiserror::Error, Debug)]
     334              : #[error("pageserver is shutting down")]
     335              : pub(crate) struct GlobalShutDown;
     336              : 
     337              : impl WalRedoManager {
     338            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     339            0 :         let id = WalredoManagerId::next();
     340            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     341            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     342            0 :         match &mut *guard {
     343            0 :             Some(map) => {
     344            0 :                 map.insert(id, Arc::downgrade(&arc));
     345            0 :                 Ok(arc)
     346              :             }
     347            0 :             None => Err(GlobalShutDown),
     348              :         }
     349            0 :     }
     350              : }
     351              : 
     352              : impl Drop for WalRedoManager {
     353           30 :     fn drop(&mut self) {
     354           30 :         match self {
     355            0 :             Self::Prod(id, _) => {
     356            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     357            0 :                 if let Some(map) = &mut *guard {
     358            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     359            0 :                 }
     360              :             }
     361              :             #[cfg(test)]
     362           30 :             Self::Test(_) => {
     363           30 :                 // Not applicable to test redo manager
     364           30 :             }
     365              :         }
     366           30 :     }
     367              : }
     368              : 
     369              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     370              : /// the walredo processes outside of the regular order.
     371              : ///
     372              : /// This is necessary to work around a systemd bug where it freezes if there are
     373              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     374              : #[allow(clippy::type_complexity)]
     375              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     376              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     377            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     378              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     379              : pub(crate) struct WalredoManagerId(u64);
     380              : impl WalredoManagerId {
     381            0 :     pub fn next() -> Self {
     382            0 :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     383            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     384            0 :         if id == 0 {
     385            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     386            0 :         }
     387            0 :         Self(id)
     388            0 :     }
     389              : }
     390              : 
     391              : #[cfg(test)]
     392              : impl From<harness::TestRedoManager> for WalRedoManager {
     393          564 :     fn from(mgr: harness::TestRedoManager) -> Self {
     394          564 :         Self::Test(mgr)
     395          564 :     }
     396              : }
     397              : 
     398              : impl WalRedoManager {
     399           18 :     pub(crate) async fn shutdown(&self) -> bool {
     400           18 :         match self {
     401            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     402              :             #[cfg(test)]
     403              :             Self::Test(_) => {
     404              :                 // Not applicable to test redo manager
     405           18 :                 true
     406              :             }
     407              :         }
     408           18 :     }
     409              : 
     410            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     411            0 :         match self {
     412            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     413            0 :             #[cfg(test)]
     414            0 :             Self::Test(_) => {
     415            0 :                 // Not applicable to test redo manager
     416            0 :             }
     417            0 :         }
     418            0 :     }
     419              : 
     420              :     /// # Cancel-Safety
     421              :     ///
     422              :     /// This method is cancellation-safe.
     423          978 :     pub async fn request_redo(
     424          978 :         &self,
     425          978 :         key: crate::repository::Key,
     426          978 :         lsn: Lsn,
     427          978 :         base_img: Option<(Lsn, bytes::Bytes)>,
     428          978 :         records: Vec<(Lsn, crate::walrecord::NeonWalRecord)>,
     429          978 :         pg_version: u32,
     430          978 :     ) -> Result<bytes::Bytes, walredo::Error> {
     431          978 :         match self {
     432            0 :             Self::Prod(_, mgr) => {
     433            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     434            0 :                     .await
     435              :             }
     436              :             #[cfg(test)]
     437          978 :             Self::Test(mgr) => {
     438          978 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     439            0 :                     .await
     440              :             }
     441              :         }
     442          978 :     }
     443              : 
     444            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     445            0 :         match self {
     446            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     447            0 :             #[cfg(test)]
     448            0 :             WalRedoManager::Test(_) => None,
     449            0 :         }
     450            0 :     }
     451              : }
     452              : 
     453            0 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     454              : pub enum GetTimelineError {
     455              :     #[error("Timeline is shutting down")]
     456              :     ShuttingDown,
     457              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     458              :     NotActive {
     459              :         tenant_id: TenantShardId,
     460              :         timeline_id: TimelineId,
     461              :         state: TimelineState,
     462              :     },
     463              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     464              :     NotFound {
     465              :         tenant_id: TenantShardId,
     466              :         timeline_id: TimelineId,
     467              :     },
     468              : }
     469              : 
     470            0 : #[derive(Debug, thiserror::Error)]
     471              : pub enum LoadLocalTimelineError {
     472              :     #[error("FailedToLoad")]
     473              :     Load(#[source] anyhow::Error),
     474              :     #[error("FailedToResumeDeletion")]
     475              :     ResumeDeletion(#[source] anyhow::Error),
     476              : }
     477              : 
     478            0 : #[derive(thiserror::Error)]
     479              : pub enum DeleteTimelineError {
     480              :     #[error("NotFound")]
     481              :     NotFound,
     482              : 
     483              :     #[error("HasChildren")]
     484              :     HasChildren(Vec<TimelineId>),
     485              : 
     486              :     #[error("Timeline deletion is already in progress")]
     487              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     488              : 
     489              :     #[error(transparent)]
     490              :     Other(#[from] anyhow::Error),
     491              : }
     492              : 
     493              : impl Debug for DeleteTimelineError {
     494            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     495            0 :         match self {
     496            0 :             Self::NotFound => write!(f, "NotFound"),
     497            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     498            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     499            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     500              :         }
     501            0 :     }
     502              : }
     503              : 
     504            0 : #[derive(thiserror::Error)]
     505              : pub enum TimelineArchivalError {
     506              :     #[error("NotFound")]
     507              :     NotFound,
     508              : 
     509              :     #[error("Timeout")]
     510              :     Timeout,
     511              : 
     512              :     #[error("HasUnarchivedChildren")]
     513              :     HasUnarchivedChildren(Vec<TimelineId>),
     514              : 
     515              :     #[error("Timeline archival is already in progress")]
     516              :     AlreadyInProgress,
     517              : 
     518              :     #[error(transparent)]
     519              :     Other(#[from] anyhow::Error),
     520              : }
     521              : 
     522              : impl Debug for TimelineArchivalError {
     523            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     524            0 :         match self {
     525            0 :             Self::NotFound => write!(f, "NotFound"),
     526            0 :             Self::Timeout => write!(f, "Timeout"),
     527            0 :             Self::HasUnarchivedChildren(c) => {
     528            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     529              :             }
     530            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     531            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     532              :         }
     533            0 :     }
     534              : }
     535              : 
     536              : pub enum SetStoppingError {
     537              :     AlreadyStopping(completion::Barrier),
     538              :     Broken,
     539              : }
     540              : 
     541              : impl Debug for SetStoppingError {
     542            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     543            0 :         match self {
     544            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     545            0 :             Self::Broken => write!(f, "Broken"),
     546              :         }
     547            0 :     }
     548              : }
     549              : 
     550            0 : #[derive(thiserror::Error, Debug)]
     551              : pub enum CreateTimelineError {
     552              :     #[error("creation of timeline with the given ID is in progress")]
     553              :     AlreadyCreating,
     554              :     #[error("timeline already exists with different parameters")]
     555              :     Conflict,
     556              :     #[error(transparent)]
     557              :     AncestorLsn(anyhow::Error),
     558              :     #[error("ancestor timeline is not active")]
     559              :     AncestorNotActive,
     560              :     #[error("tenant shutting down")]
     561              :     ShuttingDown,
     562              :     #[error(transparent)]
     563              :     Other(#[from] anyhow::Error),
     564              : }
     565              : 
     566              : #[derive(thiserror::Error, Debug)]
     567              : enum InitdbError {
     568              :     Other(anyhow::Error),
     569              :     Cancelled,
     570              :     Spawn(std::io::Result<()>),
     571              :     Failed(std::process::ExitStatus, Vec<u8>),
     572              : }
     573              : 
     574              : impl fmt::Display for InitdbError {
     575            0 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     576            0 :         match self {
     577            0 :             InitdbError::Cancelled => write!(f, "Operation was cancelled"),
     578            0 :             InitdbError::Spawn(e) => write!(f, "Spawn error: {:?}", e),
     579            0 :             InitdbError::Failed(status, stderr) => write!(
     580            0 :                 f,
     581            0 :                 "Command failed with status {:?}: {}",
     582            0 :                 status,
     583            0 :                 String::from_utf8_lossy(stderr)
     584            0 :             ),
     585            0 :             InitdbError::Other(e) => write!(f, "Error: {:?}", e),
     586              :         }
     587            0 :     }
     588              : }
     589              : 
     590              : impl From<std::io::Error> for InitdbError {
     591            0 :     fn from(error: std::io::Error) -> Self {
     592            0 :         InitdbError::Spawn(Err(error))
     593            0 :     }
     594              : }
     595              : 
     596              : enum CreateTimelineCause {
     597              :     Load,
     598              :     Delete,
     599              : }
     600              : 
     601            0 : #[derive(thiserror::Error, Debug)]
     602              : pub(crate) enum GcError {
     603              :     // The tenant is shutting down
     604              :     #[error("tenant shutting down")]
     605              :     TenantCancelled,
     606              : 
     607              :     // The tenant is shutting down
     608              :     #[error("timeline shutting down")]
     609              :     TimelineCancelled,
     610              : 
     611              :     // The tenant is in a state inelegible to run GC
     612              :     #[error("not active")]
     613              :     NotActive,
     614              : 
     615              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
     616              :     #[error("not active")]
     617              :     BadLsn { why: String },
     618              : 
     619              :     // A remote storage error while scheduling updates after compaction
     620              :     #[error(transparent)]
     621              :     Remote(anyhow::Error),
     622              : 
     623              :     // An error reading while calculating GC cutoffs
     624              :     #[error(transparent)]
     625              :     GcCutoffs(PageReconstructError),
     626              : 
     627              :     // If GC was invoked for a particular timeline, this error means it didn't exist
     628              :     #[error("timeline not found")]
     629              :     TimelineNotFound,
     630              : }
     631              : 
     632              : impl From<PageReconstructError> for GcError {
     633            0 :     fn from(value: PageReconstructError) -> Self {
     634            0 :         match value {
     635            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
     636            0 :             other => Self::GcCutoffs(other),
     637              :         }
     638            0 :     }
     639              : }
     640              : 
     641              : impl From<NotInitialized> for GcError {
     642            0 :     fn from(value: NotInitialized) -> Self {
     643            0 :         match value {
     644            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
     645            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
     646              :         }
     647            0 :     }
     648              : }
     649              : 
     650              : impl From<timeline::layer_manager::Shutdown> for GcError {
     651            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
     652            0 :         GcError::TimelineCancelled
     653            0 :     }
     654              : }
     655              : 
     656            0 : #[derive(thiserror::Error, Debug)]
     657              : pub(crate) enum LoadConfigError {
     658              :     #[error("TOML deserialization error: '{0}'")]
     659              :     DeserializeToml(#[from] toml_edit::de::Error),
     660              : 
     661              :     #[error("Config not found at {0}")]
     662              :     NotFound(Utf8PathBuf),
     663              : }
     664              : 
     665              : impl Tenant {
     666              :     /// Yet another helper for timeline initialization.
     667              :     ///
     668              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
     669              :     /// - Scans the local timeline directory for layer files and builds the layer map
     670              :     /// - Downloads remote index file and adds remote files to the layer map
     671              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
     672              :     ///
     673              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
     674              :     /// it is marked as Active.
     675              :     #[allow(clippy::too_many_arguments)]
     676           18 :     async fn timeline_init_and_sync(
     677           18 :         &self,
     678           18 :         timeline_id: TimelineId,
     679           18 :         resources: TimelineResources,
     680           18 :         index_part: Option<IndexPart>,
     681           18 :         metadata: TimelineMetadata,
     682           18 :         ancestor: Option<Arc<Timeline>>,
     683           18 :         last_aux_file_policy: Option<AuxFilePolicy>,
     684           18 :         _ctx: &RequestContext,
     685           18 :     ) -> anyhow::Result<()> {
     686           18 :         let tenant_id = self.tenant_shard_id;
     687              : 
     688           18 :         let timeline = self.create_timeline_struct(
     689           18 :             timeline_id,
     690           18 :             &metadata,
     691           18 :             ancestor.clone(),
     692           18 :             resources,
     693           18 :             CreateTimelineCause::Load,
     694           18 :             // This could be derived from ancestor branch + index part. Though the only caller of `timeline_init_and_sync` is `load_remote_timeline`,
     695           18 :             // there will potentially be other caller of this function in the future, and we don't know whether `index_part` or `ancestor` takes precedence.
     696           18 :             // Therefore, we pass this field explicitly for now, and remove it once we fully migrate to aux file v2.
     697           18 :             last_aux_file_policy,
     698           18 :         )?;
     699           18 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
     700           18 :         anyhow::ensure!(
     701           18 :             disk_consistent_lsn.is_valid(),
     702            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
     703              :         );
     704           18 :         assert_eq!(
     705           18 :             disk_consistent_lsn,
     706           18 :             metadata.disk_consistent_lsn(),
     707            0 :             "these are used interchangeably"
     708              :         );
     709              : 
     710           18 :         if let Some(index_part) = index_part.as_ref() {
     711           18 :             timeline.remote_client.init_upload_queue(index_part)?;
     712              : 
     713           18 :             timeline
     714           18 :                 .last_aux_file_policy
     715           18 :                 .store(index_part.last_aux_file_policy());
     716              :         } else {
     717              :             // No data on the remote storage, but we have local metadata file. We can end up
     718              :             // here with timeline_create being interrupted before finishing index part upload.
     719              :             // By doing what we do here, the index part upload is retried.
     720              :             // If control plane retries timeline creation in the meantime, the mgmt API handler
     721              :             // for timeline creation will coalesce on the upload we queue here.
     722              : 
     723              :             // FIXME: this branch should be dead code as we no longer write local metadata.
     724              : 
     725            0 :             timeline
     726            0 :                 .remote_client
     727            0 :                 .init_upload_queue_for_empty_remote(&metadata)?;
     728            0 :             timeline
     729            0 :                 .remote_client
     730            0 :                 .schedule_index_upload_for_full_metadata_update(&metadata)?;
     731              :         }
     732              : 
     733           18 :         timeline
     734           18 :             .load_layer_map(disk_consistent_lsn, index_part)
     735           15 :             .await
     736           18 :             .with_context(|| {
     737            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
     738           18 :             })?;
     739              : 
     740              :         {
     741              :             // avoiding holding it across awaits
     742           18 :             let mut timelines_accessor = self.timelines.lock().unwrap();
     743           18 :             match timelines_accessor.entry(timeline_id) {
     744              :                 // We should never try and load the same timeline twice during startup
     745              :                 Entry::Occupied(_) => {
     746            0 :                     unreachable!(
     747            0 :                         "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
     748            0 :                     );
     749              :                 }
     750           18 :                 Entry::Vacant(v) => {
     751           18 :                     v.insert(Arc::clone(&timeline));
     752           18 :                     timeline.maybe_spawn_flush_loop();
     753           18 :                 }
     754           18 :             }
     755           18 :         };
     756           18 : 
     757           18 :         // Sanity check: a timeline should have some content.
     758           18 :         anyhow::ensure!(
     759           18 :             ancestor.is_some()
     760           12 :                 || timeline
     761           12 :                     .layers
     762           12 :                     .read()
     763            0 :                     .await
     764           12 :                     .layer_map()
     765           12 :                     .expect("currently loading, layer manager cannot be shutdown already")
     766           12 :                     .iter_historic_layers()
     767           12 :                     .next()
     768           12 :                     .is_some(),
     769            0 :             "Timeline has no ancestor and no layer files"
     770              :         );
     771              : 
     772           18 :         Ok(())
     773           18 :     }
     774              : 
     775              :     /// Attach a tenant that's available in cloud storage.
     776              :     ///
     777              :     /// This returns quickly, after just creating the in-memory object
     778              :     /// Tenant struct and launching a background task to download
     779              :     /// the remote index files.  On return, the tenant is most likely still in
     780              :     /// Attaching state, and it will become Active once the background task
     781              :     /// finishes. You can use wait_until_active() to wait for the task to
     782              :     /// complete.
     783              :     ///
     784              :     #[allow(clippy::too_many_arguments)]
     785            0 :     pub(crate) fn spawn(
     786            0 :         conf: &'static PageServerConf,
     787            0 :         tenant_shard_id: TenantShardId,
     788            0 :         resources: TenantSharedResources,
     789            0 :         attached_conf: AttachedTenantConf,
     790            0 :         shard_identity: ShardIdentity,
     791            0 :         init_order: Option<InitializationOrder>,
     792            0 :         mode: SpawnMode,
     793            0 :         ctx: &RequestContext,
     794            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
     795            0 :         let wal_redo_manager =
     796            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
     797              : 
     798              :         let TenantSharedResources {
     799            0 :             broker_client,
     800            0 :             remote_storage,
     801            0 :             deletion_queue_client,
     802            0 :             l0_flush_global_state,
     803            0 :         } = resources;
     804            0 : 
     805            0 :         let attach_mode = attached_conf.location.attach_mode;
     806            0 :         let generation = attached_conf.location.generation;
     807            0 : 
     808            0 :         let tenant = Arc::new(Tenant::new(
     809            0 :             TenantState::Attaching,
     810            0 :             conf,
     811            0 :             attached_conf,
     812            0 :             shard_identity,
     813            0 :             Some(wal_redo_manager),
     814            0 :             tenant_shard_id,
     815            0 :             remote_storage.clone(),
     816            0 :             deletion_queue_client,
     817            0 :             l0_flush_global_state,
     818            0 :         ));
     819            0 : 
     820            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
     821            0 :         // we shut down while attaching.
     822            0 :         let attach_gate_guard = tenant
     823            0 :             .gate
     824            0 :             .enter()
     825            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
     826            0 : 
     827            0 :         // Do all the hard work in the background
     828            0 :         let tenant_clone = Arc::clone(&tenant);
     829            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
     830            0 :         task_mgr::spawn(
     831            0 :             &tokio::runtime::Handle::current(),
     832            0 :             TaskKind::Attach,
     833            0 :             tenant_shard_id,
     834            0 :             None,
     835            0 :             "attach tenant",
     836            0 :             async move {
     837            0 : 
     838            0 :                 info!(
     839              :                     ?attach_mode,
     840            0 :                     "Attaching tenant"
     841              :                 );
     842              : 
     843            0 :                 let _gate_guard = attach_gate_guard;
     844            0 : 
     845            0 :                 // Is this tenant being spawned as part of process startup?
     846            0 :                 let starting_up = init_order.is_some();
     847              :                 scopeguard::defer! {
     848              :                     if starting_up {
     849              :                         TENANT.startup_complete.inc();
     850              :                     }
     851              :                 }
     852              : 
     853              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
     854              :                 enum BrokenVerbosity {
     855              :                     Error,
     856              :                     Info
     857              :                 }
     858            0 :                 let make_broken =
     859            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
     860            0 :                         match verbosity {
     861              :                             BrokenVerbosity::Info => {
     862            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
     863              :                             },
     864              :                             BrokenVerbosity::Error => {
     865            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
     866              :                             }
     867              :                         }
     868            0 :                         t.state.send_modify(|state| {
     869            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
     870            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
     871            0 :                             assert!(
     872            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
     873            0 :                                 "the attach task owns the tenant state until activation is complete"
     874              :                             );
     875              : 
     876            0 :                             *state = TenantState::broken_from_reason(err.to_string());
     877            0 :                         });
     878            0 :                     };
     879              : 
     880              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
     881            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
     882            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
     883            0 :                     return Ok(());
     884            0 :                 }
     885            0 : 
     886            0 :                 let mut init_order = init_order;
     887            0 :                 // take the completion because initial tenant loading will complete when all of
     888            0 :                 // these tasks complete.
     889            0 :                 let _completion = init_order
     890            0 :                     .as_mut()
     891            0 :                     .and_then(|x| x.initial_tenant_load.take());
     892            0 :                 let remote_load_completion = init_order
     893            0 :                     .as_mut()
     894            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
     895              : 
     896              :                 enum AttachType<'a> {
     897              :                     /// We are attaching this tenant lazily in the background.
     898              :                     Warmup {
     899              :                         _permit: tokio::sync::SemaphorePermit<'a>,
     900              :                         during_startup: bool
     901              :                     },
     902              :                     /// We are attaching this tenant as soon as we can, because for example an
     903              :                     /// endpoint tried to access it.
     904              :                     OnDemand,
     905              :                     /// During normal operations after startup, we are attaching a tenant, and
     906              :                     /// eager attach was requested.
     907              :                     Normal,
     908              :                 }
     909              : 
     910            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
     911              :                     // Before doing any I/O, wait for at least one of:
     912              :                     // - A client attempting to access to this tenant (on-demand loading)
     913              :                     // - A permit becoming available in the warmup semaphore (background warmup)
     914              : 
     915              :                     tokio::select!(
     916              :                         permit = tenant_clone.activate_now_sem.acquire() => {
     917              :                             let _ = permit.expect("activate_now_sem is never closed");
     918              :                             tracing::info!("Activating tenant (on-demand)");
     919              :                             AttachType::OnDemand
     920              :                         },
     921              :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
     922              :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
     923              :                             tracing::info!("Activating tenant (warmup)");
     924              :                             AttachType::Warmup {
     925              :                                 _permit,
     926              :                                 during_startup: init_order.is_some()
     927              :                             }
     928              :                         }
     929              :                         _ = tenant_clone.cancel.cancelled() => {
     930              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
     931              :                             // stayed in Activating for such a long time that shutdown found it in
     932              :                             // that state.
     933              :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
     934              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
     935              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
     936              :                             // just shutting down), but ensures progress.
     937              :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
     938              :                             return Ok(());
     939              :                         },
     940              :                     )
     941              :                 } else {
     942              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
     943              :                     // concurrent_tenant_warmup queue
     944            0 :                     AttachType::Normal
     945              :                 };
     946              : 
     947            0 :                 let preload = match &mode {
     948              :                     SpawnMode::Eager | SpawnMode::Lazy => {
     949            0 :                         let _preload_timer = TENANT.preload.start_timer();
     950            0 :                         let res = tenant_clone
     951            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
     952            0 :                             .await;
     953            0 :                         match res {
     954            0 :                             Ok(p) => Some(p),
     955            0 :                             Err(e) => {
     956            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
     957            0 :                                 return Ok(());
     958              :                             }
     959              :                         }
     960              :                     }
     961              : 
     962              :                 };
     963              : 
     964              :                 // Remote preload is complete.
     965            0 :                 drop(remote_load_completion);
     966              : 
     967              :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
     968            0 :                 let attached = {
     969            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
     970            0 :                     tenant_clone.attach(preload, &ctx).await
     971              :                 };
     972              : 
     973            0 :                 match attached {
     974              :                     Ok(()) => {
     975            0 :                         info!("attach finished, activating");
     976            0 :                         tenant_clone.activate(broker_client, None, &ctx);
     977              :                     }
     978            0 :                     Err(e) => {
     979            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
     980            0 :                     }
     981              :                 }
     982              : 
     983              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
     984              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
     985              :                 // with cold caches and then coming back later to initialize their logical sizes.
     986              :                 //
     987              :                 // It also prevents the warmup proccess competing with the concurrency limit on
     988              :                 // logical size calculations: if logical size calculation semaphore is saturated,
     989              :                 // then warmup will wait for that before proceeding to the next tenant.
     990            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
     991            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
     992            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
     993            0 :                     while futs.next().await.is_some() {}
     994            0 :                     tracing::info!("Warm-up complete");
     995            0 :                 }
     996              : 
     997            0 :                 Ok(())
     998            0 :             }
     999            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1000              :         );
    1001            0 :         Ok(tenant)
    1002            0 :     }
    1003              : 
    1004         1128 :     #[instrument(skip_all)]
    1005              :     pub(crate) async fn preload(
    1006              :         self: &Arc<Self>,
    1007              :         remote_storage: &GenericRemoteStorage,
    1008              :         cancel: CancellationToken,
    1009              :     ) -> anyhow::Result<TenantPreload> {
    1010              :         span::debug_assert_current_span_has_tenant_id();
    1011              :         // Get list of remote timelines
    1012              :         // download index files for every tenant timeline
    1013              :         info!("listing remote timelines");
    1014              :         let (remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1015              :             remote_storage,
    1016              :             self.tenant_shard_id,
    1017              :             cancel.clone(),
    1018              :         )
    1019              :         .await?;
    1020              : 
    1021              :         info!("found {} timelines", remote_timeline_ids.len(),);
    1022              : 
    1023              :         for k in other_keys {
    1024              :             warn!("Unexpected non timeline key {k}");
    1025              :         }
    1026              : 
    1027              :         Ok(TenantPreload {
    1028              :             timelines: Self::load_timeline_metadata(
    1029              :                 self,
    1030              :                 remote_timeline_ids,
    1031              :                 remote_storage,
    1032              :                 cancel,
    1033              :             )
    1034              :             .await?,
    1035              :         })
    1036              :     }
    1037              : 
    1038              :     ///
    1039              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1040              :     ///
    1041              :     /// No background tasks are started as part of this routine.
    1042              :     ///
    1043          564 :     async fn attach(
    1044          564 :         self: &Arc<Tenant>,
    1045          564 :         preload: Option<TenantPreload>,
    1046          564 :         ctx: &RequestContext,
    1047          564 :     ) -> anyhow::Result<()> {
    1048          564 :         span::debug_assert_current_span_has_tenant_id();
    1049          564 : 
    1050          564 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1051              : 
    1052          564 :         let Some(preload) = preload else {
    1053            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1054              :         };
    1055              : 
    1056          564 :         let mut timelines_to_resume_deletions = vec![];
    1057          564 : 
    1058          564 :         let mut remote_index_and_client = HashMap::new();
    1059          564 :         let mut timeline_ancestors = HashMap::new();
    1060          564 :         let mut existent_timelines = HashSet::new();
    1061          582 :         for (timeline_id, preload) in preload.timelines {
    1062           18 :             let index_part = match preload.index_part {
    1063           18 :                 Ok(i) => {
    1064           18 :                     debug!("remote index part exists for timeline {timeline_id}");
    1065              :                     // We found index_part on the remote, this is the standard case.
    1066           18 :                     existent_timelines.insert(timeline_id);
    1067           18 :                     i
    1068              :                 }
    1069              :                 Err(DownloadError::NotFound) => {
    1070              :                     // There is no index_part on the remote. We only get here
    1071              :                     // if there is some prefix for the timeline in the remote storage.
    1072              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1073              :                     // remnant from a prior incomplete creation or deletion attempt.
    1074              :                     // Delete the local directory as the deciding criterion for a
    1075              :                     // timeline's existence is presence of index_part.
    1076            0 :                     info!(%timeline_id, "index_part not found on remote");
    1077            0 :                     continue;
    1078              :                 }
    1079            0 :                 Err(e) => {
    1080            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1081            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1082            0 :                     // as it might be a temporary issue and we don't want to re-download
    1083            0 :                     // everything after it resolves.
    1084            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1085              : 
    1086            0 :                     existent_timelines.insert(timeline_id);
    1087            0 :                     continue;
    1088              :                 }
    1089              :             };
    1090           18 :             match index_part {
    1091           18 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1092           18 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1093           18 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1094           18 :                 }
    1095            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1096            0 :                     info!(
    1097            0 :                         "timeline {} is deleted, picking to resume deletion",
    1098              :                         timeline_id
    1099              :                     );
    1100            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1101              :                 }
    1102              :             }
    1103              :         }
    1104              : 
    1105          564 :         let mut gc_blocks = HashMap::new();
    1106              : 
    1107              :         // For every timeline, download the metadata file, scan the local directory,
    1108              :         // and build a layer map that contains an entry for each remote and local
    1109              :         // layer file.
    1110          564 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1111          582 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1112           18 :             let (index_part, remote_client) = remote_index_and_client
    1113           18 :                 .remove(&timeline_id)
    1114           18 :                 .expect("just put it in above");
    1115              : 
    1116           18 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1117              :                 // could just filter these away, but it helps while testing
    1118            0 :                 anyhow::ensure!(
    1119            0 :                     !blocking.reasons.is_empty(),
    1120            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1121              :                 );
    1122            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1123            0 :                 assert!(prev.is_none());
    1124           18 :             }
    1125              : 
    1126              :             // TODO again handle early failure
    1127           18 :             self.load_remote_timeline(
    1128           18 :                 timeline_id,
    1129           18 :                 index_part,
    1130           18 :                 remote_metadata,
    1131           18 :                 TimelineResources {
    1132           18 :                     remote_client,
    1133           18 :                     timeline_get_throttle: self.timeline_get_throttle.clone(),
    1134           18 :                     l0_flush_global_state: self.l0_flush_global_state.clone(),
    1135           18 :                 },
    1136           18 :                 ctx,
    1137           18 :             )
    1138           28 :             .await
    1139           18 :             .with_context(|| {
    1140            0 :                 format!(
    1141            0 :                     "failed to load remote timeline {} for tenant {}",
    1142            0 :                     timeline_id, self.tenant_shard_id
    1143            0 :                 )
    1144           18 :             })?;
    1145              :         }
    1146              : 
    1147              :         // Walk through deleted timelines, resume deletion
    1148          564 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1149            0 :             remote_timeline_client
    1150            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1151            0 :                 .context("init queue stopped")
    1152            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1153              : 
    1154            0 :             DeleteTimelineFlow::resume_deletion(
    1155            0 :                 Arc::clone(self),
    1156            0 :                 timeline_id,
    1157            0 :                 &index_part.metadata,
    1158            0 :                 remote_timeline_client,
    1159            0 :             )
    1160            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1161            0 :             .await
    1162            0 :             .context("resume_deletion")
    1163            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1164              :         }
    1165              : 
    1166              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1167              :         // IndexPart is the source of truth.
    1168          564 :         self.clean_up_timelines(&existent_timelines)?;
    1169              : 
    1170          564 :         self.gc_block.set_scanned(gc_blocks);
    1171          564 : 
    1172          564 :         fail::fail_point!("attach-before-activate", |_| {
    1173            0 :             anyhow::bail!("attach-before-activate");
    1174          564 :         });
    1175          564 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1176              : 
    1177          564 :         info!("Done");
    1178              : 
    1179          564 :         Ok(())
    1180          564 :     }
    1181              : 
    1182              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1183              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1184              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1185          564 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1186          564 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1187              : 
    1188          564 :         let entries = match timelines_dir.read_dir_utf8() {
    1189          564 :             Ok(d) => d,
    1190            0 :             Err(e) => {
    1191            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1192            0 :                     return Ok(());
    1193              :                 } else {
    1194            0 :                     return Err(e).context("list timelines directory for tenant");
    1195              :                 }
    1196              :             }
    1197              :         };
    1198              : 
    1199          588 :         for entry in entries {
    1200           24 :             let entry = entry.context("read timeline dir entry")?;
    1201           24 :             let entry_path = entry.path();
    1202              : 
    1203           24 :             let purge = if crate::is_temporary(entry_path)
    1204              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1205           24 :                 || is_uninit_mark(entry_path)
    1206           24 :                 || crate::is_delete_mark(entry_path)
    1207              :             {
    1208            0 :                 true
    1209              :             } else {
    1210           24 :                 match TimelineId::try_from(entry_path.file_name()) {
    1211           24 :                     Ok(i) => {
    1212           24 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1213           24 :                         !existent_timelines.contains(&i)
    1214              :                     }
    1215            0 :                     Err(e) => {
    1216            0 :                         tracing::warn!(
    1217            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1218              :                         );
    1219              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1220            0 :                         false
    1221              :                     }
    1222              :                 }
    1223              :             };
    1224              : 
    1225           24 :             if purge {
    1226            6 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1227            6 :                 if let Err(e) = match entry.file_type() {
    1228            6 :                     Ok(t) => if t.is_dir() {
    1229            6 :                         std::fs::remove_dir_all(entry_path)
    1230              :                     } else {
    1231            0 :                         std::fs::remove_file(entry_path)
    1232              :                     }
    1233            6 :                     .or_else(fs_ext::ignore_not_found),
    1234            0 :                     Err(e) => Err(e),
    1235              :                 } {
    1236            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1237            6 :                 }
    1238           18 :             }
    1239              :         }
    1240              : 
    1241          564 :         Ok(())
    1242          564 :     }
    1243              : 
    1244              :     /// Get sum of all remote timelines sizes
    1245              :     ///
    1246              :     /// This function relies on the index_part instead of listing the remote storage
    1247            0 :     pub fn remote_size(&self) -> u64 {
    1248            0 :         let mut size = 0;
    1249              : 
    1250            0 :         for timeline in self.list_timelines() {
    1251            0 :             size += timeline.remote_client.get_remote_physical_size();
    1252            0 :         }
    1253              : 
    1254            0 :         size
    1255            0 :     }
    1256              : 
    1257           36 :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1258              :     async fn load_remote_timeline(
    1259              :         &self,
    1260              :         timeline_id: TimelineId,
    1261              :         index_part: IndexPart,
    1262              :         remote_metadata: TimelineMetadata,
    1263              :         resources: TimelineResources,
    1264              :         ctx: &RequestContext,
    1265              :     ) -> anyhow::Result<()> {
    1266              :         span::debug_assert_current_span_has_tenant_id();
    1267              : 
    1268              :         info!("downloading index file for timeline {}", timeline_id);
    1269              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1270              :             .await
    1271              :             .context("Failed to create new timeline directory")?;
    1272              : 
    1273              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1274              :             let timelines = self.timelines.lock().unwrap();
    1275              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1276            0 :                 || {
    1277            0 :                     anyhow::anyhow!(
    1278            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1279            0 :                     )
    1280            0 :                 },
    1281              :             )?))
    1282              :         } else {
    1283              :             None
    1284              :         };
    1285              : 
    1286              :         let last_aux_file_policy = index_part.last_aux_file_policy();
    1287              : 
    1288              :         self.timeline_init_and_sync(
    1289              :             timeline_id,
    1290              :             resources,
    1291              :             Some(index_part),
    1292              :             remote_metadata,
    1293              :             ancestor,
    1294              :             last_aux_file_policy,
    1295              :             ctx,
    1296              :         )
    1297              :         .await
    1298              :     }
    1299              : 
    1300          564 :     async fn load_timeline_metadata(
    1301          564 :         self: &Arc<Tenant>,
    1302          564 :         timeline_ids: HashSet<TimelineId>,
    1303          564 :         remote_storage: &GenericRemoteStorage,
    1304          564 :         cancel: CancellationToken,
    1305          564 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1306          564 :         let mut part_downloads = JoinSet::new();
    1307          582 :         for timeline_id in timeline_ids {
    1308           18 :             let client = RemoteTimelineClient::new(
    1309           18 :                 remote_storage.clone(),
    1310           18 :                 self.deletion_queue_client.clone(),
    1311           18 :                 self.conf,
    1312           18 :                 self.tenant_shard_id,
    1313           18 :                 timeline_id,
    1314           18 :                 self.generation,
    1315           18 :             );
    1316           18 :             let cancel_clone = cancel.clone();
    1317           18 :             part_downloads.spawn(
    1318           18 :                 async move {
    1319           18 :                     debug!("starting index part download");
    1320              : 
    1321           71 :                     let index_part = client.download_index_file(&cancel_clone).await;
    1322              : 
    1323           18 :                     debug!("finished index part download");
    1324              : 
    1325           18 :                     Result::<_, anyhow::Error>::Ok(TimelinePreload {
    1326           18 :                         client,
    1327           18 :                         timeline_id,
    1328           18 :                         index_part,
    1329           18 :                     })
    1330           18 :                 }
    1331           18 :                 .map(move |res| {
    1332           18 :                     res.with_context(|| format!("download index part for timeline {timeline_id}"))
    1333           18 :                 })
    1334           18 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1335              :             );
    1336              :         }
    1337              : 
    1338          564 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1339              : 
    1340          582 :         loop {
    1341          582 :             tokio::select!(
    1342              :                 next = part_downloads.join_next() => {
    1343              :                     match next {
    1344              :                         Some(result) => {
    1345              :                             let preload_result = result.context("join preload task")?;
    1346              :                             let preload = preload_result?;
    1347              :                             timeline_preloads.insert(preload.timeline_id, preload);
    1348              :                         },
    1349              :                         None => {
    1350              :                             break;
    1351              :                         }
    1352              :                     }
    1353              :                 },
    1354              :                 _ = cancel.cancelled() => {
    1355              :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1356              :                 }
    1357          582 :             )
    1358          582 :         }
    1359              : 
    1360          564 :         Ok(timeline_preloads)
    1361          564 :     }
    1362              : 
    1363            0 :     pub(crate) async fn apply_timeline_archival_config(
    1364            0 :         &self,
    1365            0 :         timeline_id: TimelineId,
    1366            0 :         state: TimelineArchivalState,
    1367            0 :     ) -> Result<(), TimelineArchivalError> {
    1368            0 :         info!("setting timeline archival config");
    1369            0 :         let timeline = {
    1370            0 :             let timelines = self.timelines.lock().unwrap();
    1371              : 
    1372            0 :             let timeline = match timelines.get(&timeline_id) {
    1373            0 :                 Some(t) => t,
    1374            0 :                 None => return Err(TimelineArchivalError::NotFound),
    1375              :             };
    1376              : 
    1377              :             // Ensure that there are no non-archived child timelines
    1378            0 :             let children: Vec<TimelineId> = timelines
    1379            0 :                 .iter()
    1380            0 :                 .filter_map(|(id, entry)| {
    1381            0 :                     if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1382            0 :                         return None;
    1383            0 :                     }
    1384            0 :                     if entry.is_archived() == Some(true) {
    1385            0 :                         return None;
    1386            0 :                     }
    1387            0 :                     Some(*id)
    1388            0 :                 })
    1389            0 :                 .collect();
    1390            0 : 
    1391            0 :             if !children.is_empty() && state == TimelineArchivalState::Archived {
    1392            0 :                 return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1393            0 :             }
    1394            0 :             Arc::clone(timeline)
    1395              :         };
    1396              : 
    1397            0 :         let upload_needed = timeline
    1398            0 :             .remote_client
    1399            0 :             .schedule_index_upload_for_timeline_archival_state(state)?;
    1400              : 
    1401            0 :         if upload_needed {
    1402            0 :             info!("Uploading new state");
    1403              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    1404            0 :             let Ok(v) =
    1405            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    1406              :             else {
    1407            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    1408            0 :                 return Err(TimelineArchivalError::Timeout);
    1409              :             };
    1410            0 :             v.map_err(|e| TimelineArchivalError::Other(anyhow::anyhow!(e)))?;
    1411            0 :         }
    1412            0 :         Ok(())
    1413            0 :     }
    1414              : 
    1415           12 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    1416           12 :         self.tenant_shard_id
    1417           12 :     }
    1418              : 
    1419              :     /// Get Timeline handle for given Neon timeline ID.
    1420              :     /// This function is idempotent. It doesn't change internal state in any way.
    1421          666 :     pub fn get_timeline(
    1422          666 :         &self,
    1423          666 :         timeline_id: TimelineId,
    1424          666 :         active_only: bool,
    1425          666 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    1426          666 :         let timelines_accessor = self.timelines.lock().unwrap();
    1427          666 :         let timeline = timelines_accessor
    1428          666 :             .get(&timeline_id)
    1429          666 :             .ok_or(GetTimelineError::NotFound {
    1430          666 :                 tenant_id: self.tenant_shard_id,
    1431          666 :                 timeline_id,
    1432          666 :             })?;
    1433              : 
    1434          660 :         if active_only && !timeline.is_active() {
    1435            0 :             Err(GetTimelineError::NotActive {
    1436            0 :                 tenant_id: self.tenant_shard_id,
    1437            0 :                 timeline_id,
    1438            0 :                 state: timeline.current_state(),
    1439            0 :             })
    1440              :         } else {
    1441          660 :             Ok(Arc::clone(timeline))
    1442              :         }
    1443          666 :     }
    1444              : 
    1445              :     /// Lists timelines the tenant contains.
    1446              :     /// Up to tenant's implementation to omit certain timelines that ar not considered ready for use.
    1447           24 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    1448           24 :         self.timelines
    1449           24 :             .lock()
    1450           24 :             .unwrap()
    1451           24 :             .values()
    1452           24 :             .map(Arc::clone)
    1453           24 :             .collect()
    1454           24 :     }
    1455              : 
    1456            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    1457            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    1458            0 :     }
    1459              : 
    1460              :     /// This is used to create the initial 'main' timeline during bootstrapping,
    1461              :     /// or when importing a new base backup. The caller is expected to load an
    1462              :     /// initial image of the datadir to the new timeline after this.
    1463              :     ///
    1464              :     /// Until that happens, the on-disk state is invalid (disk_consistent_lsn=Lsn(0))
    1465              :     /// and the timeline will fail to load at a restart.
    1466              :     ///
    1467              :     /// For tests, use `DatadirModification::init_empty_test_timeline` + `commit` to setup the
    1468              :     /// minimum amount of keys required to get a writable timeline.
    1469              :     /// (Without it, `put` might fail due to `repartition` failing.)
    1470          540 :     pub(crate) async fn create_empty_timeline(
    1471          540 :         &self,
    1472          540 :         new_timeline_id: TimelineId,
    1473          540 :         initdb_lsn: Lsn,
    1474          540 :         pg_version: u32,
    1475          540 :         _ctx: &RequestContext,
    1476          540 :     ) -> anyhow::Result<UninitializedTimeline> {
    1477          540 :         anyhow::ensure!(
    1478          540 :             self.is_active(),
    1479            0 :             "Cannot create empty timelines on inactive tenant"
    1480              :         );
    1481              : 
    1482              :         // Protect against concurrent attempts to use this TimelineId
    1483          540 :         let create_guard = self.create_timeline_create_guard(new_timeline_id)?;
    1484              : 
    1485          534 :         let new_metadata = TimelineMetadata::new(
    1486          534 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    1487          534 :             // make it valid, before calling finish_creation()
    1488          534 :             Lsn(0),
    1489          534 :             None,
    1490          534 :             None,
    1491          534 :             Lsn(0),
    1492          534 :             initdb_lsn,
    1493          534 :             initdb_lsn,
    1494          534 :             pg_version,
    1495          534 :         );
    1496          534 :         self.prepare_new_timeline(
    1497          534 :             new_timeline_id,
    1498          534 :             &new_metadata,
    1499          534 :             create_guard,
    1500          534 :             initdb_lsn,
    1501          534 :             None,
    1502          534 :             None,
    1503          534 :         )
    1504            0 :         .await
    1505          540 :     }
    1506              : 
    1507              :     /// Helper for unit tests to create an empty timeline.
    1508              :     ///
    1509              :     /// The timeline is has state value `Active` but its background loops are not running.
    1510              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    1511              :     // Our current tests don't need the background loops.
    1512              :     #[cfg(test)]
    1513          510 :     pub async fn create_test_timeline(
    1514          510 :         &self,
    1515          510 :         new_timeline_id: TimelineId,
    1516          510 :         initdb_lsn: Lsn,
    1517          510 :         pg_version: u32,
    1518          510 :         ctx: &RequestContext,
    1519          510 :     ) -> anyhow::Result<Arc<Timeline>> {
    1520          510 :         let uninit_tl = self
    1521          510 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    1522            0 :             .await?;
    1523          510 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    1524          510 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    1525              : 
    1526              :         // Setup minimum keys required for the timeline to be usable.
    1527          510 :         let mut modification = tline.begin_modification(initdb_lsn);
    1528          510 :         modification
    1529          510 :             .init_empty_test_timeline()
    1530          510 :             .context("init_empty_test_timeline")?;
    1531          510 :         modification
    1532          510 :             .commit(ctx)
    1533          492 :             .await
    1534          510 :             .context("commit init_empty_test_timeline modification")?;
    1535              : 
    1536              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    1537          510 :         tline.maybe_spawn_flush_loop();
    1538          510 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    1539              : 
    1540              :         // Make sure the freeze_and_flush reaches remote storage.
    1541          510 :         tline.remote_client.wait_completion().await.unwrap();
    1542              : 
    1543          510 :         let tl = uninit_tl.finish_creation()?;
    1544              :         // The non-test code would call tl.activate() here.
    1545          510 :         tl.set_state(TimelineState::Active);
    1546          510 :         Ok(tl)
    1547          510 :     }
    1548              : 
    1549              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    1550              :     #[cfg(test)]
    1551              :     #[allow(clippy::too_many_arguments)]
    1552           78 :     pub async fn create_test_timeline_with_layers(
    1553           78 :         &self,
    1554           78 :         new_timeline_id: TimelineId,
    1555           78 :         initdb_lsn: Lsn,
    1556           78 :         pg_version: u32,
    1557           78 :         ctx: &RequestContext,
    1558           78 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    1559           78 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    1560           78 :         end_lsn: Lsn,
    1561           78 :     ) -> anyhow::Result<Arc<Timeline>> {
    1562           78 :         let tline = self
    1563           78 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    1564          156 :             .await?;
    1565           78 :         tline.force_advance_lsn(end_lsn);
    1566          234 :         for deltas in delta_layer_desc {
    1567          156 :             tline
    1568          156 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    1569          468 :                 .await?;
    1570              :         }
    1571          204 :         for (lsn, images) in image_layer_desc {
    1572          126 :             tline
    1573          126 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    1574          717 :                 .await?;
    1575              :         }
    1576           78 :         Ok(tline)
    1577           78 :     }
    1578              : 
    1579              :     /// Create a new timeline.
    1580              :     ///
    1581              :     /// Returns the new timeline ID and reference to its Timeline object.
    1582              :     ///
    1583              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    1584              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    1585              :     #[allow(clippy::too_many_arguments)]
    1586            0 :     pub(crate) async fn create_timeline(
    1587            0 :         self: &Arc<Tenant>,
    1588            0 :         new_timeline_id: TimelineId,
    1589            0 :         ancestor_timeline_id: Option<TimelineId>,
    1590            0 :         mut ancestor_start_lsn: Option<Lsn>,
    1591            0 :         pg_version: u32,
    1592            0 :         load_existing_initdb: Option<TimelineId>,
    1593            0 :         broker_client: storage_broker::BrokerClientChannel,
    1594            0 :         ctx: &RequestContext,
    1595            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    1596            0 :         if !self.is_active() {
    1597            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    1598            0 :                 return Err(CreateTimelineError::ShuttingDown);
    1599              :             } else {
    1600            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    1601            0 :                     "Cannot create timelines on inactive tenant"
    1602            0 :                 )));
    1603              :             }
    1604            0 :         }
    1605              : 
    1606            0 :         let _gate = self
    1607            0 :             .gate
    1608            0 :             .enter()
    1609            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    1610              : 
    1611              :         // Get exclusive access to the timeline ID: this ensures that it does not already exist,
    1612              :         // and that no other creation attempts will be allowed in while we are working.
    1613            0 :         let create_guard = match self.create_timeline_create_guard(new_timeline_id) {
    1614            0 :             Ok(m) => m,
    1615              :             Err(TimelineExclusionError::AlreadyCreating) => {
    1616              :                 // Creation is in progress, we cannot create it again, and we cannot
    1617              :                 // check if this request matches the existing one, so caller must try
    1618              :                 // again later.
    1619            0 :                 return Err(CreateTimelineError::AlreadyCreating);
    1620              :             }
    1621            0 :             Err(TimelineExclusionError::Other(e)) => {
    1622            0 :                 return Err(CreateTimelineError::Other(e));
    1623              :             }
    1624            0 :             Err(TimelineExclusionError::AlreadyExists(existing)) => {
    1625            0 :                 debug!("timeline {new_timeline_id} already exists");
    1626              : 
    1627              :                 // Idempotency: creating the same timeline twice is not an error, unless
    1628              :                 // the second creation has different parameters.
    1629            0 :                 if existing.get_ancestor_timeline_id() != ancestor_timeline_id
    1630            0 :                     || existing.pg_version != pg_version
    1631            0 :                     || (ancestor_start_lsn.is_some()
    1632            0 :                         && ancestor_start_lsn != Some(existing.get_ancestor_lsn()))
    1633              :                 {
    1634            0 :                     return Err(CreateTimelineError::Conflict);
    1635            0 :                 }
    1636            0 : 
    1637            0 :                 // Wait for uploads to complete, so that when we return Ok, the timeline
    1638            0 :                 // is known to be durable on remote storage. Just like we do at the end of
    1639            0 :                 // this function, after we have created the timeline ourselves.
    1640            0 :                 //
    1641            0 :                 // We only really care that the initial version of `index_part.json` has
    1642            0 :                 // been uploaded. That's enough to remember that the timeline
    1643            0 :                 // exists. However, there is no function to wait specifically for that so
    1644            0 :                 // we just wait for all in-progress uploads to finish.
    1645            0 :                 existing
    1646            0 :                     .remote_client
    1647            0 :                     .wait_completion()
    1648            0 :                     .await
    1649            0 :                     .context("wait for timeline uploads to complete")?;
    1650              : 
    1651            0 :                 return Ok(existing);
    1652              :             }
    1653              :         };
    1654              : 
    1655              :         pausable_failpoint!("timeline-creation-after-uninit");
    1656              : 
    1657            0 :         let loaded_timeline = match ancestor_timeline_id {
    1658            0 :             Some(ancestor_timeline_id) => {
    1659            0 :                 let ancestor_timeline = self
    1660            0 :                     .get_timeline(ancestor_timeline_id, false)
    1661            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    1662              : 
    1663              :                 // instead of waiting around, just deny the request because ancestor is not yet
    1664              :                 // ready for other purposes either.
    1665            0 :                 if !ancestor_timeline.is_active() {
    1666            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    1667            0 :                 }
    1668              : 
    1669            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    1670            0 :                     *lsn = lsn.align();
    1671            0 : 
    1672            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    1673            0 :                     if ancestor_ancestor_lsn > *lsn {
    1674              :                         // can we safely just branch from the ancestor instead?
    1675            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    1676            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    1677            0 :                             lsn,
    1678            0 :                             ancestor_timeline_id,
    1679            0 :                             ancestor_ancestor_lsn,
    1680            0 :                         )));
    1681            0 :                     }
    1682            0 : 
    1683            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    1684            0 :                     // to the requested branch point. The repository code itself doesn't
    1685            0 :                     // require it, but if we start to receive WAL on the new timeline,
    1686            0 :                     // decoding the new WAL might need to look up previous pages, relation
    1687            0 :                     // sizes etc. and that would get confused if the previous page versions
    1688            0 :                     // are not in the repository yet.
    1689            0 :                     ancestor_timeline
    1690            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    1691            0 :                         .await
    1692            0 :                         .map_err(|e| match e {
    1693            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    1694            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    1695              :                             }
    1696            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    1697            0 :                         })?;
    1698            0 :                 }
    1699              : 
    1700            0 :                 self.branch_timeline(
    1701            0 :                     &ancestor_timeline,
    1702            0 :                     new_timeline_id,
    1703            0 :                     ancestor_start_lsn,
    1704            0 :                     create_guard,
    1705            0 :                     ctx,
    1706            0 :                 )
    1707            0 :                 .await?
    1708              :             }
    1709              :             None => {
    1710            0 :                 self.bootstrap_timeline(
    1711            0 :                     new_timeline_id,
    1712            0 :                     pg_version,
    1713            0 :                     load_existing_initdb,
    1714            0 :                     create_guard,
    1715            0 :                     ctx,
    1716            0 :                 )
    1717            0 :                 .await?
    1718              :             }
    1719              :         };
    1720              : 
    1721              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    1722              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    1723              :         // not send a success to the caller until it is.  The same applies to handling retries,
    1724              :         // see the handling of [`TimelineExclusionError::AlreadyExists`] above.
    1725            0 :         let kind = ancestor_timeline_id
    1726            0 :             .map(|_| "branched")
    1727            0 :             .unwrap_or("bootstrapped");
    1728            0 :         loaded_timeline
    1729            0 :             .remote_client
    1730            0 :             .wait_completion()
    1731            0 :             .await
    1732            0 :             .with_context(|| format!("wait for {} timeline initial uploads to complete", kind))?;
    1733              : 
    1734            0 :         loaded_timeline.activate(self.clone(), broker_client, None, ctx);
    1735            0 : 
    1736            0 :         Ok(loaded_timeline)
    1737            0 :     }
    1738              : 
    1739            0 :     pub(crate) async fn delete_timeline(
    1740            0 :         self: Arc<Self>,
    1741            0 :         timeline_id: TimelineId,
    1742            0 :     ) -> Result<(), DeleteTimelineError> {
    1743            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    1744              : 
    1745            0 :         Ok(())
    1746            0 :     }
    1747              : 
    1748              :     /// perform one garbage collection iteration, removing old data files from disk.
    1749              :     /// this function is periodically called by gc task.
    1750              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    1751              :     ///
    1752              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    1753              :     ///
    1754              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    1755              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    1756              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    1757              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    1758              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    1759              :     /// requires more history to be retained.
    1760              :     //
    1761         2262 :     pub(crate) async fn gc_iteration(
    1762         2262 :         &self,
    1763         2262 :         target_timeline_id: Option<TimelineId>,
    1764         2262 :         horizon: u64,
    1765         2262 :         pitr: Duration,
    1766         2262 :         cancel: &CancellationToken,
    1767         2262 :         ctx: &RequestContext,
    1768         2262 :     ) -> Result<GcResult, GcError> {
    1769         2262 :         // Don't start doing work during shutdown
    1770         2262 :         if let TenantState::Stopping { .. } = self.current_state() {
    1771            0 :             return Ok(GcResult::default());
    1772         2262 :         }
    1773         2262 : 
    1774         2262 :         // there is a global allowed_error for this
    1775         2262 :         if !self.is_active() {
    1776            0 :             return Err(GcError::NotActive);
    1777         2262 :         }
    1778         2262 : 
    1779         2262 :         {
    1780         2262 :             let conf = self.tenant_conf.load();
    1781         2262 : 
    1782         2262 :             if !conf.location.may_delete_layers_hint() {
    1783            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    1784            0 :                 return Ok(GcResult::default());
    1785         2262 :             }
    1786              :         }
    1787              : 
    1788         2262 :         let _guard = match self.gc_block.start().await {
    1789         2262 :             Ok(guard) => guard,
    1790            0 :             Err(reasons) => {
    1791            0 :                 info!("Skipping GC: {reasons}");
    1792            0 :                 return Ok(GcResult::default());
    1793              :             }
    1794              :         };
    1795              : 
    1796         2262 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    1797         2171 :             .await
    1798         2262 :     }
    1799              : 
    1800              :     /// Perform one compaction iteration.
    1801              :     /// This function is periodically called by compactor task.
    1802              :     /// Also it can be explicitly requested per timeline through page server
    1803              :     /// api's 'compact' command.
    1804              :     ///
    1805              :     /// Returns whether we have pending compaction task.
    1806            0 :     async fn compaction_iteration(
    1807            0 :         &self,
    1808            0 :         cancel: &CancellationToken,
    1809            0 :         ctx: &RequestContext,
    1810            0 :     ) -> Result<bool, timeline::CompactionError> {
    1811            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    1812            0 :         if !self.is_active() {
    1813            0 :             return Ok(false);
    1814            0 :         }
    1815            0 : 
    1816            0 :         {
    1817            0 :             let conf = self.tenant_conf.load();
    1818            0 :             if !conf.location.may_delete_layers_hint() || !conf.location.may_upload_layers_hint() {
    1819            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    1820            0 :                 return Ok(false);
    1821            0 :             }
    1822            0 :         }
    1823            0 : 
    1824            0 :         // Scan through the hashmap and collect a list of all the timelines,
    1825            0 :         // while holding the lock. Then drop the lock and actually perform the
    1826            0 :         // compactions.  We don't want to block everything else while the
    1827            0 :         // compaction runs.
    1828            0 :         let timelines_to_compact = {
    1829            0 :             let timelines = self.timelines.lock().unwrap();
    1830            0 :             let timelines_to_compact = timelines
    1831            0 :                 .iter()
    1832            0 :                 .filter_map(|(timeline_id, timeline)| {
    1833            0 :                     if timeline.is_active() {
    1834            0 :                         Some((*timeline_id, timeline.clone()))
    1835              :                     } else {
    1836            0 :                         None
    1837              :                     }
    1838            0 :                 })
    1839            0 :                 .collect::<Vec<_>>();
    1840            0 :             drop(timelines);
    1841            0 :             timelines_to_compact
    1842            0 :         };
    1843            0 : 
    1844            0 :         // Before doing any I/O work, check our circuit breaker
    1845            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    1846            0 :             info!("Skipping compaction due to previous failures");
    1847            0 :             return Ok(false);
    1848            0 :         }
    1849            0 : 
    1850            0 :         let mut has_pending_task = false;
    1851              : 
    1852            0 :         for (timeline_id, timeline) in &timelines_to_compact {
    1853            0 :             has_pending_task |= timeline
    1854            0 :                 .compact(cancel, EnumSet::empty(), ctx)
    1855            0 :                 .instrument(info_span!("compact_timeline", %timeline_id))
    1856            0 :                 .await
    1857            0 :                 .inspect_err(|e| match e {
    1858            0 :                     timeline::CompactionError::ShuttingDown => (),
    1859            0 :                     timeline::CompactionError::Other(e) => {
    1860            0 :                         self.compaction_circuit_breaker
    1861            0 :                             .lock()
    1862            0 :                             .unwrap()
    1863            0 :                             .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    1864            0 :                     }
    1865            0 :                 })?;
    1866              :         }
    1867              : 
    1868            0 :         self.compaction_circuit_breaker
    1869            0 :             .lock()
    1870            0 :             .unwrap()
    1871            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    1872            0 : 
    1873            0 :         Ok(has_pending_task)
    1874            0 :     }
    1875              : 
    1876              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    1877              :     // this happens during ingest: this background housekeeping is for freezing layers
    1878              :     // that are open but haven't been written to for some time.
    1879            0 :     async fn ingest_housekeeping(&self) {
    1880            0 :         // Scan through the hashmap and collect a list of all the timelines,
    1881            0 :         // while holding the lock. Then drop the lock and actually perform the
    1882            0 :         // compactions.  We don't want to block everything else while the
    1883            0 :         // compaction runs.
    1884            0 :         let timelines = {
    1885            0 :             self.timelines
    1886            0 :                 .lock()
    1887            0 :                 .unwrap()
    1888            0 :                 .values()
    1889            0 :                 .filter_map(|timeline| {
    1890            0 :                     if timeline.is_active() {
    1891            0 :                         Some(timeline.clone())
    1892              :                     } else {
    1893            0 :                         None
    1894              :                     }
    1895            0 :                 })
    1896            0 :                 .collect::<Vec<_>>()
    1897              :         };
    1898              : 
    1899            0 :         for timeline in &timelines {
    1900            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    1901              :         }
    1902            0 :     }
    1903              : 
    1904         7344 :     pub fn current_state(&self) -> TenantState {
    1905         7344 :         self.state.borrow().clone()
    1906         7344 :     }
    1907              : 
    1908         5064 :     pub fn is_active(&self) -> bool {
    1909         5064 :         self.current_state() == TenantState::Active
    1910         5064 :     }
    1911              : 
    1912            0 :     pub fn generation(&self) -> Generation {
    1913            0 :         self.generation
    1914            0 :     }
    1915              : 
    1916            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    1917            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    1918            0 :     }
    1919              : 
    1920              :     /// Changes tenant status to active, unless shutdown was already requested.
    1921              :     ///
    1922              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    1923              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    1924            0 :     fn activate(
    1925            0 :         self: &Arc<Self>,
    1926            0 :         broker_client: BrokerClientChannel,
    1927            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    1928            0 :         ctx: &RequestContext,
    1929            0 :     ) {
    1930            0 :         span::debug_assert_current_span_has_tenant_id();
    1931            0 : 
    1932            0 :         let mut activating = false;
    1933            0 :         self.state.send_modify(|current_state| {
    1934            0 :             use pageserver_api::models::ActivatingFrom;
    1935            0 :             match &*current_state {
    1936              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    1937            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    1938              :                 }
    1939            0 :                 TenantState::Loading => {
    1940            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Loading);
    1941            0 :                 }
    1942            0 :                 TenantState::Attaching => {
    1943            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    1944            0 :                 }
    1945              :             }
    1946            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    1947            0 :             activating = true;
    1948            0 :             // Continue outside the closure. We need to grab timelines.lock()
    1949            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    1950            0 :         });
    1951            0 : 
    1952            0 :         if activating {
    1953            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    1954            0 :             let timelines_to_activate = timelines_accessor
    1955            0 :                 .values()
    1956            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    1957            0 : 
    1958            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    1959            0 :             self.initialize_gc_info(&timelines_accessor);
    1960            0 : 
    1961            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    1962            0 :             // down when they notice that the tenant is inactive.
    1963            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    1964            0 : 
    1965            0 :             let mut activated_timelines = 0;
    1966              : 
    1967            0 :             for timeline in timelines_to_activate {
    1968            0 :                 timeline.activate(
    1969            0 :                     self.clone(),
    1970            0 :                     broker_client.clone(),
    1971            0 :                     background_jobs_can_start,
    1972            0 :                     ctx,
    1973            0 :                 );
    1974            0 :                 activated_timelines += 1;
    1975            0 :             }
    1976              : 
    1977            0 :             self.state.send_modify(move |current_state| {
    1978            0 :                 assert!(
    1979            0 :                     matches!(current_state, TenantState::Activating(_)),
    1980            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    1981              :                 );
    1982            0 :                 *current_state = TenantState::Active;
    1983            0 : 
    1984            0 :                 let elapsed = self.constructed_at.elapsed();
    1985            0 :                 let total_timelines = timelines_accessor.len();
    1986            0 : 
    1987            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    1988            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    1989            0 :                 info!(
    1990            0 :                     since_creation_millis = elapsed.as_millis(),
    1991            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    1992            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    1993            0 :                     activated_timelines,
    1994            0 :                     total_timelines,
    1995            0 :                     post_state = <&'static str>::from(&*current_state),
    1996            0 :                     "activation attempt finished"
    1997              :                 );
    1998              : 
    1999            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    2000            0 :             });
    2001            0 :         }
    2002            0 :     }
    2003              : 
    2004              :     /// Shutdown the tenant and join all of the spawned tasks.
    2005              :     ///
    2006              :     /// The method caters for all use-cases:
    2007              :     /// - pageserver shutdown (freeze_and_flush == true)
    2008              :     /// - detach + ignore (freeze_and_flush == false)
    2009              :     ///
    2010              :     /// This will attempt to shutdown even if tenant is broken.
    2011              :     ///
    2012              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    2013              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    2014              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    2015              :     /// the ongoing shutdown.
    2016           18 :     async fn shutdown(
    2017           18 :         &self,
    2018           18 :         shutdown_progress: completion::Barrier,
    2019           18 :         shutdown_mode: timeline::ShutdownMode,
    2020           18 :     ) -> Result<(), completion::Barrier> {
    2021           18 :         span::debug_assert_current_span_has_tenant_id();
    2022              : 
    2023              :         // Set tenant (and its timlines) to Stoppping state.
    2024              :         //
    2025              :         // Since we can only transition into Stopping state after activation is complete,
    2026              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    2027              :         //
    2028              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    2029              :         // 1. Lock out any new requests to the tenants.
    2030              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    2031              :         // 3. Signal cancellation for other tenant background loops.
    2032              :         // 4. ???
    2033              :         //
    2034              :         // The waiting for the cancellation is not done uniformly.
    2035              :         // We certainly wait for WAL receivers to shut down.
    2036              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    2037              :         // But the tenant background loops are joined-on in our caller.
    2038              :         // It's mesed up.
    2039              :         // we just ignore the failure to stop
    2040              : 
    2041              :         // If we're still attaching, fire the cancellation token early to drop out: this
    2042              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    2043              :         // is very slow.
    2044           18 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    2045            0 :             self.cancel.cancel();
    2046            0 : 
    2047            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    2048            0 :             // are children of ours, so their flush loops will have shut down already
    2049            0 :             timeline::ShutdownMode::Hard
    2050              :         } else {
    2051           18 :             shutdown_mode
    2052              :         };
    2053              : 
    2054           18 :         match self.set_stopping(shutdown_progress, false, false).await {
    2055           18 :             Ok(()) => {}
    2056            0 :             Err(SetStoppingError::Broken) => {
    2057            0 :                 // assume that this is acceptable
    2058            0 :             }
    2059            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    2060            0 :                 // give caller the option to wait for this this shutdown
    2061            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    2062            0 :                 return Err(other);
    2063              :             }
    2064              :         };
    2065              : 
    2066           18 :         let mut js = tokio::task::JoinSet::new();
    2067           18 :         {
    2068           18 :             let timelines = self.timelines.lock().unwrap();
    2069           18 :             timelines.values().for_each(|timeline| {
    2070           18 :                 let timeline = Arc::clone(timeline);
    2071           18 :                 let timeline_id = timeline.timeline_id;
    2072           18 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    2073           37 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    2074           18 :             })
    2075           18 :         };
    2076           18 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    2077           18 :         tracing::info!("Waiting for timelines...");
    2078           36 :         while let Some(res) = js.join_next().await {
    2079            0 :             match res {
    2080           18 :                 Ok(()) => {}
    2081            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    2082            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    2083            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    2084              :             }
    2085              :         }
    2086              : 
    2087              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    2088              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    2089           18 :         tracing::debug!("Cancelling CancellationToken");
    2090           18 :         self.cancel.cancel();
    2091           18 : 
    2092           18 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    2093           18 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    2094           18 :         //
    2095           18 :         // this will additionally shutdown and await all timeline tasks.
    2096           18 :         tracing::debug!("Waiting for tasks...");
    2097           18 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    2098              : 
    2099           18 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    2100           18 :             walredo_mgr.shutdown().await;
    2101            0 :         }
    2102              : 
    2103              :         // Wait for any in-flight operations to complete
    2104           18 :         self.gate.close().await;
    2105              : 
    2106           18 :         remove_tenant_metrics(&self.tenant_shard_id);
    2107           18 : 
    2108           18 :         Ok(())
    2109           18 :     }
    2110              : 
    2111              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    2112              :     ///
    2113              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    2114              :     ///
    2115              :     /// This function is not cancel-safe!
    2116              :     ///
    2117              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    2118              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    2119           18 :     async fn set_stopping(
    2120           18 :         &self,
    2121           18 :         progress: completion::Barrier,
    2122           18 :         allow_transition_from_loading: bool,
    2123           18 :         allow_transition_from_attaching: bool,
    2124           18 :     ) -> Result<(), SetStoppingError> {
    2125           18 :         let mut rx = self.state.subscribe();
    2126           18 : 
    2127           18 :         // cannot stop before we're done activating, so wait out until we're done activating
    2128           18 :         rx.wait_for(|state| match state {
    2129            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    2130              :             TenantState::Activating(_) | TenantState::Attaching => {
    2131            0 :                 info!(
    2132            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    2133            0 :                     <&'static str>::from(state)
    2134              :                 );
    2135            0 :                 false
    2136              :             }
    2137            0 :             TenantState::Loading => allow_transition_from_loading,
    2138           18 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    2139           18 :         })
    2140            0 :         .await
    2141           18 :         .expect("cannot drop self.state while on a &self method");
    2142           18 : 
    2143           18 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    2144           18 :         let mut err = None;
    2145           18 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    2146              :             TenantState::Activating(_) => {
    2147            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    2148              :             }
    2149              :             TenantState::Attaching => {
    2150            0 :                 if !allow_transition_from_attaching {
    2151            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    2152            0 :                 };
    2153            0 :                 *current_state = TenantState::Stopping { progress };
    2154            0 :                 true
    2155              :             }
    2156              :             TenantState::Loading => {
    2157            0 :                 if !allow_transition_from_loading {
    2158            0 :                     unreachable!("3we ensured above that we're done with activation, and, there is no re-activation")
    2159            0 :                 };
    2160            0 :                 *current_state = TenantState::Stopping { progress };
    2161            0 :                 true
    2162              :             }
    2163              :             TenantState::Active => {
    2164              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    2165              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    2166              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    2167           18 :                 *current_state = TenantState::Stopping { progress };
    2168           18 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    2169           18 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    2170           18 :                 true
    2171              :             }
    2172            0 :             TenantState::Broken { reason, .. } => {
    2173            0 :                 info!(
    2174            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    2175              :                 );
    2176            0 :                 err = Some(SetStoppingError::Broken);
    2177            0 :                 false
    2178              :             }
    2179            0 :             TenantState::Stopping { progress } => {
    2180            0 :                 info!("Tenant is already in Stopping state");
    2181            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    2182            0 :                 false
    2183              :             }
    2184           18 :         });
    2185           18 :         match (stopping, err) {
    2186           18 :             (true, None) => {} // continue
    2187            0 :             (false, Some(err)) => return Err(err),
    2188            0 :             (true, Some(_)) => unreachable!(
    2189            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    2190            0 :             ),
    2191            0 :             (false, None) => unreachable!(
    2192            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    2193            0 :             ),
    2194              :         }
    2195              : 
    2196           18 :         let timelines_accessor = self.timelines.lock().unwrap();
    2197           18 :         let not_broken_timelines = timelines_accessor
    2198           18 :             .values()
    2199           18 :             .filter(|timeline| !timeline.is_broken());
    2200           36 :         for timeline in not_broken_timelines {
    2201           18 :             timeline.set_state(TimelineState::Stopping);
    2202           18 :         }
    2203           18 :         Ok(())
    2204           18 :     }
    2205              : 
    2206              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    2207              :     /// `remove_tenant_from_memory`
    2208              :     ///
    2209              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    2210              :     ///
    2211              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    2212            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    2213            0 :         let mut rx = self.state.subscribe();
    2214            0 : 
    2215            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    2216            0 :         // So, wait until it's done.
    2217            0 :         rx.wait_for(|state| match state {
    2218              :             TenantState::Activating(_) | TenantState::Loading | TenantState::Attaching => {
    2219            0 :                 info!(
    2220            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    2221            0 :                     <&'static str>::from(state)
    2222              :                 );
    2223            0 :                 false
    2224              :             }
    2225            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    2226            0 :         })
    2227            0 :         .await
    2228            0 :         .expect("cannot drop self.state while on a &self method");
    2229            0 : 
    2230            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    2231            0 :         self.set_broken_no_wait(reason)
    2232            0 :     }
    2233              : 
    2234            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    2235            0 :         let reason = reason.to_string();
    2236            0 :         self.state.send_modify(|current_state| {
    2237            0 :             match *current_state {
    2238              :                 TenantState::Activating(_) | TenantState::Loading | TenantState::Attaching => {
    2239            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    2240              :                 }
    2241              :                 TenantState::Active => {
    2242            0 :                     if cfg!(feature = "testing") {
    2243            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    2244            0 :                         *current_state = TenantState::broken_from_reason(reason);
    2245              :                     } else {
    2246            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    2247              :                     }
    2248              :                 }
    2249              :                 TenantState::Broken { .. } => {
    2250            0 :                     warn!("Tenant is already in Broken state");
    2251              :                 }
    2252              :                 // This is the only "expected" path, any other path is a bug.
    2253              :                 TenantState::Stopping { .. } => {
    2254            0 :                     warn!(
    2255            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    2256              :                         reason
    2257              :                     );
    2258            0 :                     *current_state = TenantState::broken_from_reason(reason);
    2259              :                 }
    2260              :            }
    2261            0 :         });
    2262            0 :     }
    2263              : 
    2264            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    2265            0 :         self.state.subscribe()
    2266            0 :     }
    2267              : 
    2268              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    2269              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    2270            0 :     pub(crate) fn activate_now(&self) {
    2271            0 :         self.activate_now_sem.add_permits(1);
    2272            0 :     }
    2273              : 
    2274            0 :     pub(crate) async fn wait_to_become_active(
    2275            0 :         &self,
    2276            0 :         timeout: Duration,
    2277            0 :     ) -> Result<(), GetActiveTenantError> {
    2278            0 :         let mut receiver = self.state.subscribe();
    2279            0 :         loop {
    2280            0 :             let current_state = receiver.borrow_and_update().clone();
    2281            0 :             match current_state {
    2282              :                 TenantState::Loading | TenantState::Attaching | TenantState::Activating(_) => {
    2283              :                     // in these states, there's a chance that we can reach ::Active
    2284            0 :                     self.activate_now();
    2285            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    2286            0 :                         Ok(r) => {
    2287            0 :                             r.map_err(
    2288            0 :                             |_e: tokio::sync::watch::error::RecvError|
    2289              :                                 // Tenant existed but was dropped: report it as non-existent
    2290            0 :                                 GetActiveTenantError::NotFound(GetTenantError::NotFound(self.tenant_shard_id.tenant_id))
    2291            0 :                         )?
    2292              :                         }
    2293              :                         Err(TimeoutCancellableError::Cancelled) => {
    2294            0 :                             return Err(GetActiveTenantError::Cancelled);
    2295              :                         }
    2296              :                         Err(TimeoutCancellableError::Timeout) => {
    2297            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    2298            0 :                                 latest_state: Some(self.current_state()),
    2299            0 :                                 wait_time: timeout,
    2300            0 :                             });
    2301              :                         }
    2302              :                     }
    2303              :                 }
    2304              :                 TenantState::Active { .. } => {
    2305            0 :                     return Ok(());
    2306              :                 }
    2307            0 :                 TenantState::Broken { reason, .. } => {
    2308            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    2309            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    2310            0 :                     return Err(GetActiveTenantError::Broken(reason));
    2311              :                 }
    2312              :                 TenantState::Stopping { .. } => {
    2313              :                     // There's no chance the tenant can transition back into ::Active
    2314            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    2315              :                 }
    2316              :             }
    2317              :         }
    2318            0 :     }
    2319              : 
    2320            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    2321            0 :         self.tenant_conf.load().location.attach_mode
    2322            0 :     }
    2323              : 
    2324              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    2325              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    2326              :     /// rare external API calls, like a reconciliation at startup.
    2327            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    2328            0 :         let conf = self.tenant_conf.load();
    2329              : 
    2330            0 :         let location_config_mode = match conf.location.attach_mode {
    2331            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    2332            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    2333            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    2334              :         };
    2335              : 
    2336              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    2337            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    2338            0 : 
    2339            0 :         models::LocationConfig {
    2340            0 :             mode: location_config_mode,
    2341            0 :             generation: self.generation.into(),
    2342            0 :             secondary_conf: None,
    2343            0 :             shard_number: self.shard_identity.number.0,
    2344            0 :             shard_count: self.shard_identity.count.literal(),
    2345            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    2346            0 :             tenant_conf: tenant_config,
    2347            0 :         }
    2348            0 :     }
    2349              : 
    2350            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    2351            0 :         &self.tenant_shard_id
    2352            0 :     }
    2353              : 
    2354            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    2355            0 :         self.shard_identity.stripe_size
    2356            0 :     }
    2357              : 
    2358            0 :     pub(crate) fn get_generation(&self) -> Generation {
    2359            0 :         self.generation
    2360            0 :     }
    2361              : 
    2362              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    2363              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    2364              :     /// resetting this tenant to a valid state if we fail.
    2365            0 :     pub(crate) async fn split_prepare(
    2366            0 :         &self,
    2367            0 :         child_shards: &Vec<TenantShardId>,
    2368            0 :     ) -> anyhow::Result<()> {
    2369            0 :         let timelines = self.timelines.lock().unwrap().clone();
    2370            0 :         for timeline in timelines.values() {
    2371              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    2372              :             // to ensure that they do not start a split if currently in the process of doing these.
    2373              : 
    2374              :             // Upload an index from the parent: this is partly to provide freshness for the
    2375              :             // child tenants that will copy it, and partly for general ease-of-debugging: there will
    2376              :             // always be a parent shard index in the same generation as we wrote the child shard index.
    2377            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Uploading index");
    2378            0 :             timeline
    2379            0 :                 .remote_client
    2380            0 :                 .schedule_index_upload_for_file_changes()?;
    2381            0 :             timeline.remote_client.wait_completion().await?;
    2382              : 
    2383              :             // Shut down the timeline's remote client: this means that the indices we write
    2384              :             // for child shards will not be invalidated by the parent shard deleting layers.
    2385            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Shutting down remote storage client");
    2386            0 :             timeline.remote_client.shutdown().await;
    2387              : 
    2388              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    2389              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    2390              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    2391              :             // we use here really is the remotely persistent one).
    2392            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Downloading index_part from parent");
    2393            0 :             let result = timeline.remote_client
    2394            0 :                 .download_index_file(&self.cancel)
    2395            0 :                 .instrument(info_span!("download_index_file", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))
    2396            0 :                 .await?;
    2397            0 :             let index_part = match result {
    2398              :                 MaybeDeletedIndexPart::Deleted(_) => {
    2399            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    2400              :                 }
    2401            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    2402              :             };
    2403              : 
    2404            0 :             for child_shard in child_shards {
    2405            0 :                 tracing::info!(timeline_id=%timeline.timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    2406            0 :                 upload_index_part(
    2407            0 :                     &self.remote_storage,
    2408            0 :                     child_shard,
    2409            0 :                     &timeline.timeline_id,
    2410            0 :                     self.generation,
    2411            0 :                     &index_part,
    2412            0 :                     &self.cancel,
    2413            0 :                 )
    2414            0 :                 .await?;
    2415              :             }
    2416              :         }
    2417              : 
    2418            0 :         Ok(())
    2419            0 :     }
    2420              : 
    2421            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    2422            0 :         let mut result = TopTenantShardItem {
    2423            0 :             id: self.tenant_shard_id,
    2424            0 :             resident_size: 0,
    2425            0 :             physical_size: 0,
    2426            0 :             max_logical_size: 0,
    2427            0 :         };
    2428              : 
    2429            0 :         for timeline in self.timelines.lock().unwrap().values() {
    2430            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    2431            0 : 
    2432            0 :             result.physical_size += timeline
    2433            0 :                 .remote_client
    2434            0 :                 .metrics
    2435            0 :                 .remote_physical_size_gauge
    2436            0 :                 .get();
    2437            0 :             result.max_logical_size = std::cmp::max(
    2438            0 :                 result.max_logical_size,
    2439            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    2440            0 :             );
    2441            0 :         }
    2442              : 
    2443            0 :         result
    2444            0 :     }
    2445              : }
    2446              : 
    2447              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    2448              : /// perform a topological sort, so that the parent of each timeline comes
    2449              : /// before the children.
    2450              : /// E extracts the ancestor from T
    2451              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    2452          564 : fn tree_sort_timelines<T, E>(
    2453          564 :     timelines: HashMap<TimelineId, T>,
    2454          564 :     extractor: E,
    2455          564 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    2456          564 : where
    2457          564 :     E: Fn(&T) -> Option<TimelineId>,
    2458          564 : {
    2459          564 :     let mut result = Vec::with_capacity(timelines.len());
    2460          564 : 
    2461          564 :     let mut now = Vec::with_capacity(timelines.len());
    2462          564 :     // (ancestor, children)
    2463          564 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    2464          564 :         HashMap::with_capacity(timelines.len());
    2465              : 
    2466          582 :     for (timeline_id, value) in timelines {
    2467           18 :         if let Some(ancestor_id) = extractor(&value) {
    2468            6 :             let children = later.entry(ancestor_id).or_default();
    2469            6 :             children.push((timeline_id, value));
    2470           12 :         } else {
    2471           12 :             now.push((timeline_id, value));
    2472           12 :         }
    2473              :     }
    2474              : 
    2475          582 :     while let Some((timeline_id, metadata)) = now.pop() {
    2476           18 :         result.push((timeline_id, metadata));
    2477              :         // All children of this can be loaded now
    2478           18 :         if let Some(mut children) = later.remove(&timeline_id) {
    2479            6 :             now.append(&mut children);
    2480           12 :         }
    2481              :     }
    2482              : 
    2483              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    2484          564 :     if !later.is_empty() {
    2485            0 :         for (missing_id, orphan_ids) in later {
    2486            0 :             for (orphan_id, _) in orphan_ids {
    2487            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    2488              :             }
    2489              :         }
    2490            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    2491          564 :     }
    2492          564 : 
    2493          564 :     Ok(result)
    2494          564 : }
    2495              : 
    2496              : impl Tenant {
    2497            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    2498            0 :         self.tenant_conf.load().tenant_conf.clone()
    2499            0 :     }
    2500              : 
    2501            0 :     pub fn effective_config(&self) -> TenantConf {
    2502            0 :         self.tenant_specific_overrides()
    2503            0 :             .merge(self.conf.default_tenant_conf.clone())
    2504            0 :     }
    2505              : 
    2506            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    2507            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2508            0 :         tenant_conf
    2509            0 :             .checkpoint_distance
    2510            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    2511            0 :     }
    2512              : 
    2513            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    2514            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2515            0 :         tenant_conf
    2516            0 :             .checkpoint_timeout
    2517            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    2518            0 :     }
    2519              : 
    2520            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    2521            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2522            0 :         tenant_conf
    2523            0 :             .compaction_target_size
    2524            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    2525            0 :     }
    2526              : 
    2527            0 :     pub fn get_compaction_period(&self) -> Duration {
    2528            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2529            0 :         tenant_conf
    2530            0 :             .compaction_period
    2531            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    2532            0 :     }
    2533              : 
    2534            0 :     pub fn get_compaction_threshold(&self) -> usize {
    2535            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2536            0 :         tenant_conf
    2537            0 :             .compaction_threshold
    2538            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    2539            0 :     }
    2540              : 
    2541            0 :     pub fn get_gc_horizon(&self) -> u64 {
    2542            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2543            0 :         tenant_conf
    2544            0 :             .gc_horizon
    2545            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    2546            0 :     }
    2547              : 
    2548            0 :     pub fn get_gc_period(&self) -> Duration {
    2549            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2550            0 :         tenant_conf
    2551            0 :             .gc_period
    2552            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    2553            0 :     }
    2554              : 
    2555            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    2556            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2557            0 :         tenant_conf
    2558            0 :             .image_creation_threshold
    2559            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    2560            0 :     }
    2561              : 
    2562            0 :     pub fn get_pitr_interval(&self) -> Duration {
    2563            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2564            0 :         tenant_conf
    2565            0 :             .pitr_interval
    2566            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    2567            0 :     }
    2568              : 
    2569            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    2570            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2571            0 :         tenant_conf
    2572            0 :             .min_resident_size_override
    2573            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    2574            0 :     }
    2575              : 
    2576            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    2577            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2578            0 :         let heatmap_period = tenant_conf
    2579            0 :             .heatmap_period
    2580            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    2581            0 :         if heatmap_period.is_zero() {
    2582            0 :             None
    2583              :         } else {
    2584            0 :             Some(heatmap_period)
    2585              :         }
    2586            0 :     }
    2587              : 
    2588            0 :     pub fn get_lsn_lease_length(&self) -> Duration {
    2589            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    2590            0 :         tenant_conf
    2591            0 :             .lsn_lease_length
    2592            0 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    2593            0 :     }
    2594              : 
    2595            0 :     pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
    2596            0 :         // Use read-copy-update in order to avoid overwriting the location config
    2597            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    2598            0 :         // this race is not possible if both request types come from the storage
    2599            0 :         // controller (as they should!) because an exclusive op lock is required
    2600            0 :         // on the storage controller side.
    2601            0 :         self.tenant_conf.rcu(|inner| {
    2602            0 :             Arc::new(AttachedTenantConf {
    2603            0 :                 tenant_conf: new_tenant_conf.clone(),
    2604            0 :                 location: inner.location,
    2605            0 :             })
    2606            0 :         });
    2607            0 : 
    2608            0 :         self.tenant_conf_updated(&new_tenant_conf);
    2609            0 :         // Don't hold self.timelines.lock() during the notifies.
    2610            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    2611            0 :         // mutexes in struct Timeline in the future.
    2612            0 :         let timelines = self.list_timelines();
    2613            0 :         for timeline in timelines {
    2614            0 :             timeline.tenant_conf_updated(&new_tenant_conf);
    2615            0 :         }
    2616            0 :     }
    2617              : 
    2618           24 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    2619           24 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    2620           24 : 
    2621           24 :         self.tenant_conf.store(Arc::new(new_conf));
    2622           24 : 
    2623           24 :         self.tenant_conf_updated(&new_tenant_conf);
    2624           24 :         // Don't hold self.timelines.lock() during the notifies.
    2625           24 :         // There's no risk of deadlock right now, but there could be if we consolidate
    2626           24 :         // mutexes in struct Timeline in the future.
    2627           24 :         let timelines = self.list_timelines();
    2628           48 :         for timeline in timelines {
    2629           24 :             timeline.tenant_conf_updated(&new_tenant_conf);
    2630           24 :         }
    2631           24 :     }
    2632              : 
    2633          588 :     fn get_timeline_get_throttle_config(
    2634          588 :         psconf: &'static PageServerConf,
    2635          588 :         overrides: &TenantConfOpt,
    2636          588 :     ) -> throttle::Config {
    2637          588 :         overrides
    2638          588 :             .timeline_get_throttle
    2639          588 :             .clone()
    2640          588 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    2641          588 :     }
    2642              : 
    2643           24 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    2644           24 :         let conf = Self::get_timeline_get_throttle_config(self.conf, new_conf);
    2645           24 :         self.timeline_get_throttle.reconfigure(conf)
    2646           24 :     }
    2647              : 
    2648              :     /// Helper function to create a new Timeline struct.
    2649              :     ///
    2650              :     /// The returned Timeline is in Loading state. The caller is responsible for
    2651              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    2652              :     /// map.
    2653              :     ///
    2654              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    2655              :     /// and we might not have the ancestor present anymore which is fine for to be
    2656              :     /// deleted timelines.
    2657         1236 :     fn create_timeline_struct(
    2658         1236 :         &self,
    2659         1236 :         new_timeline_id: TimelineId,
    2660         1236 :         new_metadata: &TimelineMetadata,
    2661         1236 :         ancestor: Option<Arc<Timeline>>,
    2662         1236 :         resources: TimelineResources,
    2663         1236 :         cause: CreateTimelineCause,
    2664         1236 :         last_aux_file_policy: Option<AuxFilePolicy>,
    2665         1236 :     ) -> anyhow::Result<Arc<Timeline>> {
    2666         1236 :         let state = match cause {
    2667              :             CreateTimelineCause::Load => {
    2668         1236 :                 let ancestor_id = new_metadata.ancestor_timeline();
    2669         1236 :                 anyhow::ensure!(
    2670         1236 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    2671            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    2672              :                 );
    2673         1236 :                 TimelineState::Loading
    2674              :             }
    2675            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    2676              :         };
    2677              : 
    2678         1236 :         let pg_version = new_metadata.pg_version();
    2679         1236 : 
    2680         1236 :         let timeline = Timeline::new(
    2681         1236 :             self.conf,
    2682         1236 :             Arc::clone(&self.tenant_conf),
    2683         1236 :             new_metadata,
    2684         1236 :             ancestor,
    2685         1236 :             new_timeline_id,
    2686         1236 :             self.tenant_shard_id,
    2687         1236 :             self.generation,
    2688         1236 :             self.shard_identity,
    2689         1236 :             self.walredo_mgr.clone(),
    2690         1236 :             resources,
    2691         1236 :             pg_version,
    2692         1236 :             state,
    2693         1236 :             last_aux_file_policy,
    2694         1236 :             self.cancel.child_token(),
    2695         1236 :         );
    2696         1236 : 
    2697         1236 :         Ok(timeline)
    2698         1236 :     }
    2699              : 
    2700              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    2701              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    2702              :     #[allow(clippy::too_many_arguments)]
    2703          564 :     fn new(
    2704          564 :         state: TenantState,
    2705          564 :         conf: &'static PageServerConf,
    2706          564 :         attached_conf: AttachedTenantConf,
    2707          564 :         shard_identity: ShardIdentity,
    2708          564 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    2709          564 :         tenant_shard_id: TenantShardId,
    2710          564 :         remote_storage: GenericRemoteStorage,
    2711          564 :         deletion_queue_client: DeletionQueueClient,
    2712          564 :         l0_flush_global_state: L0FlushGlobalState,
    2713          564 :     ) -> Tenant {
    2714          564 :         debug_assert!(
    2715          564 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    2716              :         );
    2717              : 
    2718          564 :         let (state, mut rx) = watch::channel(state);
    2719          564 : 
    2720          564 :         tokio::spawn(async move {
    2721          564 :             // reflect tenant state in metrics:
    2722          564 :             // - global per tenant state: TENANT_STATE_METRIC
    2723          564 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    2724          564 :             //
    2725          564 :             // set of broken tenants should not have zero counts so that it remains accessible for
    2726          564 :             // alerting.
    2727          564 : 
    2728          564 :             let tid = tenant_shard_id.to_string();
    2729          564 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    2730          564 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    2731          564 : 
    2732         1121 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    2733         1121 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    2734         1121 :             }
    2735          564 : 
    2736          564 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    2737          564 : 
    2738          564 :             let is_broken = tuple.1;
    2739          564 :             let mut counted_broken = if is_broken {
    2740              :                 // add the id to the set right away, there should not be any updates on the channel
    2741              :                 // after before tenant is removed, if ever
    2742            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    2743            0 :                 true
    2744              :             } else {
    2745          564 :                 false
    2746              :             };
    2747              : 
    2748         1121 :             loop {
    2749         1121 :                 let labels = &tuple.0;
    2750         1121 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    2751         1121 :                 current.inc();
    2752         1121 : 
    2753         1121 :                 if rx.changed().await.is_err() {
    2754              :                     // tenant has been dropped
    2755           48 :                     current.dec();
    2756           48 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    2757           48 :                     break;
    2758          557 :                 }
    2759          557 : 
    2760          557 :                 current.dec();
    2761          557 :                 tuple = inspect_state(&rx.borrow_and_update());
    2762          557 : 
    2763          557 :                 let is_broken = tuple.1;
    2764          557 :                 if is_broken && !counted_broken {
    2765            0 :                     counted_broken = true;
    2766            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    2767            0 :                     // access
    2768            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    2769          557 :                 }
    2770              :             }
    2771          564 :         });
    2772          564 : 
    2773          564 :         Tenant {
    2774          564 :             tenant_shard_id,
    2775          564 :             shard_identity,
    2776          564 :             generation: attached_conf.location.generation,
    2777          564 :             conf,
    2778          564 :             // using now here is good enough approximation to catch tenants with really long
    2779          564 :             // activation times.
    2780          564 :             constructed_at: Instant::now(),
    2781          564 :             timelines: Mutex::new(HashMap::new()),
    2782          564 :             timelines_creating: Mutex::new(HashSet::new()),
    2783          564 :             gc_cs: tokio::sync::Mutex::new(()),
    2784          564 :             walredo_mgr,
    2785          564 :             remote_storage,
    2786          564 :             deletion_queue_client,
    2787          564 :             state,
    2788          564 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    2789          564 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    2790          564 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    2791          564 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    2792          564 :                 format!("compaction-{tenant_shard_id}"),
    2793          564 :                 5,
    2794          564 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    2795          564 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    2796          564 :                 // use an extremely long backoff.
    2797          564 :                 Some(Duration::from_secs(3600 * 24)),
    2798          564 :             )),
    2799          564 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    2800          564 :             cancel: CancellationToken::default(),
    2801          564 :             gate: Gate::default(),
    2802          564 :             timeline_get_throttle: Arc::new(throttle::Throttle::new(
    2803          564 :                 Tenant::get_timeline_get_throttle_config(conf, &attached_conf.tenant_conf),
    2804          564 :                 &crate::metrics::tenant_throttling::TIMELINE_GET,
    2805          564 :             )),
    2806          564 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    2807          564 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    2808          564 :             gc_block: Default::default(),
    2809          564 :             l0_flush_global_state,
    2810          564 :         }
    2811          564 :     }
    2812              : 
    2813              :     /// Locate and load config
    2814            0 :     pub(super) fn load_tenant_config(
    2815            0 :         conf: &'static PageServerConf,
    2816            0 :         tenant_shard_id: &TenantShardId,
    2817            0 :     ) -> Result<LocationConf, LoadConfigError> {
    2818            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    2819            0 : 
    2820            0 :         info!("loading tenant configuration from {config_path}");
    2821              : 
    2822              :         // load and parse file
    2823            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    2824            0 :             match e.kind() {
    2825              :                 std::io::ErrorKind::NotFound => {
    2826              :                     // The config should almost always exist for a tenant directory:
    2827              :                     //  - When attaching a tenant, the config is the first thing we write
    2828              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    2829              :                     //    before deleting contents.
    2830              :                     //
    2831              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    2832              :                     // between creating directory and writing config.  Callers should handle that as if the
    2833              :                     // directory didn't exist.
    2834              : 
    2835            0 :                     LoadConfigError::NotFound(config_path)
    2836              :                 }
    2837              :                 _ => {
    2838              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    2839              :                     // that we cannot cleanly recover
    2840            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    2841              :                 }
    2842              :             }
    2843            0 :         })?;
    2844              : 
    2845            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    2846            0 :     }
    2847              : 
    2848            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    2849              :     pub(super) async fn persist_tenant_config(
    2850              :         conf: &'static PageServerConf,
    2851              :         tenant_shard_id: &TenantShardId,
    2852              :         location_conf: &LocationConf,
    2853              :     ) -> std::io::Result<()> {
    2854              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    2855              : 
    2856              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    2857              :     }
    2858              : 
    2859            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    2860              :     pub(super) async fn persist_tenant_config_at(
    2861              :         tenant_shard_id: &TenantShardId,
    2862              :         config_path: &Utf8Path,
    2863              :         location_conf: &LocationConf,
    2864              :     ) -> std::io::Result<()> {
    2865              :         debug!("persisting tenantconf to {config_path}");
    2866              : 
    2867              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    2868              : #  It is read in case of pageserver restart.
    2869              : "#
    2870              :         .to_string();
    2871              : 
    2872            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    2873            0 :             Err(std::io::Error::new(
    2874            0 :                 std::io::ErrorKind::Other,
    2875            0 :                 "tenant-config-before-write",
    2876            0 :             ))
    2877            0 :         });
    2878              : 
    2879              :         // Convert the config to a toml file.
    2880              :         conf_content +=
    2881              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    2882              : 
    2883              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    2884              : 
    2885              :         let conf_content = conf_content.into_bytes();
    2886              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    2887              :     }
    2888              : 
    2889              :     //
    2890              :     // How garbage collection works:
    2891              :     //
    2892              :     //                    +--bar------------->
    2893              :     //                   /
    2894              :     //             +----+-----foo---------------->
    2895              :     //            /
    2896              :     // ----main--+-------------------------->
    2897              :     //                \
    2898              :     //                 +-----baz-------->
    2899              :     //
    2900              :     //
    2901              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    2902              :     //    `gc_infos` are being refreshed
    2903              :     // 2. Scan collected timelines, and on each timeline, make note of the
    2904              :     //    all the points where other timelines have been branched off.
    2905              :     //    We will refrain from removing page versions at those LSNs.
    2906              :     // 3. For each timeline, scan all layer files on the timeline.
    2907              :     //    Remove all files for which a newer file exists and which
    2908              :     //    don't cover any branch point LSNs.
    2909              :     //
    2910              :     // TODO:
    2911              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    2912              :     //   don't need to keep that in the parent anymore. But currently
    2913              :     //   we do.
    2914         2262 :     async fn gc_iteration_internal(
    2915         2262 :         &self,
    2916         2262 :         target_timeline_id: Option<TimelineId>,
    2917         2262 :         horizon: u64,
    2918         2262 :         pitr: Duration,
    2919         2262 :         cancel: &CancellationToken,
    2920         2262 :         ctx: &RequestContext,
    2921         2262 :     ) -> Result<GcResult, GcError> {
    2922         2262 :         let mut totals: GcResult = Default::default();
    2923         2262 :         let now = Instant::now();
    2924              : 
    2925         2262 :         let gc_timelines = self
    2926         2262 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2927         2169 :             .await?;
    2928              : 
    2929         2262 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    2930              : 
    2931              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    2932         2262 :         if !gc_timelines.is_empty() {
    2933         2262 :             info!("{} timelines need GC", gc_timelines.len());
    2934              :         } else {
    2935            0 :             debug!("{} timelines need GC", gc_timelines.len());
    2936              :         }
    2937              : 
    2938              :         // Perform GC for each timeline.
    2939              :         //
    2940              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    2941              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    2942              :         // with branch creation.
    2943              :         //
    2944              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    2945              :         // creation task can run concurrently with timeline's GC iteration.
    2946         4524 :         for timeline in gc_timelines {
    2947         2262 :             if cancel.is_cancelled() {
    2948              :                 // We were requested to shut down. Stop and return with the progress we
    2949              :                 // made.
    2950            0 :                 break;
    2951         2262 :             }
    2952         2262 :             let result = match timeline.gc().await {
    2953              :                 Err(GcError::TimelineCancelled) => {
    2954            0 :                     if target_timeline_id.is_some() {
    2955              :                         // If we were targetting this specific timeline, surface cancellation to caller
    2956            0 :                         return Err(GcError::TimelineCancelled);
    2957              :                     } else {
    2958              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    2959              :                         // skip past this and proceed to try GC on other timelines.
    2960            0 :                         continue;
    2961              :                     }
    2962              :                 }
    2963         2262 :                 r => r?,
    2964              :             };
    2965         2262 :             totals += result;
    2966              :         }
    2967              : 
    2968         2262 :         totals.elapsed = now.elapsed();
    2969         2262 :         Ok(totals)
    2970         2262 :     }
    2971              : 
    2972              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    2973              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    2974              :     /// [`Tenant::get_gc_horizon`].
    2975              :     ///
    2976              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    2977            0 :     pub(crate) async fn refresh_gc_info(
    2978            0 :         &self,
    2979            0 :         cancel: &CancellationToken,
    2980            0 :         ctx: &RequestContext,
    2981            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    2982            0 :         // since this method can now be called at different rates than the configured gc loop, it
    2983            0 :         // might be that these configuration values get applied faster than what it was previously,
    2984            0 :         // since these were only read from the gc task.
    2985            0 :         let horizon = self.get_gc_horizon();
    2986            0 :         let pitr = self.get_pitr_interval();
    2987            0 : 
    2988            0 :         // refresh all timelines
    2989            0 :         let target_timeline_id = None;
    2990            0 : 
    2991            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2992            0 :             .await
    2993            0 :     }
    2994              : 
    2995              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    2996              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    2997              :     ///
    2998              :     /// Subsequently, parent-child relationships are updated incrementally during timeline creation/deletion.
    2999            0 :     fn initialize_gc_info(
    3000            0 :         &self,
    3001            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    3002            0 :     ) {
    3003            0 :         // This function must be called before activation: after activation timeline create/delete operations
    3004            0 :         // might happen, and this function is not safe to run concurrently with those.
    3005            0 :         assert!(!self.is_active());
    3006              : 
    3007              :         // Scan all timelines. For each timeline, remember the timeline ID and
    3008              :         // the branch point where it was created.
    3009            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId)>> = BTreeMap::new();
    3010            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    3011            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    3012            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    3013            0 :                 ancestor_children.push((timeline_entry.get_ancestor_lsn(), *timeline_id));
    3014            0 :             }
    3015            0 :         });
    3016            0 : 
    3017            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    3018            0 :         let horizon = self.get_gc_horizon();
    3019              : 
    3020              :         // Populate each timeline's GcInfo with information about its child branches
    3021            0 :         for timeline in timelines.values() {
    3022            0 :             let mut branchpoints: Vec<(Lsn, TimelineId)> = all_branchpoints
    3023            0 :                 .remove(&timeline.timeline_id)
    3024            0 :                 .unwrap_or_default();
    3025            0 : 
    3026            0 :             branchpoints.sort_by_key(|b| b.0);
    3027            0 : 
    3028            0 :             let mut target = timeline.gc_info.write().unwrap();
    3029            0 : 
    3030            0 :             target.retain_lsns = branchpoints;
    3031            0 : 
    3032            0 :             let space_cutoff = timeline
    3033            0 :                 .get_last_record_lsn()
    3034            0 :                 .checked_sub(horizon)
    3035            0 :                 .unwrap_or(Lsn(0));
    3036            0 : 
    3037            0 :             target.cutoffs = GcCutoffs {
    3038            0 :                 space: space_cutoff,
    3039            0 :                 time: Lsn::INVALID,
    3040            0 :             };
    3041            0 :         }
    3042            0 :     }
    3043              : 
    3044         2262 :     async fn refresh_gc_info_internal(
    3045         2262 :         &self,
    3046         2262 :         target_timeline_id: Option<TimelineId>,
    3047         2262 :         horizon: u64,
    3048         2262 :         pitr: Duration,
    3049         2262 :         cancel: &CancellationToken,
    3050         2262 :         ctx: &RequestContext,
    3051         2262 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    3052         2262 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    3053         2262 :         // currently visible timelines.
    3054         2262 :         let timelines = self
    3055         2262 :             .timelines
    3056         2262 :             .lock()
    3057         2262 :             .unwrap()
    3058         2262 :             .values()
    3059         9930 :             .filter(|tl| match target_timeline_id.as_ref() {
    3060         9930 :                 Some(target) => &tl.timeline_id == target,
    3061            0 :                 None => true,
    3062         9930 :             })
    3063         2262 :             .cloned()
    3064         2262 :             .collect::<Vec<_>>();
    3065         2262 : 
    3066         2262 :         if target_timeline_id.is_some() && timelines.is_empty() {
    3067              :             // We were to act on a particular timeline and it wasn't found
    3068            0 :             return Err(GcError::TimelineNotFound);
    3069         2262 :         }
    3070         2262 : 
    3071         2262 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    3072         2262 :             HashMap::with_capacity(timelines.len());
    3073              : 
    3074         2262 :         for timeline in timelines.iter() {
    3075         2262 :             let cutoff = timeline
    3076         2262 :                 .get_last_record_lsn()
    3077         2262 :                 .checked_sub(horizon)
    3078         2262 :                 .unwrap_or(Lsn(0));
    3079              : 
    3080         2262 :             let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
    3081         2262 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    3082         2262 :             assert!(old.is_none());
    3083              :         }
    3084              : 
    3085         2262 :         if !self.is_active() || self.cancel.is_cancelled() {
    3086            0 :             return Err(GcError::TenantCancelled);
    3087         2262 :         }
    3088              : 
    3089              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    3090              :         // because that will stall branch creation.
    3091         2262 :         let gc_cs = self.gc_cs.lock().await;
    3092              : 
    3093              :         // Ok, we now know all the branch points.
    3094              :         // Update the GC information for each timeline.
    3095         2262 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    3096         4524 :         for timeline in timelines {
    3097              :             // We filtered the timeline list above
    3098         2262 :             if let Some(target_timeline_id) = target_timeline_id {
    3099         2262 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    3100            0 :             }
    3101              : 
    3102              :             {
    3103         2262 :                 let mut target = timeline.gc_info.write().unwrap();
    3104         2262 : 
    3105         2262 :                 // Cull any expired leases
    3106         2262 :                 let now = SystemTime::now();
    3107         2262 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    3108         2262 : 
    3109         2262 :                 timeline
    3110         2262 :                     .metrics
    3111         2262 :                     .valid_lsn_lease_count_gauge
    3112         2262 :                     .set(target.leases.len() as u64);
    3113              : 
    3114              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    3115         2262 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    3116          300 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    3117            0 :                         target.within_ancestor_pitr =
    3118            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    3119          300 :                     }
    3120         1962 :                 }
    3121              : 
    3122              :                 // Update metrics that depend on GC state
    3123         2262 :                 timeline
    3124         2262 :                     .metrics
    3125         2262 :                     .archival_size
    3126         2262 :                     .set(if target.within_ancestor_pitr {
    3127            0 :                         timeline.metrics.current_logical_size_gauge.get()
    3128              :                     } else {
    3129         2262 :                         0
    3130              :                     });
    3131         2262 :                 timeline.metrics.pitr_history_size.set(
    3132         2262 :                     timeline
    3133         2262 :                         .get_last_record_lsn()
    3134         2262 :                         .checked_sub(target.cutoffs.time)
    3135         2262 :                         .unwrap_or(Lsn(0))
    3136         2262 :                         .0,
    3137         2262 :                 );
    3138              : 
    3139              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    3140              :                 // - this timeline was created while we were finding cutoffs
    3141              :                 // - lsn for timestamp search fails for this timeline repeatedly
    3142         2262 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    3143         2262 :                     target.cutoffs = cutoffs.clone();
    3144         2262 :                 }
    3145              :             }
    3146              : 
    3147         2262 :             gc_timelines.push(timeline);
    3148              :         }
    3149         2262 :         drop(gc_cs);
    3150         2262 :         Ok(gc_timelines)
    3151         2262 :     }
    3152              : 
    3153              :     /// A substitute for `branch_timeline` for use in unit tests.
    3154              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    3155              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    3156              :     /// timeline background tasks are launched, except the flush loop.
    3157              :     #[cfg(test)]
    3158          690 :     async fn branch_timeline_test(
    3159          690 :         &self,
    3160          690 :         src_timeline: &Arc<Timeline>,
    3161          690 :         dst_id: TimelineId,
    3162          690 :         ancestor_lsn: Option<Lsn>,
    3163          690 :         ctx: &RequestContext,
    3164          690 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    3165          690 :         let create_guard = self.create_timeline_create_guard(dst_id).unwrap();
    3166          690 :         let tl = self
    3167          690 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, create_guard, ctx)
    3168           12 :             .await?;
    3169          678 :         tl.set_state(TimelineState::Active);
    3170          678 :         Ok(tl)
    3171          690 :     }
    3172              : 
    3173              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    3174              :     #[cfg(test)]
    3175              :     #[allow(clippy::too_many_arguments)]
    3176           18 :     pub async fn branch_timeline_test_with_layers(
    3177           18 :         &self,
    3178           18 :         src_timeline: &Arc<Timeline>,
    3179           18 :         dst_id: TimelineId,
    3180           18 :         ancestor_lsn: Option<Lsn>,
    3181           18 :         ctx: &RequestContext,
    3182           18 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    3183           18 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    3184           18 :         end_lsn: Lsn,
    3185           18 :     ) -> anyhow::Result<Arc<Timeline>> {
    3186           18 :         let tline = self
    3187           18 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    3188            0 :             .await?;
    3189           18 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    3190           18 :             ancestor_lsn
    3191              :         } else {
    3192            0 :             tline.get_last_record_lsn()
    3193              :         };
    3194           18 :         assert!(end_lsn >= ancestor_lsn);
    3195           18 :         tline.force_advance_lsn(end_lsn);
    3196           36 :         for deltas in delta_layer_desc {
    3197           18 :             tline
    3198           18 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    3199           54 :                 .await?;
    3200              :         }
    3201           30 :         for (lsn, images) in image_layer_desc {
    3202           12 :             tline
    3203           12 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    3204           42 :                 .await?;
    3205              :         }
    3206           18 :         Ok(tline)
    3207           18 :     }
    3208              : 
    3209              :     /// Branch an existing timeline.
    3210              :     ///
    3211              :     /// The caller is responsible for activating the returned timeline.
    3212            0 :     async fn branch_timeline(
    3213            0 :         &self,
    3214            0 :         src_timeline: &Arc<Timeline>,
    3215            0 :         dst_id: TimelineId,
    3216            0 :         start_lsn: Option<Lsn>,
    3217            0 :         timeline_create_guard: TimelineCreateGuard<'_>,
    3218            0 :         ctx: &RequestContext,
    3219            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    3220            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, timeline_create_guard, ctx)
    3221            0 :             .await
    3222            0 :     }
    3223              : 
    3224          690 :     async fn branch_timeline_impl(
    3225          690 :         &self,
    3226          690 :         src_timeline: &Arc<Timeline>,
    3227          690 :         dst_id: TimelineId,
    3228          690 :         start_lsn: Option<Lsn>,
    3229          690 :         timeline_create_guard: TimelineCreateGuard<'_>,
    3230          690 :         _ctx: &RequestContext,
    3231          690 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    3232          690 :         let src_id = src_timeline.timeline_id;
    3233              : 
    3234              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    3235              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    3236              :         // valid while we are creating the branch.
    3237          690 :         let _gc_cs = self.gc_cs.lock().await;
    3238              : 
    3239              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    3240          690 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    3241            6 :             let lsn = src_timeline.get_last_record_lsn();
    3242            6 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    3243            6 :             lsn
    3244          690 :         });
    3245          690 : 
    3246          690 :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    3247          690 :         // horizon on the source timeline
    3248          690 :         //
    3249          690 :         // We check it against both the planned GC cutoff stored in 'gc_info',
    3250          690 :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    3251          690 :         // planned GC cutoff in 'gc_info' is normally larger than
    3252          690 :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    3253          690 :         // changed the GC settings for the tenant to make the PITR window
    3254          690 :         // larger, but some of the data was already removed by an earlier GC
    3255          690 :         // iteration.
    3256          690 : 
    3257          690 :         // check against last actual 'latest_gc_cutoff' first
    3258          690 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    3259          690 :         src_timeline
    3260          690 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    3261          690 :             .context(format!(
    3262          690 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    3263          690 :                 *latest_gc_cutoff_lsn,
    3264          690 :             ))
    3265          690 :             .map_err(CreateTimelineError::AncestorLsn)?;
    3266              : 
    3267              :         // and then the planned GC cutoff
    3268              :         {
    3269          678 :             let gc_info = src_timeline.gc_info.read().unwrap();
    3270          678 :             let cutoff = gc_info.min_cutoff();
    3271          678 :             if start_lsn < cutoff {
    3272            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    3273            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    3274            0 :                 )));
    3275          678 :             }
    3276          678 :         }
    3277          678 : 
    3278          678 :         //
    3279          678 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    3280          678 :         // so that GC cannot advance the GC cutoff until we are finished.
    3281          678 :         // Proceed with the branch creation.
    3282          678 :         //
    3283          678 : 
    3284          678 :         // Determine prev-LSN for the new timeline. We can only determine it if
    3285          678 :         // the timeline was branched at the current end of the source timeline.
    3286          678 :         let RecordLsn {
    3287          678 :             last: src_last,
    3288          678 :             prev: src_prev,
    3289          678 :         } = src_timeline.get_last_record_rlsn();
    3290          678 :         let dst_prev = if src_last == start_lsn {
    3291          648 :             Some(src_prev)
    3292              :         } else {
    3293           30 :             None
    3294              :         };
    3295              : 
    3296              :         // Create the metadata file, noting the ancestor of the new timeline.
    3297              :         // There is initially no data in it, but all the read-calls know to look
    3298              :         // into the ancestor.
    3299          678 :         let metadata = TimelineMetadata::new(
    3300          678 :             start_lsn,
    3301          678 :             dst_prev,
    3302          678 :             Some(src_id),
    3303          678 :             start_lsn,
    3304          678 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    3305          678 :             src_timeline.initdb_lsn,
    3306          678 :             src_timeline.pg_version,
    3307          678 :         );
    3308              : 
    3309          678 :         let uninitialized_timeline = self
    3310          678 :             .prepare_new_timeline(
    3311          678 :                 dst_id,
    3312          678 :                 &metadata,
    3313          678 :                 timeline_create_guard,
    3314          678 :                 start_lsn + 1,
    3315          678 :                 Some(Arc::clone(src_timeline)),
    3316          678 :                 src_timeline.last_aux_file_policy.load(),
    3317          678 :             )
    3318            0 :             .await?;
    3319              : 
    3320          678 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    3321              : 
    3322              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    3323              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    3324              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    3325              :         // could get incorrect information and remove more layers, than needed.
    3326              :         // See also https://github.com/neondatabase/neon/issues/3865
    3327          678 :         new_timeline
    3328          678 :             .remote_client
    3329          678 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    3330          678 :             .context("branch initial metadata upload")?;
    3331              : 
    3332          678 :         Ok(new_timeline)
    3333          690 :     }
    3334              : 
    3335              :     /// For unit tests, make this visible so that other modules can directly create timelines
    3336              :     #[cfg(test)]
    3337           12 :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    3338              :     pub(crate) async fn bootstrap_timeline_test(
    3339              :         &self,
    3340              :         timeline_id: TimelineId,
    3341              :         pg_version: u32,
    3342              :         load_existing_initdb: Option<TimelineId>,
    3343              :         ctx: &RequestContext,
    3344              :     ) -> anyhow::Result<Arc<Timeline>> {
    3345              :         let create_guard = self.create_timeline_create_guard(timeline_id).unwrap();
    3346              :         self.bootstrap_timeline(
    3347              :             timeline_id,
    3348              :             pg_version,
    3349              :             load_existing_initdb,
    3350              :             create_guard,
    3351              :             ctx,
    3352              :         )
    3353              :         .await
    3354              :     }
    3355              : 
    3356            0 :     async fn upload_initdb(
    3357            0 :         &self,
    3358            0 :         timelines_path: &Utf8PathBuf,
    3359            0 :         pgdata_path: &Utf8PathBuf,
    3360            0 :         timeline_id: &TimelineId,
    3361            0 :     ) -> anyhow::Result<()> {
    3362            0 :         let temp_path = timelines_path.join(format!(
    3363            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    3364            0 :         ));
    3365              : 
    3366              :         scopeguard::defer! {
    3367              :             if let Err(e) = fs::remove_file(&temp_path) {
    3368              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    3369              :             }
    3370              :         }
    3371              : 
    3372            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    3373              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    3374            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    3375            0 :             warn!(
    3376            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    3377              :             );
    3378            0 :         }
    3379              : 
    3380              :         pausable_failpoint!("before-initdb-upload");
    3381              : 
    3382            0 :         backoff::retry(
    3383            0 :             || async {
    3384            0 :                 self::remote_timeline_client::upload_initdb_dir(
    3385            0 :                     &self.remote_storage,
    3386            0 :                     &self.tenant_shard_id.tenant_id,
    3387            0 :                     timeline_id,
    3388            0 :                     pgdata_zstd.try_clone().await?,
    3389            0 :                     tar_zst_size,
    3390            0 :                     &self.cancel,
    3391            0 :                 )
    3392            0 :                 .await
    3393            0 :             },
    3394            0 :             |_| false,
    3395            0 :             3,
    3396            0 :             u32::MAX,
    3397            0 :             "persist_initdb_tar_zst",
    3398            0 :             &self.cancel,
    3399            0 :         )
    3400            0 :         .await
    3401            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    3402            0 :         .and_then(|x| x)
    3403            0 :     }
    3404              : 
    3405              :     /// - run initdb to init temporary instance and get bootstrap data
    3406              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    3407              :     ///
    3408              :     /// The caller is responsible for activating the returned timeline.
    3409            6 :     async fn bootstrap_timeline(
    3410            6 :         &self,
    3411            6 :         timeline_id: TimelineId,
    3412            6 :         pg_version: u32,
    3413            6 :         load_existing_initdb: Option<TimelineId>,
    3414            6 :         timeline_create_guard: TimelineCreateGuard<'_>,
    3415            6 :         ctx: &RequestContext,
    3416            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    3417            6 :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    3418            6 :         // temporary directory for basebackup files for the given timeline.
    3419            6 : 
    3420            6 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    3421            6 :         let pgdata_path = path_with_suffix_extension(
    3422            6 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    3423            6 :             TEMP_FILE_SUFFIX,
    3424            6 :         );
    3425            6 : 
    3426            6 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    3427            6 :         // we won't race with other creations or existent timelines with the same path.
    3428            6 :         if pgdata_path.exists() {
    3429            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    3430            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    3431            0 :             })?;
    3432            6 :         }
    3433              : 
    3434              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    3435              :         scopeguard::defer! {
    3436              :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    3437              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    3438              :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    3439              :             }
    3440              :         }
    3441            6 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    3442            6 :             if existing_initdb_timeline_id != timeline_id {
    3443            0 :                 let source_path = &remote_initdb_archive_path(
    3444            0 :                     &self.tenant_shard_id.tenant_id,
    3445            0 :                     &existing_initdb_timeline_id,
    3446            0 :                 );
    3447            0 :                 let dest_path =
    3448            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    3449            0 : 
    3450            0 :                 // if this fails, it will get retried by retried control plane requests
    3451            0 :                 self.remote_storage
    3452            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    3453            0 :                     .await
    3454            0 :                     .context("copy initdb tar")?;
    3455            6 :             }
    3456            6 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    3457            6 :                 self::remote_timeline_client::download_initdb_tar_zst(
    3458            6 :                     self.conf,
    3459            6 :                     &self.remote_storage,
    3460            6 :                     &self.tenant_shard_id,
    3461            6 :                     &existing_initdb_timeline_id,
    3462            6 :                     &self.cancel,
    3463            6 :                 )
    3464         1748 :                 .await
    3465            6 :                 .context("download initdb tar")?;
    3466              : 
    3467              :             scopeguard::defer! {
    3468              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    3469              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    3470              :                 }
    3471              :             }
    3472              : 
    3473            6 :             let buf_read =
    3474            6 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    3475            6 :             extract_zst_tarball(&pgdata_path, buf_read)
    3476        28777 :                 .await
    3477            6 :                 .context("extract initdb tar")?;
    3478              :         } else {
    3479              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    3480            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel).await?;
    3481              : 
    3482              :             // Upload the created data dir to S3
    3483            0 :             if self.tenant_shard_id().is_shard_zero() {
    3484            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    3485            0 :                     .await?;
    3486            0 :             }
    3487              :         }
    3488            6 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    3489            6 : 
    3490            6 :         // Import the contents of the data directory at the initial checkpoint
    3491            6 :         // LSN, and any WAL after that.
    3492            6 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    3493            6 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    3494            6 :         let new_metadata = TimelineMetadata::new(
    3495            6 :             Lsn(0),
    3496            6 :             None,
    3497            6 :             None,
    3498            6 :             Lsn(0),
    3499            6 :             pgdata_lsn,
    3500            6 :             pgdata_lsn,
    3501            6 :             pg_version,
    3502            6 :         );
    3503            6 :         let raw_timeline = self
    3504            6 :             .prepare_new_timeline(
    3505            6 :                 timeline_id,
    3506            6 :                 &new_metadata,
    3507            6 :                 timeline_create_guard,
    3508            6 :                 pgdata_lsn,
    3509            6 :                 None,
    3510            6 :                 None,
    3511            6 :             )
    3512            0 :             .await?;
    3513              : 
    3514            6 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    3515            6 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    3516              : 
    3517              :         // Flush the new layer files to disk, before we make the timeline as available to
    3518              :         // the outside world.
    3519              :         //
    3520              :         // Flush loop needs to be spawned in order to be able to flush.
    3521            6 :         unfinished_timeline.maybe_spawn_flush_loop();
    3522            6 : 
    3523            6 :         import_datadir::import_timeline_from_postgres_datadir(
    3524            6 :             unfinished_timeline,
    3525            6 :             &pgdata_path,
    3526            6 :             pgdata_lsn,
    3527            6 :             ctx,
    3528            6 :         )
    3529        26243 :         .await
    3530            6 :         .with_context(|| {
    3531            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    3532            6 :         })?;
    3533              : 
    3534            6 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    3535            0 :             anyhow::bail!("failpoint before-checkpoint-new-timeline");
    3536            6 :         });
    3537              : 
    3538            6 :         unfinished_timeline
    3539            6 :             .freeze_and_flush()
    3540            6 :             .await
    3541            6 :             .with_context(|| {
    3542            0 :                 format!(
    3543            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    3544            0 :                 )
    3545            6 :             })?;
    3546              : 
    3547              :         // All done!
    3548            6 :         let timeline = raw_timeline.finish_creation()?;
    3549              : 
    3550            6 :         Ok(timeline)
    3551            6 :     }
    3552              : 
    3553              :     /// Call this before constructing a timeline, to build its required structures
    3554         1218 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    3555         1218 :         let remote_client = RemoteTimelineClient::new(
    3556         1218 :             self.remote_storage.clone(),
    3557         1218 :             self.deletion_queue_client.clone(),
    3558         1218 :             self.conf,
    3559         1218 :             self.tenant_shard_id,
    3560         1218 :             timeline_id,
    3561         1218 :             self.generation,
    3562         1218 :         );
    3563         1218 :         TimelineResources {
    3564         1218 :             remote_client,
    3565         1218 :             timeline_get_throttle: self.timeline_get_throttle.clone(),
    3566         1218 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    3567         1218 :         }
    3568         1218 :     }
    3569              : 
    3570              :     /// Creates intermediate timeline structure and its files.
    3571              :     ///
    3572              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    3573              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    3574              :     /// `finish_creation` to insert the Timeline into the timelines map.
    3575         1218 :     async fn prepare_new_timeline<'a>(
    3576         1218 :         &'a self,
    3577         1218 :         new_timeline_id: TimelineId,
    3578         1218 :         new_metadata: &TimelineMetadata,
    3579         1218 :         create_guard: TimelineCreateGuard<'a>,
    3580         1218 :         start_lsn: Lsn,
    3581         1218 :         ancestor: Option<Arc<Timeline>>,
    3582         1218 :         last_aux_file_policy: Option<AuxFilePolicy>,
    3583         1218 :     ) -> anyhow::Result<UninitializedTimeline> {
    3584         1218 :         let tenant_shard_id = self.tenant_shard_id;
    3585         1218 : 
    3586         1218 :         let resources = self.build_timeline_resources(new_timeline_id);
    3587         1218 :         resources
    3588         1218 :             .remote_client
    3589         1218 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    3590              : 
    3591         1218 :         let timeline_struct = self
    3592         1218 :             .create_timeline_struct(
    3593         1218 :                 new_timeline_id,
    3594         1218 :                 new_metadata,
    3595         1218 :                 ancestor,
    3596         1218 :                 resources,
    3597         1218 :                 CreateTimelineCause::Load,
    3598         1218 :                 last_aux_file_policy,
    3599         1218 :             )
    3600         1218 :             .context("Failed to create timeline data structure")?;
    3601              : 
    3602         1218 :         timeline_struct.init_empty_layer_map(start_lsn);
    3603              : 
    3604         1218 :         if let Err(e) = self
    3605         1218 :             .create_timeline_files(&create_guard.timeline_path)
    3606            0 :             .await
    3607              :         {
    3608            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    3609            0 :             cleanup_timeline_directory(create_guard);
    3610            0 :             return Err(e);
    3611         1218 :         }
    3612         1218 : 
    3613         1218 :         debug!(
    3614            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    3615              :         );
    3616              : 
    3617         1218 :         Ok(UninitializedTimeline::new(
    3618         1218 :             self,
    3619         1218 :             new_timeline_id,
    3620         1218 :             Some((timeline_struct, create_guard)),
    3621         1218 :         ))
    3622         1218 :     }
    3623              : 
    3624         1218 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    3625         1218 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    3626              : 
    3627         1218 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    3628            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    3629         1218 :         });
    3630              : 
    3631         1218 :         Ok(())
    3632         1218 :     }
    3633              : 
    3634              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    3635              :     /// concurrent attempts to create the same timeline.
    3636         1236 :     fn create_timeline_create_guard(
    3637         1236 :         &self,
    3638         1236 :         timeline_id: TimelineId,
    3639         1236 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    3640         1236 :         let tenant_shard_id = self.tenant_shard_id;
    3641         1236 : 
    3642         1236 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    3643              : 
    3644         1236 :         let create_guard = TimelineCreateGuard::new(self, timeline_id, timeline_path.clone())?;
    3645              : 
    3646              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    3647              :         // for creation.
    3648              :         // A timeline directory should never exist on disk already:
    3649              :         // - a previous failed creation would have cleaned up after itself
    3650              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    3651              :         //
    3652              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    3653              :         // this error may indicate a bug in cleanup on failed creations.
    3654         1230 :         if timeline_path.exists() {
    3655            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    3656            0 :                 "Timeline directory already exists! This is a bug."
    3657            0 :             )));
    3658         1230 :         }
    3659         1230 : 
    3660         1230 :         Ok(create_guard)
    3661         1236 :     }
    3662              : 
    3663              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    3664              :     ///
    3665              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    3666            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    3667              :     pub async fn gather_size_inputs(
    3668              :         &self,
    3669              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    3670              :         // (only if it is shorter than the real cutoff).
    3671              :         max_retention_period: Option<u64>,
    3672              :         cause: LogicalSizeCalculationCause,
    3673              :         cancel: &CancellationToken,
    3674              :         ctx: &RequestContext,
    3675              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    3676              :         let logical_sizes_at_once = self
    3677              :             .conf
    3678              :             .concurrent_tenant_size_logical_size_queries
    3679              :             .inner();
    3680              : 
    3681              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    3682              :         //
    3683              :         // But the only case where we need to run multiple of these at once is when we
    3684              :         // request a size for a tenant manually via API, while another background calculation
    3685              :         // is in progress (which is not a common case).
    3686              :         //
    3687              :         // See more for on the issue #2748 condenced out of the initial PR review.
    3688              :         let mut shared_cache = tokio::select! {
    3689              :             locked = self.cached_logical_sizes.lock() => locked,
    3690              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    3691              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    3692              :         };
    3693              : 
    3694              :         size::gather_inputs(
    3695              :             self,
    3696              :             logical_sizes_at_once,
    3697              :             max_retention_period,
    3698              :             &mut shared_cache,
    3699              :             cause,
    3700              :             cancel,
    3701              :             ctx,
    3702              :         )
    3703              :         .await
    3704              :     }
    3705              : 
    3706              :     /// Calculate synthetic tenant size and cache the result.
    3707              :     /// This is periodically called by background worker.
    3708              :     /// result is cached in tenant struct
    3709            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    3710              :     pub async fn calculate_synthetic_size(
    3711              :         &self,
    3712              :         cause: LogicalSizeCalculationCause,
    3713              :         cancel: &CancellationToken,
    3714              :         ctx: &RequestContext,
    3715              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    3716              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    3717              : 
    3718              :         let size = inputs.calculate();
    3719              : 
    3720              :         self.set_cached_synthetic_size(size);
    3721              : 
    3722              :         Ok(size)
    3723              :     }
    3724              : 
    3725              :     /// Cache given synthetic size and update the metric value
    3726            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    3727            0 :         self.cached_synthetic_tenant_size
    3728            0 :             .store(size, Ordering::Relaxed);
    3729            0 : 
    3730            0 :         // Only shard zero should be calculating synthetic sizes
    3731            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    3732              : 
    3733            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    3734            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    3735            0 :             .unwrap()
    3736            0 :             .set(size);
    3737            0 :     }
    3738              : 
    3739            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    3740            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    3741            0 :     }
    3742              : 
    3743              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    3744              :     ///
    3745              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    3746              :     /// from an external API handler.
    3747              :     ///
    3748              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    3749              :     /// still bounded by tenant/timeline shutdown.
    3750            0 :     #[tracing::instrument(skip_all)]
    3751              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    3752              :         let timelines = self.timelines.lock().unwrap().clone();
    3753              : 
    3754            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    3755            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    3756            0 :             timeline.freeze_and_flush().await?;
    3757            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    3758            0 :             timeline.remote_client.wait_completion().await?;
    3759              : 
    3760            0 :             Ok(())
    3761            0 :         }
    3762              : 
    3763              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    3764              :         // aborted when this function's future is cancelled: they should stay alive
    3765              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    3766              :         // before Timeline shutdown completes.
    3767              :         let mut results = FuturesUnordered::new();
    3768              : 
    3769              :         for (_timeline_id, timeline) in timelines {
    3770              :             // Run each timeline's flush in a task holding the timeline's gate: this
    3771              :             // means that if this function's future is cancelled, the Timeline shutdown
    3772              :             // will still wait for any I/O in here to complete.
    3773              :             let Ok(gate) = timeline.gate.enter() else {
    3774              :                 continue;
    3775              :             };
    3776            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    3777              :             results.push(jh);
    3778              :         }
    3779              : 
    3780              :         while let Some(r) = results.next().await {
    3781              :             if let Err(e) = r {
    3782              :                 if !e.is_cancelled() && !e.is_panic() {
    3783              :                     tracing::error!("unexpected join error: {e:?}");
    3784              :                 }
    3785              :             }
    3786              :         }
    3787              : 
    3788              :         // The flushes we did above were just writes, but the Tenant might have had
    3789              :         // pending deletions as well from recent compaction/gc: we want to flush those
    3790              :         // as well.  This requires flushing the global delete queue.  This is cheap
    3791              :         // because it's typically a no-op.
    3792              :         match self.deletion_queue_client.flush_execute().await {
    3793              :             Ok(_) => {}
    3794              :             Err(DeletionQueueError::ShuttingDown) => {}
    3795              :         }
    3796              : 
    3797              :         Ok(())
    3798              :     }
    3799              : 
    3800            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    3801            0 :         self.tenant_conf.load().tenant_conf.clone()
    3802            0 :     }
    3803              : 
    3804              :     /// How much local storage would this tenant like to have?  It can cope with
    3805              :     /// less than this (via eviction and on-demand downloads), but this function enables
    3806              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    3807              :     /// by keeping important things on local disk.
    3808              :     ///
    3809              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    3810              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    3811              :     /// actually use more than they report here.
    3812            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    3813            0 :         let timelines = self.timelines.lock().unwrap();
    3814            0 : 
    3815            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    3816            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    3817            0 :         // of them is used actively enough to occupy space on disk.
    3818            0 :         timelines
    3819            0 :             .values()
    3820            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    3821            0 :             .max()
    3822            0 :             .unwrap_or(0)
    3823            0 :     }
    3824              : }
    3825              : 
    3826              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    3827              : /// to get bootstrap data for timeline initialization.
    3828            0 : async fn run_initdb(
    3829            0 :     conf: &'static PageServerConf,
    3830            0 :     initdb_target_dir: &Utf8Path,
    3831            0 :     pg_version: u32,
    3832            0 :     cancel: &CancellationToken,
    3833            0 : ) -> Result<(), InitdbError> {
    3834            0 :     let initdb_bin_path = conf
    3835            0 :         .pg_bin_dir(pg_version)
    3836            0 :         .map_err(InitdbError::Other)?
    3837            0 :         .join("initdb");
    3838            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    3839            0 :     info!(
    3840            0 :         "running {} in {}, libdir: {}",
    3841              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    3842              :     );
    3843              : 
    3844            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    3845              : 
    3846            0 :     let initdb_command = tokio::process::Command::new(&initdb_bin_path)
    3847            0 :         .args(["-D", initdb_target_dir.as_ref()])
    3848            0 :         .args(["-U", &conf.superuser])
    3849            0 :         .args(["-E", "utf8"])
    3850            0 :         .arg("--no-instructions")
    3851            0 :         .arg("--no-sync")
    3852            0 :         .env_clear()
    3853            0 :         .env("LD_LIBRARY_PATH", &initdb_lib_dir)
    3854            0 :         .env("DYLD_LIBRARY_PATH", &initdb_lib_dir)
    3855            0 :         .stdin(std::process::Stdio::null())
    3856            0 :         // stdout invocation produces the same output every time, we don't need it
    3857            0 :         .stdout(std::process::Stdio::null())
    3858            0 :         // we would be interested in the stderr output, if there was any
    3859            0 :         .stderr(std::process::Stdio::piped())
    3860            0 :         .spawn()?;
    3861              : 
    3862              :     // Ideally we'd select here with the cancellation token, but the problem is that
    3863              :     // we can't safely terminate initdb: it launches processes of its own, and killing
    3864              :     // initdb doesn't kill them. After we return from this function, we want the target
    3865              :     // directory to be able to be cleaned up.
    3866              :     // See https://github.com/neondatabase/neon/issues/6385
    3867            0 :     let initdb_output = initdb_command.wait_with_output().await?;
    3868            0 :     if !initdb_output.status.success() {
    3869            0 :         return Err(InitdbError::Failed(
    3870            0 :             initdb_output.status,
    3871            0 :             initdb_output.stderr,
    3872            0 :         ));
    3873            0 :     }
    3874            0 : 
    3875            0 :     // This isn't true cancellation support, see above. Still return an error to
    3876            0 :     // excercise the cancellation code path.
    3877            0 :     if cancel.is_cancelled() {
    3878            0 :         return Err(InitdbError::Cancelled);
    3879            0 :     }
    3880            0 : 
    3881            0 :     Ok(())
    3882            0 : }
    3883              : 
    3884              : /// Dump contents of a layer file to stdout.
    3885            0 : pub async fn dump_layerfile_from_path(
    3886            0 :     path: &Utf8Path,
    3887            0 :     verbose: bool,
    3888            0 :     ctx: &RequestContext,
    3889            0 : ) -> anyhow::Result<()> {
    3890              :     use std::os::unix::fs::FileExt;
    3891              : 
    3892              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    3893              :     // file.
    3894            0 :     let file = File::open(path)?;
    3895            0 :     let mut header_buf = [0u8; 2];
    3896            0 :     file.read_exact_at(&mut header_buf, 0)?;
    3897              : 
    3898            0 :     match u16::from_be_bytes(header_buf) {
    3899              :         crate::IMAGE_FILE_MAGIC => {
    3900            0 :             ImageLayer::new_for_path(path, file)?
    3901            0 :                 .dump(verbose, ctx)
    3902            0 :                 .await?
    3903              :         }
    3904              :         crate::DELTA_FILE_MAGIC => {
    3905            0 :             DeltaLayer::new_for_path(path, file)?
    3906            0 :                 .dump(verbose, ctx)
    3907            0 :                 .await?
    3908              :         }
    3909            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    3910              :     }
    3911              : 
    3912            0 :     Ok(())
    3913            0 : }
    3914              : 
    3915              : #[cfg(test)]
    3916              : pub(crate) mod harness {
    3917              :     use bytes::{Bytes, BytesMut};
    3918              :     use once_cell::sync::OnceCell;
    3919              :     use pageserver_api::models::ShardParameters;
    3920              :     use pageserver_api::shard::ShardIndex;
    3921              :     use utils::logging;
    3922              : 
    3923              :     use crate::deletion_queue::mock::MockDeletionQueue;
    3924              :     use crate::l0_flush::L0FlushConfig;
    3925              :     use crate::walredo::apply_neon;
    3926              :     use crate::{repository::Key, walrecord::NeonWalRecord};
    3927              : 
    3928              :     use super::*;
    3929              :     use hex_literal::hex;
    3930              :     use utils::id::TenantId;
    3931              : 
    3932              :     pub const TIMELINE_ID: TimelineId =
    3933              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    3934              :     pub const NEW_TIMELINE_ID: TimelineId =
    3935              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    3936              : 
    3937              :     /// Convenience function to create a page image with given string as the only content
    3938     15086214 :     pub fn test_img(s: &str) -> Bytes {
    3939     15086214 :         let mut buf = BytesMut::new();
    3940     15086214 :         buf.extend_from_slice(s.as_bytes());
    3941     15086214 :         buf.resize(64, 0);
    3942     15086214 : 
    3943     15086214 :         buf.freeze()
    3944     15086214 :     }
    3945              : 
    3946              :     impl From<TenantConf> for TenantConfOpt {
    3947          564 :         fn from(tenant_conf: TenantConf) -> Self {
    3948          564 :             Self {
    3949          564 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    3950          564 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    3951          564 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    3952          564 :                 compaction_period: Some(tenant_conf.compaction_period),
    3953          564 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    3954          564 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    3955          564 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    3956          564 :                 gc_period: Some(tenant_conf.gc_period),
    3957          564 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    3958          564 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    3959          564 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    3960          564 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    3961          564 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    3962          564 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    3963          564 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    3964          564 :                 evictions_low_residence_duration_metric_threshold: Some(
    3965          564 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    3966          564 :                 ),
    3967          564 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    3968          564 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    3969          564 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    3970          564 :                 image_layer_creation_check_threshold: Some(
    3971          564 :                     tenant_conf.image_layer_creation_check_threshold,
    3972          564 :                 ),
    3973          564 :                 switch_aux_file_policy: Some(tenant_conf.switch_aux_file_policy),
    3974          564 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    3975          564 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    3976          564 :             }
    3977          564 :         }
    3978              :     }
    3979              : 
    3980              :     pub struct TenantHarness {
    3981              :         pub conf: &'static PageServerConf,
    3982              :         pub tenant_conf: TenantConf,
    3983              :         pub tenant_shard_id: TenantShardId,
    3984              :         pub generation: Generation,
    3985              :         pub shard: ShardIndex,
    3986              :         pub remote_storage: GenericRemoteStorage,
    3987              :         pub remote_fs_dir: Utf8PathBuf,
    3988              :         pub deletion_queue: MockDeletionQueue,
    3989              :     }
    3990              : 
    3991              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    3992              : 
    3993          606 :     pub(crate) fn setup_logging() {
    3994          606 :         LOG_HANDLE.get_or_init(|| {
    3995          570 :             logging::init(
    3996          570 :                 logging::LogFormat::Test,
    3997          570 :                 // enable it in case the tests exercise code paths that use
    3998          570 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    3999          570 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    4000          570 :                 logging::Output::Stdout,
    4001          570 :             )
    4002          570 :             .expect("Failed to init test logging")
    4003          606 :         });
    4004          606 :     }
    4005              : 
    4006              :     impl TenantHarness {
    4007          564 :         pub async fn create_custom(
    4008          564 :             test_name: &'static str,
    4009          564 :             tenant_conf: TenantConf,
    4010          564 :             tenant_id: TenantId,
    4011          564 :             shard_identity: ShardIdentity,
    4012          564 :             generation: Generation,
    4013          564 :         ) -> anyhow::Result<Self> {
    4014          564 :             setup_logging();
    4015          564 : 
    4016          564 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    4017          564 :             let _ = fs::remove_dir_all(&repo_dir);
    4018          564 :             fs::create_dir_all(&repo_dir)?;
    4019              : 
    4020          564 :             let conf = PageServerConf::dummy_conf(repo_dir);
    4021          564 :             // Make a static copy of the config. This can never be free'd, but that's
    4022          564 :             // OK in a test.
    4023          564 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    4024          564 : 
    4025          564 :             let shard = shard_identity.shard_index();
    4026          564 :             let tenant_shard_id = TenantShardId {
    4027          564 :                 tenant_id,
    4028          564 :                 shard_number: shard.shard_number,
    4029          564 :                 shard_count: shard.shard_count,
    4030          564 :             };
    4031          564 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    4032          564 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    4033              : 
    4034              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    4035          564 :             let remote_fs_dir = conf.workdir.join("localfs");
    4036          564 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    4037          564 :             let config = RemoteStorageConfig {
    4038          564 :                 storage: RemoteStorageKind::LocalFs {
    4039          564 :                     local_path: remote_fs_dir.clone(),
    4040          564 :                 },
    4041          564 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    4042          564 :             };
    4043          564 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    4044          564 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    4045          564 : 
    4046          564 :             Ok(Self {
    4047          564 :                 conf,
    4048          564 :                 tenant_conf,
    4049          564 :                 tenant_shard_id,
    4050          564 :                 generation,
    4051          564 :                 shard,
    4052          564 :                 remote_storage,
    4053          564 :                 remote_fs_dir,
    4054          564 :                 deletion_queue,
    4055          564 :             })
    4056          564 :         }
    4057              : 
    4058          528 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    4059          528 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    4060          528 :             // The tests perform them manually if needed.
    4061          528 :             let tenant_conf = TenantConf {
    4062          528 :                 gc_period: Duration::ZERO,
    4063          528 :                 compaction_period: Duration::ZERO,
    4064          528 :                 ..TenantConf::default()
    4065          528 :             };
    4066          528 :             let tenant_id = TenantId::generate();
    4067          528 :             let shard = ShardIdentity::unsharded();
    4068          528 :             Self::create_custom(
    4069          528 :                 test_name,
    4070          528 :                 tenant_conf,
    4071          528 :                 tenant_id,
    4072          528 :                 shard,
    4073          528 :                 Generation::new(0xdeadbeef),
    4074          528 :             )
    4075            0 :             .await
    4076          528 :         }
    4077              : 
    4078           54 :         pub fn span(&self) -> tracing::Span {
    4079           54 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    4080           54 :         }
    4081              : 
    4082          564 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    4083          564 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    4084          564 :             (
    4085          564 :                 self.do_try_load(&ctx)
    4086         2222 :                     .await
    4087          564 :                     .expect("failed to load test tenant"),
    4088          564 :                 ctx,
    4089          564 :             )
    4090          564 :         }
    4091              : 
    4092         1128 :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    4093              :         pub(crate) async fn do_try_load(
    4094              :             &self,
    4095              :             ctx: &RequestContext,
    4096              :         ) -> anyhow::Result<Arc<Tenant>> {
    4097              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    4098              : 
    4099              :             let tenant = Arc::new(Tenant::new(
    4100              :                 TenantState::Loading,
    4101              :                 self.conf,
    4102              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    4103              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    4104              :                     self.generation,
    4105              :                     &ShardParameters::default(),
    4106              :                 ))
    4107              :                 .unwrap(),
    4108              :                 // This is a legacy/test code path: sharding isn't supported here.
    4109              :                 ShardIdentity::unsharded(),
    4110              :                 Some(walredo_mgr),
    4111              :                 self.tenant_shard_id,
    4112              :                 self.remote_storage.clone(),
    4113              :                 self.deletion_queue.new_client(),
    4114              :                 // TODO: ideally we should run all unit tests with both configs
    4115              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    4116              :             ));
    4117              : 
    4118              :             let preload = tenant
    4119              :                 .preload(&self.remote_storage, CancellationToken::new())
    4120              :                 .await?;
    4121              :             tenant.attach(Some(preload), ctx).await?;
    4122              : 
    4123              :             tenant.state.send_replace(TenantState::Active);
    4124              :             for timeline in tenant.timelines.lock().unwrap().values() {
    4125              :                 timeline.set_state(TimelineState::Active);
    4126              :             }
    4127              :             Ok(tenant)
    4128              :         }
    4129              : 
    4130            6 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    4131            6 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    4132            6 :         }
    4133              :     }
    4134              : 
    4135              :     // Mock WAL redo manager that doesn't do much
    4136              :     pub(crate) struct TestRedoManager;
    4137              : 
    4138              :     impl TestRedoManager {
    4139              :         /// # Cancel-Safety
    4140              :         ///
    4141              :         /// This method is cancellation-safe.
    4142          978 :         pub async fn request_redo(
    4143          978 :             &self,
    4144          978 :             key: Key,
    4145          978 :             lsn: Lsn,
    4146          978 :             base_img: Option<(Lsn, Bytes)>,
    4147          978 :             records: Vec<(Lsn, NeonWalRecord)>,
    4148          978 :             _pg_version: u32,
    4149          978 :         ) -> Result<Bytes, walredo::Error> {
    4150         1326 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    4151          978 :             if records_neon {
    4152              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    4153          978 :                 let base_img = base_img.expect("Neon WAL redo requires base image").1;
    4154          978 :                 let mut page = BytesMut::new();
    4155          978 :                 page.extend_from_slice(&base_img);
    4156         2304 :                 for (record_lsn, record) in records {
    4157         1326 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    4158              :                 }
    4159          978 :                 Ok(page.freeze())
    4160              :             } else {
    4161              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    4162            0 :                 let s = format!(
    4163            0 :                     "redo for {} to get to {}, with {} and {} records",
    4164            0 :                     key,
    4165            0 :                     lsn,
    4166            0 :                     if base_img.is_some() {
    4167            0 :                         "base image"
    4168              :                     } else {
    4169            0 :                         "no base image"
    4170              :                     },
    4171            0 :                     records.len()
    4172            0 :                 );
    4173            0 :                 println!("{s}");
    4174            0 : 
    4175            0 :                 Ok(test_img(&s))
    4176              :             }
    4177          978 :         }
    4178              :     }
    4179              : }
    4180              : 
    4181              : #[cfg(test)]
    4182              : mod tests {
    4183              :     use std::collections::{BTreeMap, BTreeSet};
    4184              : 
    4185              :     use super::*;
    4186              :     use crate::keyspace::KeySpaceAccum;
    4187              :     use crate::pgdatadir_mapping::AuxFilesDirectory;
    4188              :     use crate::repository::{Key, Value};
    4189              :     use crate::tenant::harness::*;
    4190              :     use crate::tenant::timeline::CompactFlags;
    4191              :     use crate::walrecord::NeonWalRecord;
    4192              :     use crate::DEFAULT_PG_VERSION;
    4193              :     use bytes::{Bytes, BytesMut};
    4194              :     use hex_literal::hex;
    4195              :     use itertools::Itertools;
    4196              :     use pageserver_api::key::{AUX_FILES_KEY, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
    4197              :     use pageserver_api::keyspace::KeySpace;
    4198              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    4199              :     use rand::{thread_rng, Rng};
    4200              :     use storage_layer::PersistentLayerKey;
    4201              :     use tests::storage_layer::ValuesReconstructState;
    4202              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    4203              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    4204              :     use timeline::{DeltaLayerTestDesc, GcInfo};
    4205              :     use utils::bin_ser::BeSer;
    4206              :     use utils::id::TenantId;
    4207              : 
    4208              :     static TEST_KEY: Lazy<Key> =
    4209           54 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    4210              : 
    4211              :     #[tokio::test]
    4212            6 :     async fn test_basic() -> anyhow::Result<()> {
    4213           24 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    4214            6 :         let tline = tenant
    4215            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    4216           12 :             .await?;
    4217            6 : 
    4218            6 :         let mut writer = tline.writer().await;
    4219            6 :         writer
    4220            6 :             .put(
    4221            6 :                 *TEST_KEY,
    4222            6 :                 Lsn(0x10),
    4223            6 :                 &Value::Image(test_img("foo at 0x10")),
    4224            6 :                 &ctx,
    4225            6 :             )
    4226            6 :             .await?;
    4227            6 :         writer.finish_write(Lsn(0x10));
    4228            6 :         drop(writer);
    4229            6 : 
    4230            6 :         let mut writer = tline.writer().await;
    4231            6 :         writer
    4232            6 :             .put(
    4233            6 :                 *TEST_KEY,
    4234            6 :                 Lsn(0x20),
    4235            6 :                 &Value::Image(test_img("foo at 0x20")),
    4236            6 :                 &ctx,
    4237            6 :             )
    4238            6 :             .await?;
    4239            6 :         writer.finish_write(Lsn(0x20));
    4240            6 :         drop(writer);
    4241            6 : 
    4242            6 :         assert_eq!(
    4243            6 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    4244            6 :             test_img("foo at 0x10")
    4245            6 :         );
    4246            6 :         assert_eq!(
    4247            6 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    4248            6 :             test_img("foo at 0x10")
    4249            6 :         );
    4250            6 :         assert_eq!(
    4251            6 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    4252            6 :             test_img("foo at 0x20")
    4253            6 :         );
    4254            6 : 
    4255            6 :         Ok(())
    4256            6 :     }
    4257              : 
    4258              :     #[tokio::test]
    4259            6 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    4260            6 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    4261            6 :             .await?
    4262            6 :             .load()
    4263           24 :             .await;
    4264            6 :         let _ = tenant
    4265            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4266           12 :             .await?;
    4267            6 : 
    4268            6 :         match tenant
    4269            6 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4270            6 :             .await
    4271            6 :         {
    4272            6 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    4273            6 :             Err(e) => assert_eq!(e.to_string(), "Already exists".to_string()),
    4274            6 :         }
    4275            6 : 
    4276            6 :         Ok(())
    4277            6 :     }
    4278              : 
    4279              :     /// Convenience function to create a page image with given string as the only content
    4280           30 :     pub fn test_value(s: &str) -> Value {
    4281           30 :         let mut buf = BytesMut::new();
    4282           30 :         buf.extend_from_slice(s.as_bytes());
    4283           30 :         Value::Image(buf.freeze())
    4284           30 :     }
    4285              : 
    4286              :     ///
    4287              :     /// Test branch creation
    4288              :     ///
    4289              :     #[tokio::test]
    4290            6 :     async fn test_branch() -> anyhow::Result<()> {
    4291            6 :         use std::str::from_utf8;
    4292            6 : 
    4293           24 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    4294            6 :         let tline = tenant
    4295            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4296           12 :             .await?;
    4297            6 :         let mut writer = tline.writer().await;
    4298            6 : 
    4299            6 :         #[allow(non_snake_case)]
    4300            6 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    4301            6 :         #[allow(non_snake_case)]
    4302            6 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    4303            6 : 
    4304            6 :         // Insert a value on the timeline
    4305            6 :         writer
    4306            6 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    4307            6 :             .await?;
    4308            6 :         writer
    4309            6 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    4310            6 :             .await?;
    4311            6 :         writer.finish_write(Lsn(0x20));
    4312            6 : 
    4313            6 :         writer
    4314            6 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    4315            6 :             .await?;
    4316            6 :         writer.finish_write(Lsn(0x30));
    4317            6 :         writer
    4318            6 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    4319            6 :             .await?;
    4320            6 :         writer.finish_write(Lsn(0x40));
    4321            6 : 
    4322            6 :         //assert_current_logical_size(&tline, Lsn(0x40));
    4323            6 : 
    4324            6 :         // Branch the history, modify relation differently on the new timeline
    4325            6 :         tenant
    4326            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    4327            6 :             .await?;
    4328            6 :         let newtline = tenant
    4329            6 :             .get_timeline(NEW_TIMELINE_ID, true)
    4330            6 :             .expect("Should have a local timeline");
    4331            6 :         let mut new_writer = newtline.writer().await;
    4332            6 :         new_writer
    4333            6 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    4334            6 :             .await?;
    4335            6 :         new_writer.finish_write(Lsn(0x40));
    4336            6 : 
    4337            6 :         // Check page contents on both branches
    4338            6 :         assert_eq!(
    4339            6 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    4340            6 :             "foo at 0x40"
    4341            6 :         );
    4342            6 :         assert_eq!(
    4343            6 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    4344            6 :             "bar at 0x40"
    4345            6 :         );
    4346            6 :         assert_eq!(
    4347            6 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    4348            6 :             "foobar at 0x20"
    4349            6 :         );
    4350            6 : 
    4351            6 :         //assert_current_logical_size(&tline, Lsn(0x40));
    4352            6 : 
    4353            6 :         Ok(())
    4354            6 :     }
    4355              : 
    4356           60 :     async fn make_some_layers(
    4357           60 :         tline: &Timeline,
    4358           60 :         start_lsn: Lsn,
    4359           60 :         ctx: &RequestContext,
    4360           60 :     ) -> anyhow::Result<()> {
    4361           60 :         let mut lsn = start_lsn;
    4362              :         {
    4363           60 :             let mut writer = tline.writer().await;
    4364              :             // Create a relation on the timeline
    4365           60 :             writer
    4366           60 :                 .put(
    4367           60 :                     *TEST_KEY,
    4368           60 :                     lsn,
    4369           60 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    4370           60 :                     ctx,
    4371           60 :                 )
    4372           30 :                 .await?;
    4373           60 :             writer.finish_write(lsn);
    4374           60 :             lsn += 0x10;
    4375           60 :             writer
    4376           60 :                 .put(
    4377           60 :                     *TEST_KEY,
    4378           60 :                     lsn,
    4379           60 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    4380           60 :                     ctx,
    4381           60 :                 )
    4382            0 :                 .await?;
    4383           60 :             writer.finish_write(lsn);
    4384           60 :             lsn += 0x10;
    4385           60 :         }
    4386           64 :         tline.freeze_and_flush().await?;
    4387              :         {
    4388           60 :             let mut writer = tline.writer().await;
    4389           60 :             writer
    4390           60 :                 .put(
    4391           60 :                     *TEST_KEY,
    4392           60 :                     lsn,
    4393           60 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    4394           60 :                     ctx,
    4395           60 :                 )
    4396           30 :                 .await?;
    4397           60 :             writer.finish_write(lsn);
    4398           60 :             lsn += 0x10;
    4399           60 :             writer
    4400           60 :                 .put(
    4401           60 :                     *TEST_KEY,
    4402           60 :                     lsn,
    4403           60 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    4404           60 :                     ctx,
    4405           60 :                 )
    4406            0 :                 .await?;
    4407           60 :             writer.finish_write(lsn);
    4408           60 :         }
    4409           60 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    4410           60 :     }
    4411              : 
    4412              :     #[tokio::test]
    4413            6 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    4414            6 :         let (tenant, ctx) =
    4415            6 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    4416            6 :                 .await?
    4417            6 :                 .load()
    4418           24 :                 .await;
    4419            6 :         let tline = tenant
    4420            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4421           12 :             .await?;
    4422           19 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4423            6 : 
    4424            6 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    4425            6 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    4426            6 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    4427            6 :         // below should fail.
    4428            6 :         tenant
    4429            6 :             .gc_iteration(
    4430            6 :                 Some(TIMELINE_ID),
    4431            6 :                 0x10,
    4432            6 :                 Duration::ZERO,
    4433            6 :                 &CancellationToken::new(),
    4434            6 :                 &ctx,
    4435            6 :             )
    4436            6 :             .await?;
    4437            6 : 
    4438            6 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    4439            6 :         match tenant
    4440            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    4441            6 :             .await
    4442            6 :         {
    4443            6 :             Ok(_) => panic!("branching should have failed"),
    4444            6 :             Err(err) => {
    4445            6 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    4446            6 :                     panic!("wrong error type")
    4447            6 :                 };
    4448            6 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    4449            6 :                 assert!(err
    4450            6 :                     .source()
    4451            6 :                     .unwrap()
    4452            6 :                     .to_string()
    4453            6 :                     .contains("we might've already garbage collected needed data"))
    4454            6 :             }
    4455            6 :         }
    4456            6 : 
    4457            6 :         Ok(())
    4458            6 :     }
    4459              : 
    4460              :     #[tokio::test]
    4461            6 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    4462            6 :         let (tenant, ctx) =
    4463            6 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    4464            6 :                 .await?
    4465            6 :                 .load()
    4466           24 :                 .await;
    4467            6 : 
    4468            6 :         let tline = tenant
    4469            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    4470           12 :             .await?;
    4471            6 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    4472            6 :         match tenant
    4473            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    4474            6 :             .await
    4475            6 :         {
    4476            6 :             Ok(_) => panic!("branching should have failed"),
    4477            6 :             Err(err) => {
    4478            6 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    4479            6 :                     panic!("wrong error type");
    4480            6 :                 };
    4481            6 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    4482            6 :                 assert!(&err
    4483            6 :                     .source()
    4484            6 :                     .unwrap()
    4485            6 :                     .to_string()
    4486            6 :                     .contains("is earlier than latest GC cutoff"));
    4487            6 :             }
    4488            6 :         }
    4489            6 : 
    4490            6 :         Ok(())
    4491            6 :     }
    4492              : 
    4493              :     /*
    4494              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    4495              :     // remove the old value, we'd need to work a little harder
    4496              :     #[tokio::test]
    4497              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    4498              :         let repo =
    4499              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    4500              :             .load();
    4501              : 
    4502              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    4503              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4504              : 
    4505              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    4506              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    4507              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    4508              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    4509              :             Ok(_) => panic!("request for page should have failed"),
    4510              :             Err(err) => assert!(err.to_string().contains("not found at")),
    4511              :         }
    4512              :         Ok(())
    4513              :     }
    4514              :      */
    4515              : 
    4516              :     #[tokio::test]
    4517            6 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    4518            6 :         let (tenant, ctx) =
    4519            6 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    4520            6 :                 .await?
    4521            6 :                 .load()
    4522           24 :                 .await;
    4523            6 :         let tline = tenant
    4524            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4525           12 :             .await?;
    4526           18 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4527            6 : 
    4528            6 :         tenant
    4529            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    4530            6 :             .await?;
    4531            6 :         let newtline = tenant
    4532            6 :             .get_timeline(NEW_TIMELINE_ID, true)
    4533            6 :             .expect("Should have a local timeline");
    4534            6 : 
    4535           18 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    4536            6 : 
    4537            6 :         tline.set_broken("test".to_owned());
    4538            6 : 
    4539            6 :         tenant
    4540            6 :             .gc_iteration(
    4541            6 :                 Some(TIMELINE_ID),
    4542            6 :                 0x10,
    4543            6 :                 Duration::ZERO,
    4544            6 :                 &CancellationToken::new(),
    4545            6 :                 &ctx,
    4546            6 :             )
    4547            6 :             .await?;
    4548            6 : 
    4549            6 :         // The branchpoints should contain all timelines, even ones marked
    4550            6 :         // as Broken.
    4551            6 :         {
    4552            6 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    4553            6 :             assert_eq!(branchpoints.len(), 1);
    4554            6 :             assert_eq!(branchpoints[0], (Lsn(0x40), NEW_TIMELINE_ID));
    4555            6 :         }
    4556            6 : 
    4557            6 :         // You can read the key from the child branch even though the parent is
    4558            6 :         // Broken, as long as you don't need to access data from the parent.
    4559            6 :         assert_eq!(
    4560           12 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    4561            6 :             test_img(&format!("foo at {}", Lsn(0x70)))
    4562            6 :         );
    4563            6 : 
    4564            6 :         // This needs to traverse to the parent, and fails.
    4565            6 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    4566            6 :         assert!(
    4567            6 :             err.to_string().starts_with(&format!(
    4568            6 :                 "bad state on timeline {}: Broken",
    4569            6 :                 tline.timeline_id
    4570            6 :             )),
    4571            6 :             "{err}"
    4572            6 :         );
    4573            6 : 
    4574            6 :         Ok(())
    4575            6 :     }
    4576              : 
    4577              :     #[tokio::test]
    4578            6 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    4579            6 :         let (tenant, ctx) =
    4580            6 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    4581            6 :                 .await?
    4582            6 :                 .load()
    4583           24 :                 .await;
    4584            6 :         let tline = tenant
    4585            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4586           12 :             .await?;
    4587           19 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4588            6 : 
    4589            6 :         tenant
    4590            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    4591            6 :             .await?;
    4592            6 :         let newtline = tenant
    4593            6 :             .get_timeline(NEW_TIMELINE_ID, true)
    4594            6 :             .expect("Should have a local timeline");
    4595            6 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    4596            6 :         tenant
    4597            6 :             .gc_iteration(
    4598            6 :                 Some(TIMELINE_ID),
    4599            6 :                 0x10,
    4600            6 :                 Duration::ZERO,
    4601            6 :                 &CancellationToken::new(),
    4602            6 :                 &ctx,
    4603            6 :             )
    4604            6 :             .await?;
    4605           12 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    4606            6 : 
    4607            6 :         Ok(())
    4608            6 :     }
    4609              :     #[tokio::test]
    4610            6 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    4611            6 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    4612            6 :             .await?
    4613            6 :             .load()
    4614           24 :             .await;
    4615            6 :         let tline = tenant
    4616            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4617           12 :             .await?;
    4618           18 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4619            6 : 
    4620            6 :         tenant
    4621            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    4622            6 :             .await?;
    4623            6 :         let newtline = tenant
    4624            6 :             .get_timeline(NEW_TIMELINE_ID, true)
    4625            6 :             .expect("Should have a local timeline");
    4626            6 : 
    4627           18 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    4628            6 : 
    4629            6 :         // run gc on parent
    4630            6 :         tenant
    4631            6 :             .gc_iteration(
    4632            6 :                 Some(TIMELINE_ID),
    4633            6 :                 0x10,
    4634            6 :                 Duration::ZERO,
    4635            6 :                 &CancellationToken::new(),
    4636            6 :                 &ctx,
    4637            6 :             )
    4638            6 :             .await?;
    4639            6 : 
    4640            6 :         // Check that the data is still accessible on the branch.
    4641            6 :         assert_eq!(
    4642           21 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    4643            6 :             test_img(&format!("foo at {}", Lsn(0x40)))
    4644            6 :         );
    4645            6 : 
    4646            6 :         Ok(())
    4647            6 :     }
    4648              : 
    4649              :     #[tokio::test]
    4650            6 :     async fn timeline_load() -> anyhow::Result<()> {
    4651            6 :         const TEST_NAME: &str = "timeline_load";
    4652            6 :         let harness = TenantHarness::create(TEST_NAME).await?;
    4653            6 :         {
    4654           21 :             let (tenant, ctx) = harness.load().await;
    4655            6 :             let tline = tenant
    4656            6 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    4657           12 :                 .await?;
    4658           18 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    4659            6 :             // so that all uploads finish & we can call harness.load() below again
    4660            6 :             tenant
    4661            6 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    4662            6 :                 .instrument(harness.span())
    4663            6 :                 .await
    4664            6 :                 .ok()
    4665            6 :                 .unwrap();
    4666            6 :         }
    4667            6 : 
    4668           19 :         let (tenant, _ctx) = harness.load().await;
    4669            6 :         tenant
    4670            6 :             .get_timeline(TIMELINE_ID, true)
    4671            6 :             .expect("cannot load timeline");
    4672            6 : 
    4673            6 :         Ok(())
    4674            6 :     }
    4675              : 
    4676              :     #[tokio::test]
    4677            6 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    4678            6 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    4679            6 :         let harness = TenantHarness::create(TEST_NAME).await?;
    4680            6 :         // create two timelines
    4681            6 :         {
    4682           24 :             let (tenant, ctx) = harness.load().await;
    4683            6 :             let tline = tenant
    4684            6 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4685           12 :                 .await?;
    4686            6 : 
    4687           18 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4688            6 : 
    4689            6 :             let child_tline = tenant
    4690            6 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    4691            6 :                 .await?;
    4692            6 :             child_tline.set_state(TimelineState::Active);
    4693            6 : 
    4694            6 :             let newtline = tenant
    4695            6 :                 .get_timeline(NEW_TIMELINE_ID, true)
    4696            6 :                 .expect("Should have a local timeline");
    4697            6 : 
    4698           18 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    4699            6 : 
    4700            6 :             // so that all uploads finish & we can call harness.load() below again
    4701            6 :             tenant
    4702            6 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    4703            6 :                 .instrument(harness.span())
    4704            7 :                 .await
    4705            6 :                 .ok()
    4706            6 :                 .unwrap();
    4707            6 :         }
    4708            6 : 
    4709            6 :         // check that both of them are initially unloaded
    4710           35 :         let (tenant, _ctx) = harness.load().await;
    4711            6 : 
    4712            6 :         // check that both, child and ancestor are loaded
    4713            6 :         let _child_tline = tenant
    4714            6 :             .get_timeline(NEW_TIMELINE_ID, true)
    4715            6 :             .expect("cannot get child timeline loaded");
    4716            6 : 
    4717            6 :         let _ancestor_tline = tenant
    4718            6 :             .get_timeline(TIMELINE_ID, true)
    4719            6 :             .expect("cannot get ancestor timeline loaded");
    4720            6 : 
    4721            6 :         Ok(())
    4722            6 :     }
    4723              : 
    4724              :     #[tokio::test]
    4725            6 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    4726            6 :         use storage_layer::AsLayerDesc;
    4727            6 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    4728            6 :             .await?
    4729            6 :             .load()
    4730           24 :             .await;
    4731            6 :         let tline = tenant
    4732            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    4733           12 :             .await?;
    4734           20 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    4735            6 : 
    4736            6 :         let layer_map = tline.layers.read().await;
    4737            6 :         let level0_deltas = layer_map
    4738            6 :             .layer_map()?
    4739            6 :             .level0_deltas()
    4740            6 :             .iter()
    4741           12 :             .map(|desc| layer_map.get_from_desc(desc))
    4742            6 :             .collect::<Vec<_>>();
    4743            6 : 
    4744            6 :         assert!(!level0_deltas.is_empty());
    4745            6 : 
    4746           18 :         for delta in level0_deltas {
    4747            6 :             // Ensure we are dumping a delta layer here
    4748           12 :             assert!(delta.layer_desc().is_delta);
    4749           24 :             delta.dump(true, &ctx).await.unwrap();
    4750            6 :         }
    4751            6 : 
    4752            6 :         Ok(())
    4753            6 :     }
    4754              : 
    4755              :     #[tokio::test]
    4756            6 :     async fn test_images() -> anyhow::Result<()> {
    4757           24 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    4758            6 :         let tline = tenant
    4759            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    4760           12 :             .await?;
    4761            6 : 
    4762            6 :         let mut writer = tline.writer().await;
    4763            6 :         writer
    4764            6 :             .put(
    4765            6 :                 *TEST_KEY,
    4766            6 :                 Lsn(0x10),
    4767            6 :                 &Value::Image(test_img("foo at 0x10")),
    4768            6 :                 &ctx,
    4769            6 :             )
    4770            6 :             .await?;
    4771            6 :         writer.finish_write(Lsn(0x10));
    4772            6 :         drop(writer);
    4773            6 : 
    4774            6 :         tline.freeze_and_flush().await?;
    4775            6 :         tline
    4776            6 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    4777            6 :             .await?;
    4778            6 : 
    4779            6 :         let mut writer = tline.writer().await;
    4780            6 :         writer
    4781            6 :             .put(
    4782            6 :                 *TEST_KEY,
    4783            6 :                 Lsn(0x20),
    4784            6 :                 &Value::Image(test_img("foo at 0x20")),
    4785            6 :                 &ctx,
    4786            6 :             )
    4787            6 :             .await?;
    4788            6 :         writer.finish_write(Lsn(0x20));
    4789            6 :         drop(writer);
    4790            6 : 
    4791            7 :         tline.freeze_and_flush().await?;
    4792            6 :         tline
    4793            6 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    4794            6 :             .await?;
    4795            6 : 
    4796            6 :         let mut writer = tline.writer().await;
    4797            6 :         writer
    4798            6 :             .put(
    4799            6 :                 *TEST_KEY,
    4800            6 :                 Lsn(0x30),
    4801            6 :                 &Value::Image(test_img("foo at 0x30")),
    4802            6 :                 &ctx,
    4803            6 :             )
    4804            6 :             .await?;
    4805            6 :         writer.finish_write(Lsn(0x30));
    4806            6 :         drop(writer);
    4807            6 : 
    4808            6 :         tline.freeze_and_flush().await?;
    4809            6 :         tline
    4810            6 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    4811            6 :             .await?;
    4812            6 : 
    4813            6 :         let mut writer = tline.writer().await;
    4814            6 :         writer
    4815            6 :             .put(
    4816            6 :                 *TEST_KEY,
    4817            6 :                 Lsn(0x40),
    4818            6 :                 &Value::Image(test_img("foo at 0x40")),
    4819            6 :                 &ctx,
    4820            6 :             )
    4821            6 :             .await?;
    4822            6 :         writer.finish_write(Lsn(0x40));
    4823            6 :         drop(writer);
    4824            6 : 
    4825            6 :         tline.freeze_and_flush().await?;
    4826            6 :         tline
    4827            6 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    4828            6 :             .await?;
    4829            6 : 
    4830            6 :         assert_eq!(
    4831           12 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    4832            6 :             test_img("foo at 0x10")
    4833            6 :         );
    4834            6 :         assert_eq!(
    4835           12 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    4836            6 :             test_img("foo at 0x10")
    4837            6 :         );
    4838            6 :         assert_eq!(
    4839            6 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    4840            6 :             test_img("foo at 0x20")
    4841            6 :         );
    4842            6 :         assert_eq!(
    4843           12 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    4844            6 :             test_img("foo at 0x30")
    4845            6 :         );
    4846            6 :         assert_eq!(
    4847           12 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    4848            6 :             test_img("foo at 0x40")
    4849            6 :         );
    4850            6 : 
    4851            6 :         Ok(())
    4852            6 :     }
    4853              : 
    4854           12 :     async fn bulk_insert_compact_gc(
    4855           12 :         tenant: &Tenant,
    4856           12 :         timeline: &Arc<Timeline>,
    4857           12 :         ctx: &RequestContext,
    4858           12 :         lsn: Lsn,
    4859           12 :         repeat: usize,
    4860           12 :         key_count: usize,
    4861           12 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    4862           12 :         let compact = true;
    4863       226439 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    4864           12 :     }
    4865              : 
    4866           24 :     async fn bulk_insert_maybe_compact_gc(
    4867           24 :         tenant: &Tenant,
    4868           24 :         timeline: &Arc<Timeline>,
    4869           24 :         ctx: &RequestContext,
    4870           24 :         mut lsn: Lsn,
    4871           24 :         repeat: usize,
    4872           24 :         key_count: usize,
    4873           24 :         compact: bool,
    4874           24 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    4875           24 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    4876           24 : 
    4877           24 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    4878           24 :         let mut blknum = 0;
    4879           24 : 
    4880           24 :         // Enforce that key range is monotonously increasing
    4881           24 :         let mut keyspace = KeySpaceAccum::new();
    4882           24 : 
    4883           24 :         let cancel = CancellationToken::new();
    4884           24 : 
    4885           24 :         for _ in 0..repeat {
    4886         1200 :             for _ in 0..key_count {
    4887     12000000 :                 test_key.field6 = blknum;
    4888     12000000 :                 let mut writer = timeline.writer().await;
    4889     12000000 :                 writer
    4890     12000000 :                     .put(
    4891     12000000 :                         test_key,
    4892     12000000 :                         lsn,
    4893     12000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    4894     12000000 :                         ctx,
    4895     12000000 :                     )
    4896         7943 :                     .await?;
    4897     12000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    4898     12000000 :                 writer.finish_write(lsn);
    4899     12000000 :                 drop(writer);
    4900     12000000 : 
    4901     12000000 :                 keyspace.add_key(test_key);
    4902     12000000 : 
    4903     12000000 :                 lsn = Lsn(lsn.0 + 0x10);
    4904     12000000 :                 blknum += 1;
    4905              :             }
    4906              : 
    4907         1200 :             timeline.freeze_and_flush().await?;
    4908         1200 :             if compact {
    4909              :                 // this requires timeline to be &Arc<Timeline>
    4910       129540 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    4911          600 :             }
    4912              : 
    4913              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    4914              :             // originally was.
    4915         1200 :             let res = tenant
    4916         1200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    4917         1198 :                 .await?;
    4918              : 
    4919         1200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    4920              :         }
    4921              : 
    4922           24 :         Ok(inserted)
    4923           24 :     }
    4924              : 
    4925              :     //
    4926              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    4927              :     // Repeat 50 times.
    4928              :     //
    4929              :     #[tokio::test]
    4930            6 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    4931            6 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    4932           24 :         let (tenant, ctx) = harness.load().await;
    4933            6 :         let tline = tenant
    4934            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    4935           12 :             .await?;
    4936            6 : 
    4937            6 :         let lsn = Lsn(0x10);
    4938       113220 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    4939            6 : 
    4940            6 :         Ok(())
    4941            6 :     }
    4942              : 
    4943              :     // Test the vectored get real implementation against a simple sequential implementation.
    4944              :     //
    4945              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    4946              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    4947              :     // grow to the right on the X axis.
    4948              :     //                       [Delta]
    4949              :     //                 [Delta]
    4950              :     //           [Delta]
    4951              :     //    [Delta]
    4952              :     // ------------ Image ---------------
    4953              :     //
    4954              :     // After layer generation we pick the ranges to query as follows:
    4955              :     // 1. The beginning of each delta layer
    4956              :     // 2. At the seam between two adjacent delta layers
    4957              :     //
    4958              :     // There's one major downside to this test: delta layers only contains images,
    4959              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    4960              :     #[tokio::test]
    4961            6 :     async fn test_get_vectored() -> anyhow::Result<()> {
    4962            6 :         let harness = TenantHarness::create("test_get_vectored").await?;
    4963           24 :         let (tenant, ctx) = harness.load().await;
    4964            6 :         let tline = tenant
    4965            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    4966           12 :             .await?;
    4967            6 : 
    4968            6 :         let lsn = Lsn(0x10);
    4969       113219 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    4970            6 : 
    4971            6 :         let guard = tline.layers.read().await;
    4972            6 :         let lm = guard.layer_map()?;
    4973            6 : 
    4974            6 :         lm.dump(true, &ctx).await?;
    4975            6 : 
    4976            6 :         let mut reads = Vec::new();
    4977            6 :         let mut prev = None;
    4978           36 :         lm.iter_historic_layers().for_each(|desc| {
    4979           36 :             if !desc.is_delta() {
    4980            6 :                 prev = Some(desc.clone());
    4981            6 :                 return;
    4982           30 :             }
    4983           30 : 
    4984           30 :             let start = desc.key_range.start;
    4985           30 :             let end = desc
    4986           30 :                 .key_range
    4987           30 :                 .start
    4988           30 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    4989           30 :             reads.push(KeySpace {
    4990           30 :                 ranges: vec![start..end],
    4991           30 :             });
    4992            6 : 
    4993           30 :             if let Some(prev) = &prev {
    4994           30 :                 if !prev.is_delta() {
    4995           30 :                     return;
    4996            6 :                 }
    4997            0 : 
    4998            0 :                 let first_range = Key {
    4999            0 :                     field6: prev.key_range.end.field6 - 4,
    5000            0 :                     ..prev.key_range.end
    5001            0 :                 }..prev.key_range.end;
    5002            0 : 
    5003            0 :                 let second_range = desc.key_range.start..Key {
    5004            0 :                     field6: desc.key_range.start.field6 + 4,
    5005            0 :                     ..desc.key_range.start
    5006            0 :                 };
    5007            0 : 
    5008            0 :                 reads.push(KeySpace {
    5009            0 :                     ranges: vec![first_range, second_range],
    5010            0 :                 });
    5011            6 :             };
    5012            6 : 
    5013            6 :             prev = Some(desc.clone());
    5014           36 :         });
    5015            6 : 
    5016            6 :         drop(guard);
    5017            6 : 
    5018            6 :         // Pick a big LSN such that we query over all the changes.
    5019            6 :         let reads_lsn = Lsn(u64::MAX - 1);
    5020            6 : 
    5021           36 :         for read in reads {
    5022           30 :             info!("Doing vectored read on {:?}", read);
    5023            6 : 
    5024           30 :             let vectored_res = tline
    5025           30 :                 .get_vectored_impl(
    5026           30 :                     read.clone(),
    5027           30 :                     reads_lsn,
    5028           30 :                     &mut ValuesReconstructState::new(),
    5029           30 :                     &ctx,
    5030           30 :                 )
    5031           75 :                 .await;
    5032            6 : 
    5033           30 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    5034           30 :             let mut expect_missing = false;
    5035           30 :             let mut key = read.start().unwrap();
    5036          990 :             while key != read.end().unwrap() {
    5037          960 :                 if let Some(lsns) = inserted.get(&key) {
    5038          960 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    5039          960 :                     match expected_lsn {
    5040          960 :                         Some(lsn) => {
    5041          960 :                             expected_lsns.insert(key, *lsn);
    5042          960 :                         }
    5043            6 :                         None => {
    5044            6 :                             expect_missing = true;
    5045            0 :                             break;
    5046            6 :                         }
    5047            6 :                     }
    5048            6 :                 } else {
    5049            6 :                     expect_missing = true;
    5050            0 :                     break;
    5051            6 :                 }
    5052            6 : 
    5053          960 :                 key = key.next();
    5054            6 :             }
    5055            6 : 
    5056           30 :             if expect_missing {
    5057            6 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    5058            6 :             } else {
    5059          960 :                 for (key, image) in vectored_res? {
    5060          960 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    5061          960 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    5062          960 :                     assert_eq!(image?, expected_image);
    5063            6 :                 }
    5064            6 :             }
    5065            6 :         }
    5066            6 : 
    5067            6 :         Ok(())
    5068            6 :     }
    5069              : 
    5070              :     #[tokio::test]
    5071            6 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    5072            6 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    5073            6 : 
    5074           21 :         let (tenant, ctx) = harness.load().await;
    5075            6 :         let tline = tenant
    5076            6 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    5077            6 :             .await?;
    5078            6 :         let tline = tline.raw_timeline().unwrap();
    5079            6 : 
    5080            6 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    5081            6 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    5082            6 :         modification.set_lsn(Lsn(0x1008))?;
    5083            6 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    5084            6 :         modification.commit(&ctx).await?;
    5085            6 : 
    5086            6 :         let child_timeline_id = TimelineId::generate();
    5087            6 :         tenant
    5088            6 :             .branch_timeline_test(
    5089            6 :                 tline,
    5090            6 :                 child_timeline_id,
    5091            6 :                 Some(tline.get_last_record_lsn()),
    5092            6 :                 &ctx,
    5093            6 :             )
    5094            6 :             .await?;
    5095            6 : 
    5096            6 :         let child_timeline = tenant
    5097            6 :             .get_timeline(child_timeline_id, true)
    5098            6 :             .expect("Should have the branched timeline");
    5099            6 : 
    5100            6 :         let aux_keyspace = KeySpace {
    5101            6 :             ranges: vec![NON_INHERITED_RANGE],
    5102            6 :         };
    5103            6 :         let read_lsn = child_timeline.get_last_record_lsn();
    5104            6 : 
    5105            6 :         let vectored_res = child_timeline
    5106            6 :             .get_vectored_impl(
    5107            6 :                 aux_keyspace.clone(),
    5108            6 :                 read_lsn,
    5109            6 :                 &mut ValuesReconstructState::new(),
    5110            6 :                 &ctx,
    5111            6 :             )
    5112            6 :             .await;
    5113            6 : 
    5114            6 :         let images = vectored_res?;
    5115            6 :         assert!(images.is_empty());
    5116            6 :         Ok(())
    5117            6 :     }
    5118              : 
    5119              :     // Test that vectored get handles layer gaps correctly
    5120              :     // by advancing into the next ancestor timeline if required.
    5121              :     //
    5122              :     // The test generates timelines that look like the diagram below.
    5123              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    5124              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    5125              :     //
    5126              :     // ```
    5127              :     //-------------------------------+
    5128              :     //                          ...  |
    5129              :     //               [   L1   ]      |
    5130              :     //     [ / L1   ]                | Child Timeline
    5131              :     // ...                           |
    5132              :     // ------------------------------+
    5133              :     //     [ X L1   ]                | Parent Timeline
    5134              :     // ------------------------------+
    5135              :     // ```
    5136              :     #[tokio::test]
    5137            6 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    5138            6 :         let tenant_conf = TenantConf {
    5139            6 :             // Make compaction deterministic
    5140            6 :             gc_period: Duration::ZERO,
    5141            6 :             compaction_period: Duration::ZERO,
    5142            6 :             // Encourage creation of L1 layers
    5143            6 :             checkpoint_distance: 16 * 1024,
    5144            6 :             compaction_target_size: 8 * 1024,
    5145            6 :             ..TenantConf::default()
    5146            6 :         };
    5147            6 : 
    5148            6 :         let harness = TenantHarness::create_custom(
    5149            6 :             "test_get_vectored_key_gap",
    5150            6 :             tenant_conf,
    5151            6 :             TenantId::generate(),
    5152            6 :             ShardIdentity::unsharded(),
    5153            6 :             Generation::new(0xdeadbeef),
    5154            6 :         )
    5155            6 :         .await?;
    5156           24 :         let (tenant, ctx) = harness.load().await;
    5157            6 : 
    5158            6 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5159            6 :         let gap_at_key = current_key.add(100);
    5160            6 :         let mut current_lsn = Lsn(0x10);
    5161            6 : 
    5162            6 :         const KEY_COUNT: usize = 10_000;
    5163            6 : 
    5164            6 :         let timeline_id = TimelineId::generate();
    5165            6 :         let current_timeline = tenant
    5166            6 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    5167           12 :             .await?;
    5168            6 : 
    5169            6 :         current_lsn += 0x100;
    5170            6 : 
    5171            6 :         let mut writer = current_timeline.writer().await;
    5172            6 :         writer
    5173            6 :             .put(
    5174            6 :                 gap_at_key,
    5175            6 :                 current_lsn,
    5176            6 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    5177            6 :                 &ctx,
    5178            6 :             )
    5179            6 :             .await?;
    5180            6 :         writer.finish_write(current_lsn);
    5181            6 :         drop(writer);
    5182            6 : 
    5183            6 :         let mut latest_lsns = HashMap::new();
    5184            6 :         latest_lsns.insert(gap_at_key, current_lsn);
    5185            6 : 
    5186            6 :         current_timeline.freeze_and_flush().await?;
    5187            6 : 
    5188            6 :         let child_timeline_id = TimelineId::generate();
    5189            6 : 
    5190            6 :         tenant
    5191            6 :             .branch_timeline_test(
    5192            6 :                 &current_timeline,
    5193            6 :                 child_timeline_id,
    5194            6 :                 Some(current_lsn),
    5195            6 :                 &ctx,
    5196            6 :             )
    5197            6 :             .await?;
    5198            6 :         let child_timeline = tenant
    5199            6 :             .get_timeline(child_timeline_id, true)
    5200            6 :             .expect("Should have the branched timeline");
    5201            6 : 
    5202        60006 :         for i in 0..KEY_COUNT {
    5203        60000 :             if current_key == gap_at_key {
    5204            6 :                 current_key = current_key.next();
    5205            6 :                 continue;
    5206        59994 :             }
    5207        59994 : 
    5208        59994 :             current_lsn += 0x10;
    5209            6 : 
    5210        59994 :             let mut writer = child_timeline.writer().await;
    5211        59994 :             writer
    5212        59994 :                 .put(
    5213        59994 :                     current_key,
    5214        59994 :                     current_lsn,
    5215        59994 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    5216        59994 :                     &ctx,
    5217        59994 :                 )
    5218          202 :                 .await?;
    5219        59994 :             writer.finish_write(current_lsn);
    5220        59994 :             drop(writer);
    5221        59994 : 
    5222        59994 :             latest_lsns.insert(current_key, current_lsn);
    5223        59994 :             current_key = current_key.next();
    5224        59994 : 
    5225        59994 :             // Flush every now and then to encourage layer file creation.
    5226        59994 :             if i % 500 == 0 {
    5227          127 :                 child_timeline.freeze_and_flush().await?;
    5228        59874 :             }
    5229            6 :         }
    5230            6 : 
    5231            6 :         child_timeline.freeze_and_flush().await?;
    5232            6 :         let mut flags = EnumSet::new();
    5233            6 :         flags.insert(CompactFlags::ForceRepartition);
    5234            6 :         child_timeline
    5235            6 :             .compact(&CancellationToken::new(), flags, &ctx)
    5236         6981 :             .await?;
    5237            6 : 
    5238            6 :         let key_near_end = {
    5239            6 :             let mut tmp = current_key;
    5240            6 :             tmp.field6 -= 10;
    5241            6 :             tmp
    5242            6 :         };
    5243            6 : 
    5244            6 :         let key_near_gap = {
    5245            6 :             let mut tmp = gap_at_key;
    5246            6 :             tmp.field6 -= 10;
    5247            6 :             tmp
    5248            6 :         };
    5249            6 : 
    5250            6 :         let read = KeySpace {
    5251            6 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    5252            6 :         };
    5253            6 :         let results = child_timeline
    5254            6 :             .get_vectored_impl(
    5255            6 :                 read.clone(),
    5256            6 :                 current_lsn,
    5257            6 :                 &mut ValuesReconstructState::new(),
    5258            6 :                 &ctx,
    5259            6 :             )
    5260           45 :             .await?;
    5261            6 : 
    5262          132 :         for (key, img_res) in results {
    5263          126 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    5264          126 :             assert_eq!(img_res?, expected);
    5265            6 :         }
    5266            6 : 
    5267            6 :         Ok(())
    5268            6 :     }
    5269              : 
    5270              :     // Test that vectored get descends into ancestor timelines correctly and
    5271              :     // does not return an image that's newer than requested.
    5272              :     //
    5273              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    5274              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    5275              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    5276              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    5277              :     // order to avoid returning an image that's too new. The test below constructs such
    5278              :     // a timeline setup and does a few queries around the Lsn of each page image.
    5279              :     // ```
    5280              :     //    LSN
    5281              :     //     ^
    5282              :     //     |
    5283              :     //     |
    5284              :     // 500 | --------------------------------------> branch point
    5285              :     // 400 |        X
    5286              :     // 300 |        X
    5287              :     // 200 | --------------------------------------> requested lsn
    5288              :     // 100 |        X
    5289              :     //     |---------------------------------------> Key
    5290              :     //              |
    5291              :     //              ------> requested key
    5292              :     //
    5293              :     // Legend:
    5294              :     // * X - page images
    5295              :     // ```
    5296              :     #[tokio::test]
    5297            6 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    5298            6 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    5299           24 :         let (tenant, ctx) = harness.load().await;
    5300            6 : 
    5301            6 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5302            6 :         let end_key = start_key.add(1000);
    5303            6 :         let child_gap_at_key = start_key.add(500);
    5304            6 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    5305            6 : 
    5306            6 :         let mut current_lsn = Lsn(0x10);
    5307            6 : 
    5308            6 :         let timeline_id = TimelineId::generate();
    5309            6 :         let parent_timeline = tenant
    5310            6 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    5311           12 :             .await?;
    5312            6 : 
    5313            6 :         current_lsn += 0x100;
    5314            6 : 
    5315           24 :         for _ in 0..3 {
    5316           18 :             let mut key = start_key;
    5317        18018 :             while key < end_key {
    5318        18000 :                 current_lsn += 0x10;
    5319        18000 : 
    5320        18000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    5321            6 : 
    5322        18000 :                 let mut writer = parent_timeline.writer().await;
    5323        18000 :                 writer
    5324        18000 :                     .put(
    5325        18000 :                         key,
    5326        18000 :                         current_lsn,
    5327        18000 :                         &Value::Image(test_img(&image_value)),
    5328        18000 :                         &ctx,
    5329        18000 :                     )
    5330           18 :                     .await?;
    5331        18000 :                 writer.finish_write(current_lsn);
    5332        18000 : 
    5333        18000 :                 if key == child_gap_at_key {
    5334           18 :                     parent_gap_lsns.insert(current_lsn, image_value);
    5335        17982 :                 }
    5336            6 : 
    5337        18000 :                 key = key.next();
    5338            6 :             }
    5339            6 : 
    5340           18 :             parent_timeline.freeze_and_flush().await?;
    5341            6 :         }
    5342            6 : 
    5343            6 :         let child_timeline_id = TimelineId::generate();
    5344            6 : 
    5345            6 :         let child_timeline = tenant
    5346            6 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    5347            6 :             .await?;
    5348            6 : 
    5349            6 :         let mut key = start_key;
    5350         6006 :         while key < end_key {
    5351         6000 :             if key == child_gap_at_key {
    5352            6 :                 key = key.next();
    5353            6 :                 continue;
    5354         5994 :             }
    5355         5994 : 
    5356         5994 :             current_lsn += 0x10;
    5357            6 : 
    5358         5994 :             let mut writer = child_timeline.writer().await;
    5359         5994 :             writer
    5360         5994 :                 .put(
    5361         5994 :                     key,
    5362         5994 :                     current_lsn,
    5363         5994 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    5364         5994 :                     &ctx,
    5365         5994 :                 )
    5366           51 :                 .await?;
    5367         5994 :             writer.finish_write(current_lsn);
    5368         5994 : 
    5369         5994 :             key = key.next();
    5370            6 :         }
    5371            6 : 
    5372            6 :         child_timeline.freeze_and_flush().await?;
    5373            6 : 
    5374            6 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    5375            6 :         let mut query_lsns = Vec::new();
    5376           18 :         for image_lsn in parent_gap_lsns.keys().rev() {
    5377          108 :             for offset in lsn_offsets {
    5378           90 :                 query_lsns.push(Lsn(image_lsn
    5379           90 :                     .0
    5380           90 :                     .checked_add_signed(offset)
    5381           90 :                     .expect("Shouldn't overflow")));
    5382           90 :             }
    5383            6 :         }
    5384            6 : 
    5385           96 :         for query_lsn in query_lsns {
    5386           90 :             let results = child_timeline
    5387           90 :                 .get_vectored_impl(
    5388           90 :                     KeySpace {
    5389           90 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    5390           90 :                     },
    5391           90 :                     query_lsn,
    5392           90 :                     &mut ValuesReconstructState::new(),
    5393           90 :                     &ctx,
    5394           90 :                 )
    5395           87 :                 .await;
    5396            6 : 
    5397           90 :             let expected_item = parent_gap_lsns
    5398           90 :                 .iter()
    5399           90 :                 .rev()
    5400          204 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    5401           90 : 
    5402           90 :             info!(
    5403            6 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    5404            6 :                 query_lsn, expected_item
    5405            6 :             );
    5406            6 : 
    5407           90 :             match expected_item {
    5408           78 :                 Some((_, img_value)) => {
    5409           78 :                     let key_results = results.expect("No vectored get error expected");
    5410           78 :                     let key_result = &key_results[&child_gap_at_key];
    5411           78 :                     let returned_img = key_result
    5412           78 :                         .as_ref()
    5413           78 :                         .expect("No page reconstruct error expected");
    5414           78 : 
    5415           78 :                     info!(
    5416            6 :                         "Vectored read at LSN {} returned image {}",
    5417            0 :                         query_lsn,
    5418            0 :                         std::str::from_utf8(returned_img)?
    5419            6 :                     );
    5420           78 :                     assert_eq!(*returned_img, test_img(img_value));
    5421            6 :                 }
    5422            6 :                 None => {
    5423           12 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    5424            6 :                 }
    5425            6 :             }
    5426            6 :         }
    5427            6 : 
    5428            6 :         Ok(())
    5429            6 :     }
    5430              : 
    5431              :     #[tokio::test]
    5432            6 :     async fn test_random_updates() -> anyhow::Result<()> {
    5433            6 :         let names_algorithms = [
    5434            6 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    5435            6 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    5436            6 :         ];
    5437           18 :         for (name, algorithm) in names_algorithms {
    5438       289215 :             test_random_updates_algorithm(name, algorithm).await?;
    5439            6 :         }
    5440            6 :         Ok(())
    5441            6 :     }
    5442              : 
    5443           12 :     async fn test_random_updates_algorithm(
    5444           12 :         name: &'static str,
    5445           12 :         compaction_algorithm: CompactionAlgorithm,
    5446           12 :     ) -> anyhow::Result<()> {
    5447           12 :         let mut harness = TenantHarness::create(name).await?;
    5448           12 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    5449           12 :             kind: compaction_algorithm,
    5450           12 :         };
    5451           48 :         let (tenant, ctx) = harness.load().await;
    5452           12 :         let tline = tenant
    5453           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5454           21 :             .await?;
    5455              : 
    5456              :         const NUM_KEYS: usize = 1000;
    5457           12 :         let cancel = CancellationToken::new();
    5458           12 : 
    5459           12 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5460           12 :         let mut test_key_end = test_key;
    5461           12 :         test_key_end.field6 = NUM_KEYS as u32;
    5462           12 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    5463           12 : 
    5464           12 :         let mut keyspace = KeySpaceAccum::new();
    5465           12 : 
    5466           12 :         // Track when each page was last modified. Used to assert that
    5467           12 :         // a read sees the latest page version.
    5468           12 :         let mut updated = [Lsn(0); NUM_KEYS];
    5469           12 : 
    5470           12 :         let mut lsn = Lsn(0x10);
    5471              :         #[allow(clippy::needless_range_loop)]
    5472        12012 :         for blknum in 0..NUM_KEYS {
    5473        12000 :             lsn = Lsn(lsn.0 + 0x10);
    5474        12000 :             test_key.field6 = blknum as u32;
    5475        12000 :             let mut writer = tline.writer().await;
    5476        12000 :             writer
    5477        12000 :                 .put(
    5478        12000 :                     test_key,
    5479        12000 :                     lsn,
    5480        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5481        12000 :                     &ctx,
    5482        12000 :                 )
    5483           12 :                 .await?;
    5484        12000 :             writer.finish_write(lsn);
    5485        12000 :             updated[blknum] = lsn;
    5486        12000 :             drop(writer);
    5487        12000 : 
    5488        12000 :             keyspace.add_key(test_key);
    5489              :         }
    5490              : 
    5491          612 :         for _ in 0..50 {
    5492       600600 :             for _ in 0..NUM_KEYS {
    5493       600000 :                 lsn = Lsn(lsn.0 + 0x10);
    5494       600000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    5495       600000 :                 test_key.field6 = blknum as u32;
    5496       600000 :                 let mut writer = tline.writer().await;
    5497       600000 :                 writer
    5498       600000 :                     .put(
    5499       600000 :                         test_key,
    5500       600000 :                         lsn,
    5501       600000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5502       600000 :                         &ctx,
    5503       600000 :                     )
    5504          714 :                     .await?;
    5505       600000 :                 writer.finish_write(lsn);
    5506       600000 :                 drop(writer);
    5507       600000 :                 updated[blknum] = lsn;
    5508              :             }
    5509              : 
    5510              :             // Read all the blocks
    5511       600000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    5512       600000 :                 test_key.field6 = blknum as u32;
    5513       600000 :                 assert_eq!(
    5514       600000 :                     tline.get(test_key, lsn, &ctx).await?,
    5515       600000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    5516              :                 );
    5517              :             }
    5518              : 
    5519              :             // Perform a cycle of flush, and GC
    5520          612 :             tline.freeze_and_flush().await?;
    5521          600 :             tenant
    5522          600 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    5523          578 :                 .await?;
    5524              :         }
    5525              : 
    5526           12 :         Ok(())
    5527           12 :     }
    5528              : 
    5529              :     #[tokio::test]
    5530            6 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    5531            6 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    5532            6 :             .await?
    5533            6 :             .load()
    5534           21 :             .await;
    5535            6 :         let mut tline = tenant
    5536            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5537           12 :             .await?;
    5538            6 : 
    5539            6 :         const NUM_KEYS: usize = 1000;
    5540            6 : 
    5541            6 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5542            6 : 
    5543            6 :         let mut keyspace = KeySpaceAccum::new();
    5544            6 : 
    5545            6 :         let cancel = CancellationToken::new();
    5546            6 : 
    5547            6 :         // Track when each page was last modified. Used to assert that
    5548            6 :         // a read sees the latest page version.
    5549            6 :         let mut updated = [Lsn(0); NUM_KEYS];
    5550            6 : 
    5551            6 :         let mut lsn = Lsn(0x10);
    5552            6 :         #[allow(clippy::needless_range_loop)]
    5553         6006 :         for blknum in 0..NUM_KEYS {
    5554         6000 :             lsn = Lsn(lsn.0 + 0x10);
    5555         6000 :             test_key.field6 = blknum as u32;
    5556         6000 :             let mut writer = tline.writer().await;
    5557         6000 :             writer
    5558         6000 :                 .put(
    5559         6000 :                     test_key,
    5560         6000 :                     lsn,
    5561         6000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5562         6000 :                     &ctx,
    5563         6000 :                 )
    5564            6 :                 .await?;
    5565         6000 :             writer.finish_write(lsn);
    5566         6000 :             updated[blknum] = lsn;
    5567         6000 :             drop(writer);
    5568         6000 : 
    5569         6000 :             keyspace.add_key(test_key);
    5570            6 :         }
    5571            6 : 
    5572          306 :         for _ in 0..50 {
    5573          300 :             let new_tline_id = TimelineId::generate();
    5574          300 :             tenant
    5575          300 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    5576            6 :                 .await?;
    5577          300 :             tline = tenant
    5578          300 :                 .get_timeline(new_tline_id, true)
    5579          300 :                 .expect("Should have the branched timeline");
    5580            6 : 
    5581       300300 :             for _ in 0..NUM_KEYS {
    5582       300000 :                 lsn = Lsn(lsn.0 + 0x10);
    5583       300000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    5584       300000 :                 test_key.field6 = blknum as u32;
    5585       300000 :                 let mut writer = tline.writer().await;
    5586       300000 :                 writer
    5587       300000 :                     .put(
    5588       300000 :                         test_key,
    5589       300000 :                         lsn,
    5590       300000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5591       300000 :                         &ctx,
    5592       300000 :                     )
    5593         2469 :                     .await?;
    5594       300000 :                 println!("updating {} at {}", blknum, lsn);
    5595       300000 :                 writer.finish_write(lsn);
    5596       300000 :                 drop(writer);
    5597       300000 :                 updated[blknum] = lsn;
    5598            6 :             }
    5599            6 : 
    5600            6 :             // Read all the blocks
    5601       300000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    5602       300000 :                 test_key.field6 = blknum as u32;
    5603       300000 :                 assert_eq!(
    5604       300000 :                     tline.get(test_key, lsn, &ctx).await?,
    5605       300000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    5606            6 :                 );
    5607            6 :             }
    5608            6 : 
    5609            6 :             // Perform a cycle of flush, compact, and GC
    5610          307 :             tline.freeze_and_flush().await?;
    5611        45346 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    5612          300 :             tenant
    5613          300 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    5614          260 :                 .await?;
    5615            6 :         }
    5616            6 : 
    5617            6 :         Ok(())
    5618            6 :     }
    5619              : 
    5620              :     #[tokio::test]
    5621            6 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    5622            6 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    5623            6 :             .await?
    5624            6 :             .load()
    5625           24 :             .await;
    5626            6 :         let mut tline = tenant
    5627            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5628           12 :             .await?;
    5629            6 : 
    5630            6 :         const NUM_KEYS: usize = 100;
    5631            6 :         const NUM_TLINES: usize = 50;
    5632            6 : 
    5633            6 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5634            6 :         // Track page mutation lsns across different timelines.
    5635            6 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    5636            6 : 
    5637            6 :         let mut lsn = Lsn(0x10);
    5638            6 : 
    5639            6 :         #[allow(clippy::needless_range_loop)]
    5640          306 :         for idx in 0..NUM_TLINES {
    5641          300 :             let new_tline_id = TimelineId::generate();
    5642          300 :             tenant
    5643          300 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    5644            6 :                 .await?;
    5645          300 :             tline = tenant
    5646          300 :                 .get_timeline(new_tline_id, true)
    5647          300 :                 .expect("Should have the branched timeline");
    5648            6 : 
    5649        30300 :             for _ in 0..NUM_KEYS {
    5650        30000 :                 lsn = Lsn(lsn.0 + 0x10);
    5651        30000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    5652        30000 :                 test_key.field6 = blknum as u32;
    5653        30000 :                 let mut writer = tline.writer().await;
    5654        30000 :                 writer
    5655        30000 :                     .put(
    5656        30000 :                         test_key,
    5657        30000 :                         lsn,
    5658        30000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    5659        30000 :                         &ctx,
    5660        30000 :                     )
    5661          264 :                     .await?;
    5662        30000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    5663        30000 :                 writer.finish_write(lsn);
    5664        30000 :                 drop(writer);
    5665        30000 :                 updated[idx][blknum] = lsn;
    5666            6 :             }
    5667            6 :         }
    5668            6 : 
    5669            6 :         // Read pages from leaf timeline across all ancestors.
    5670          300 :         for (idx, lsns) in updated.iter().enumerate() {
    5671        30000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    5672            6 :                 // Skip empty mutations.
    5673        30000 :                 if lsn.0 == 0 {
    5674        10968 :                     continue;
    5675        19032 :                 }
    5676        19032 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    5677        19032 :                 test_key.field6 = blknum as u32;
    5678        19032 :                 assert_eq!(
    5679        19032 :                     tline.get(test_key, *lsn, &ctx).await?,
    5680        19032 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    5681            6 :                 );
    5682            6 :             }
    5683            6 :         }
    5684            6 :         Ok(())
    5685            6 :     }
    5686              : 
    5687              :     #[tokio::test]
    5688            6 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    5689            6 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    5690            6 :             .await?
    5691            6 :             .load()
    5692           24 :             .await;
    5693            6 : 
    5694            6 :         let initdb_lsn = Lsn(0x20);
    5695            6 :         let utline = tenant
    5696            6 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    5697            6 :             .await?;
    5698            6 :         let tline = utline.raw_timeline().unwrap();
    5699            6 : 
    5700            6 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    5701            6 :         tline.maybe_spawn_flush_loop();
    5702            6 : 
    5703            6 :         // Make sure the timeline has the minimum set of required keys for operation.
    5704            6 :         // The only operation you can always do on an empty timeline is to `put` new data.
    5705            6 :         // Except if you `put` at `initdb_lsn`.
    5706            6 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    5707            6 :         // It uses `repartition()`, which assumes some keys to be present.
    5708            6 :         // Let's make sure the test timeline can handle that case.
    5709            6 :         {
    5710            6 :             let mut state = tline.flush_loop_state.lock().unwrap();
    5711            6 :             assert_eq!(
    5712            6 :                 timeline::FlushLoopState::Running {
    5713            6 :                     expect_initdb_optimization: false,
    5714            6 :                     initdb_optimization_count: 0,
    5715            6 :                 },
    5716            6 :                 *state
    5717            6 :             );
    5718            6 :             *state = timeline::FlushLoopState::Running {
    5719            6 :                 expect_initdb_optimization: true,
    5720            6 :                 initdb_optimization_count: 0,
    5721            6 :             };
    5722            6 :         }
    5723            6 : 
    5724            6 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    5725            6 :         // As explained above, the optimization requires some keys to be present.
    5726            6 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    5727            6 :         // This is what `create_test_timeline` does, by the way.
    5728            6 :         let mut modification = tline.begin_modification(initdb_lsn);
    5729            6 :         modification
    5730            6 :             .init_empty_test_timeline()
    5731            6 :             .context("init_empty_test_timeline")?;
    5732            6 :         modification
    5733            6 :             .commit(&ctx)
    5734            6 :             .await
    5735            6 :             .context("commit init_empty_test_timeline modification")?;
    5736            6 : 
    5737            6 :         // Do the flush. The flush code will check the expectations that we set above.
    5738            6 :         tline.freeze_and_flush().await?;
    5739            6 : 
    5740            6 :         // assert freeze_and_flush exercised the initdb optimization
    5741            6 :         {
    5742            6 :             let state = tline.flush_loop_state.lock().unwrap();
    5743            6 :             let timeline::FlushLoopState::Running {
    5744            6 :                 expect_initdb_optimization,
    5745            6 :                 initdb_optimization_count,
    5746            6 :             } = *state
    5747            6 :             else {
    5748            6 :                 panic!("unexpected state: {:?}", *state);
    5749            6 :             };
    5750            6 :             assert!(expect_initdb_optimization);
    5751            6 :             assert!(initdb_optimization_count > 0);
    5752            6 :         }
    5753            6 :         Ok(())
    5754            6 :     }
    5755              : 
    5756              :     #[tokio::test]
    5757            6 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    5758            6 :         let name = "test_create_guard_crash";
    5759            6 :         let harness = TenantHarness::create(name).await?;
    5760            6 :         {
    5761           24 :             let (tenant, ctx) = harness.load().await;
    5762            6 :             let tline = tenant
    5763            6 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    5764            6 :                 .await?;
    5765            6 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    5766            6 :             let raw_tline = tline.raw_timeline().unwrap();
    5767            6 :             raw_tline
    5768            6 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    5769            6 :                 .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
    5770            6 :                 .await;
    5771            6 :             std::mem::forget(tline);
    5772            6 :         }
    5773            6 : 
    5774           23 :         let (tenant, _) = harness.load().await;
    5775            6 :         match tenant.get_timeline(TIMELINE_ID, false) {
    5776            6 :             Ok(_) => panic!("timeline should've been removed during load"),
    5777            6 :             Err(e) => {
    5778            6 :                 assert_eq!(
    5779            6 :                     e,
    5780            6 :                     GetTimelineError::NotFound {
    5781            6 :                         tenant_id: tenant.tenant_shard_id,
    5782            6 :                         timeline_id: TIMELINE_ID,
    5783            6 :                     }
    5784            6 :                 )
    5785            6 :             }
    5786            6 :         }
    5787            6 : 
    5788            6 :         assert!(!harness
    5789            6 :             .conf
    5790            6 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    5791            6 :             .exists());
    5792            6 : 
    5793            6 :         Ok(())
    5794            6 :     }
    5795              : 
    5796              :     #[tokio::test]
    5797            6 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    5798            6 :         let names_algorithms = [
    5799            6 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    5800            6 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    5801            6 :         ];
    5802           18 :         for (name, algorithm) in names_algorithms {
    5803        98198 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    5804            6 :         }
    5805            6 :         Ok(())
    5806            6 :     }
    5807              : 
    5808           12 :     async fn test_read_at_max_lsn_algorithm(
    5809           12 :         name: &'static str,
    5810           12 :         compaction_algorithm: CompactionAlgorithm,
    5811           12 :     ) -> anyhow::Result<()> {
    5812           12 :         let mut harness = TenantHarness::create(name).await?;
    5813           12 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    5814           12 :             kind: compaction_algorithm,
    5815           12 :         };
    5816           48 :         let (tenant, ctx) = harness.load().await;
    5817           12 :         let tline = tenant
    5818           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5819           21 :             .await?;
    5820              : 
    5821           12 :         let lsn = Lsn(0x10);
    5822           12 :         let compact = false;
    5823        96899 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    5824              : 
    5825           12 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5826           12 :         let read_lsn = Lsn(u64::MAX - 1);
    5827              : 
    5828         1230 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    5829           12 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    5830              : 
    5831           12 :         Ok(())
    5832           12 :     }
    5833              : 
    5834              :     #[tokio::test]
    5835            6 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    5836            6 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    5837           24 :         let (tenant, ctx) = harness.load().await;
    5838            6 :         let tline = tenant
    5839            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5840           12 :             .await?;
    5841            6 : 
    5842            6 :         const NUM_KEYS: usize = 1000;
    5843            6 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    5844            6 : 
    5845            6 :         let cancel = CancellationToken::new();
    5846            6 : 
    5847            6 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    5848            6 :         base_key.field1 = AUX_KEY_PREFIX;
    5849            6 :         let mut test_key = base_key;
    5850            6 : 
    5851            6 :         // Track when each page was last modified. Used to assert that
    5852            6 :         // a read sees the latest page version.
    5853            6 :         let mut updated = [Lsn(0); NUM_KEYS];
    5854            6 : 
    5855            6 :         let mut lsn = Lsn(0x10);
    5856            6 :         #[allow(clippy::needless_range_loop)]
    5857         6006 :         for blknum in 0..NUM_KEYS {
    5858         6000 :             lsn = Lsn(lsn.0 + 0x10);
    5859         6000 :             test_key.field6 = (blknum * STEP) as u32;
    5860         6000 :             let mut writer = tline.writer().await;
    5861         6000 :             writer
    5862         6000 :                 .put(
    5863         6000 :                     test_key,
    5864         6000 :                     lsn,
    5865         6000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5866         6000 :                     &ctx,
    5867         6000 :                 )
    5868            6 :                 .await?;
    5869         6000 :             writer.finish_write(lsn);
    5870         6000 :             updated[blknum] = lsn;
    5871         6000 :             drop(writer);
    5872            6 :         }
    5873            6 : 
    5874            6 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    5875            6 : 
    5876           72 :         for iter in 0..=10 {
    5877            6 :             // Read all the blocks
    5878        66000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    5879        66000 :                 test_key.field6 = (blknum * STEP) as u32;
    5880        66000 :                 assert_eq!(
    5881        66000 :                     tline.get(test_key, lsn, &ctx).await?,
    5882        66000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    5883            6 :                 );
    5884            6 :             }
    5885            6 : 
    5886           66 :             let mut cnt = 0;
    5887        66000 :             for (key, value) in tline
    5888           66 :                 .get_vectored_impl(
    5889           66 :                     keyspace.clone(),
    5890           66 :                     lsn,
    5891           66 :                     &mut ValuesReconstructState::default(),
    5892           66 :                     &ctx,
    5893           66 :                 )
    5894        12568 :                 .await?
    5895            6 :             {
    5896        66000 :                 let blknum = key.field6 as usize;
    5897        66000 :                 let value = value?;
    5898        66000 :                 assert!(blknum % STEP == 0);
    5899        66000 :                 let blknum = blknum / STEP;
    5900        66000 :                 assert_eq!(
    5901        66000 :                     value,
    5902        66000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    5903        66000 :                 );
    5904        66000 :                 cnt += 1;
    5905            6 :             }
    5906            6 : 
    5907           66 :             assert_eq!(cnt, NUM_KEYS);
    5908            6 : 
    5909        66066 :             for _ in 0..NUM_KEYS {
    5910        66000 :                 lsn = Lsn(lsn.0 + 0x10);
    5911        66000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    5912        66000 :                 test_key.field6 = (blknum * STEP) as u32;
    5913        66000 :                 let mut writer = tline.writer().await;
    5914        66000 :                 writer
    5915        66000 :                     .put(
    5916        66000 :                         test_key,
    5917        66000 :                         lsn,
    5918        66000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5919        66000 :                         &ctx,
    5920        66000 :                     )
    5921          468 :                     .await?;
    5922        66000 :                 writer.finish_write(lsn);
    5923        66000 :                 drop(writer);
    5924        66000 :                 updated[blknum] = lsn;
    5925            6 :             }
    5926            6 : 
    5927            6 :             // Perform two cycles of flush, compact, and GC
    5928          198 :             for round in 0..2 {
    5929          132 :                 tline.freeze_and_flush().await?;
    5930          132 :                 tline
    5931          132 :                     .compact(
    5932          132 :                         &cancel,
    5933          132 :                         if iter % 5 == 0 && round == 0 {
    5934           18 :                             let mut flags = EnumSet::new();
    5935           18 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    5936           18 :                             flags.insert(CompactFlags::ForceRepartition);
    5937           18 :                             flags
    5938            6 :                         } else {
    5939          114 :                             EnumSet::empty()
    5940            6 :                         },
    5941          132 :                         &ctx,
    5942            6 :                     )
    5943        25246 :                     .await?;
    5944          132 :                 tenant
    5945          132 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    5946          108 :                     .await?;
    5947            6 :             }
    5948            6 :         }
    5949            6 : 
    5950            6 :         Ok(())
    5951            6 :     }
    5952              : 
    5953              :     #[tokio::test]
    5954            6 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    5955            6 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    5956           21 :         let (tenant, ctx) = harness.load().await;
    5957            6 :         let tline = tenant
    5958            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5959           12 :             .await?;
    5960            6 : 
    5961            6 :         let cancel = CancellationToken::new();
    5962            6 : 
    5963            6 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    5964            6 :         base_key.field1 = AUX_KEY_PREFIX;
    5965            6 :         let test_key = base_key;
    5966            6 :         let mut lsn = Lsn(0x10);
    5967            6 : 
    5968          126 :         for _ in 0..20 {
    5969          120 :             lsn = Lsn(lsn.0 + 0x10);
    5970          120 :             let mut writer = tline.writer().await;
    5971          120 :             writer
    5972          120 :                 .put(
    5973          120 :                     test_key,
    5974          120 :                     lsn,
    5975          120 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    5976          120 :                     &ctx,
    5977          120 :                 )
    5978           60 :                 .await?;
    5979          120 :             writer.finish_write(lsn);
    5980          120 :             drop(writer);
    5981          126 :             tline.freeze_and_flush().await?; // force create a delta layer
    5982            6 :         }
    5983            6 : 
    5984            6 :         let before_num_l0_delta_files =
    5985            6 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    5986            6 : 
    5987          450 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    5988            6 : 
    5989            6 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    5990            6 : 
    5991            6 :         assert!(after_num_l0_delta_files < before_num_l0_delta_files, "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}");
    5992            6 : 
    5993            6 :         assert_eq!(
    5994           12 :             tline.get(test_key, lsn, &ctx).await?,
    5995            6 :             test_img(&format!("{} at {}", 0, lsn))
    5996            6 :         );
    5997            6 : 
    5998            6 :         Ok(())
    5999            6 :     }
    6000              : 
    6001              :     #[tokio::test]
    6002            6 :     async fn test_branch_copies_dirty_aux_file_flag() {
    6003            6 :         let harness = TenantHarness::create("test_branch_copies_dirty_aux_file_flag")
    6004            6 :             .await
    6005            6 :             .unwrap();
    6006            6 : 
    6007            6 :         // the default aux file policy to switch is v2 if not set by the admins
    6008            6 :         assert_eq!(
    6009            6 :             harness.tenant_conf.switch_aux_file_policy,
    6010            6 :             AuxFilePolicy::default_tenant_config()
    6011            6 :         );
    6012           24 :         let (tenant, ctx) = harness.load().await;
    6013            6 : 
    6014            6 :         let mut lsn = Lsn(0x08);
    6015            6 : 
    6016            6 :         let tline: Arc<Timeline> = tenant
    6017            6 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    6018           12 :             .await
    6019            6 :             .unwrap();
    6020            6 : 
    6021            6 :         // no aux file is written at this point, so the persistent flag should be unset
    6022            6 :         assert_eq!(tline.last_aux_file_policy.load(), None);
    6023            6 : 
    6024            6 :         {
    6025            6 :             lsn += 8;
    6026            6 :             let mut modification = tline.begin_modification(lsn);
    6027            6 :             modification
    6028            6 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    6029            6 :                 .await
    6030            6 :                 .unwrap();
    6031            6 :             modification.commit(&ctx).await.unwrap();
    6032            6 :         }
    6033            6 : 
    6034            6 :         // there is no tenant manager to pass the configuration through, so lets mimic it
    6035            6 :         tenant.set_new_location_config(
    6036            6 :             AttachedTenantConf::try_from(LocationConf::attached_single(
    6037            6 :                 TenantConfOpt {
    6038            6 :                     switch_aux_file_policy: Some(AuxFilePolicy::V2),
    6039            6 :                     ..Default::default()
    6040            6 :                 },
    6041            6 :                 tenant.generation,
    6042            6 :                 &pageserver_api::models::ShardParameters::default(),
    6043            6 :             ))
    6044            6 :             .unwrap(),
    6045            6 :         );
    6046            6 : 
    6047            6 :         assert_eq!(
    6048            6 :             tline.get_switch_aux_file_policy(),
    6049            6 :             AuxFilePolicy::V2,
    6050            6 :             "wanted state has been updated"
    6051            6 :         );
    6052            6 :         assert_eq!(
    6053            6 :             tline.last_aux_file_policy.load(),
    6054            6 :             Some(AuxFilePolicy::V2),
    6055            6 :             "aux file is written with switch_aux_file_policy unset (which is v2), so we should use v2 there"
    6056            6 :         );
    6057            6 : 
    6058            6 :         // we can read everything from the storage
    6059            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6060            6 :         assert_eq!(
    6061            6 :             files.get("pg_logical/mappings/test1"),
    6062            6 :             Some(&bytes::Bytes::from_static(b"first"))
    6063            6 :         );
    6064            6 : 
    6065            6 :         {
    6066            6 :             lsn += 8;
    6067            6 :             let mut modification = tline.begin_modification(lsn);
    6068            6 :             modification
    6069            6 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    6070            6 :                 .await
    6071            6 :                 .unwrap();
    6072            6 :             modification.commit(&ctx).await.unwrap();
    6073            6 :         }
    6074            6 : 
    6075            6 :         assert_eq!(
    6076            6 :             tline.last_aux_file_policy.load(),
    6077            6 :             Some(AuxFilePolicy::V2),
    6078            6 :             "keep v2 storage format when new files are written"
    6079            6 :         );
    6080            6 : 
    6081            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6082            6 :         assert_eq!(
    6083            6 :             files.get("pg_logical/mappings/test2"),
    6084            6 :             Some(&bytes::Bytes::from_static(b"second"))
    6085            6 :         );
    6086            6 : 
    6087            6 :         let child = tenant
    6088            6 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    6089            6 :             .await
    6090            6 :             .unwrap();
    6091            6 : 
    6092            6 :         // child copies the last flag even if that is not on remote storage yet
    6093            6 :         assert_eq!(child.get_switch_aux_file_policy(), AuxFilePolicy::V2);
    6094            6 :         assert_eq!(child.last_aux_file_policy.load(), Some(AuxFilePolicy::V2));
    6095            6 : 
    6096            6 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    6097            6 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    6098            6 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    6099            6 : 
    6100            6 :         // even if we crash here without flushing parent timeline with it's new
    6101            6 :         // last_aux_file_policy we are safe, because child was never meant to access ancestor's
    6102            6 :         // files. the ancestor can even switch back to V1 because of a migration safely.
    6103            6 :     }
    6104              : 
    6105              :     #[tokio::test]
    6106            6 :     async fn aux_file_policy_switch() {
    6107            6 :         let mut harness = TenantHarness::create("aux_file_policy_switch")
    6108            6 :             .await
    6109            6 :             .unwrap();
    6110            6 :         harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::CrossValidation; // set to cross-validation mode
    6111           24 :         let (tenant, ctx) = harness.load().await;
    6112            6 : 
    6113            6 :         let mut lsn = Lsn(0x08);
    6114            6 : 
    6115            6 :         let tline: Arc<Timeline> = tenant
    6116            6 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    6117           12 :             .await
    6118            6 :             .unwrap();
    6119            6 : 
    6120            6 :         assert_eq!(
    6121            6 :             tline.last_aux_file_policy.load(),
    6122            6 :             None,
    6123            6 :             "no aux file is written so it should be unset"
    6124            6 :         );
    6125            6 : 
    6126            6 :         {
    6127            6 :             lsn += 8;
    6128            6 :             let mut modification = tline.begin_modification(lsn);
    6129            6 :             modification
    6130            6 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    6131           15 :                 .await
    6132            6 :                 .unwrap();
    6133            6 :             modification.commit(&ctx).await.unwrap();
    6134            6 :         }
    6135            6 : 
    6136            6 :         // there is no tenant manager to pass the configuration through, so lets mimic it
    6137            6 :         tenant.set_new_location_config(
    6138            6 :             AttachedTenantConf::try_from(LocationConf::attached_single(
    6139            6 :                 TenantConfOpt {
    6140            6 :                     switch_aux_file_policy: Some(AuxFilePolicy::V2),
    6141            6 :                     ..Default::default()
    6142            6 :                 },
    6143            6 :                 tenant.generation,
    6144            6 :                 &pageserver_api::models::ShardParameters::default(),
    6145            6 :             ))
    6146            6 :             .unwrap(),
    6147            6 :         );
    6148            6 : 
    6149            6 :         assert_eq!(
    6150            6 :             tline.get_switch_aux_file_policy(),
    6151            6 :             AuxFilePolicy::V2,
    6152            6 :             "wanted state has been updated"
    6153            6 :         );
    6154            6 :         assert_eq!(
    6155            6 :             tline.last_aux_file_policy.load(),
    6156            6 :             Some(AuxFilePolicy::CrossValidation),
    6157            6 :             "dirty index_part.json reflected state is yet to be updated"
    6158            6 :         );
    6159            6 : 
    6160            6 :         // we can still read the auxfile v1 before we ingest anything new
    6161            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6162            6 :         assert_eq!(
    6163            6 :             files.get("pg_logical/mappings/test1"),
    6164            6 :             Some(&bytes::Bytes::from_static(b"first"))
    6165            6 :         );
    6166            6 : 
    6167            6 :         {
    6168            6 :             lsn += 8;
    6169            6 :             let mut modification = tline.begin_modification(lsn);
    6170            6 :             modification
    6171            6 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    6172            6 :                 .await
    6173            6 :                 .unwrap();
    6174            6 :             modification.commit(&ctx).await.unwrap();
    6175            6 :         }
    6176            6 : 
    6177            6 :         assert_eq!(
    6178            6 :             tline.last_aux_file_policy.load(),
    6179            6 :             Some(AuxFilePolicy::V2),
    6180            6 :             "ingesting a file should apply the wanted switch state when applicable"
    6181            6 :         );
    6182            6 : 
    6183            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6184            6 :         assert_eq!(
    6185            6 :             files.get("pg_logical/mappings/test1"),
    6186            6 :             Some(&bytes::Bytes::from_static(b"first")),
    6187            6 :             "cross validation writes to both v1 and v2 so this should be available in v2"
    6188            6 :         );
    6189            6 :         assert_eq!(
    6190            6 :             files.get("pg_logical/mappings/test2"),
    6191            6 :             Some(&bytes::Bytes::from_static(b"second"))
    6192            6 :         );
    6193            6 : 
    6194            6 :         // mimic again by trying to flip it from V2 to V1 (not switched to while ingesting a file)
    6195            6 :         tenant.set_new_location_config(
    6196            6 :             AttachedTenantConf::try_from(LocationConf::attached_single(
    6197            6 :                 TenantConfOpt {
    6198            6 :                     switch_aux_file_policy: Some(AuxFilePolicy::V1),
    6199            6 :                     ..Default::default()
    6200            6 :                 },
    6201            6 :                 tenant.generation,
    6202            6 :                 &pageserver_api::models::ShardParameters::default(),
    6203            6 :             ))
    6204            6 :             .unwrap(),
    6205            6 :         );
    6206            6 : 
    6207            6 :         {
    6208            6 :             lsn += 8;
    6209            6 :             let mut modification = tline.begin_modification(lsn);
    6210            6 :             modification
    6211            6 :                 .put_file("pg_logical/mappings/test2", b"third", &ctx)
    6212            6 :                 .await
    6213            6 :                 .unwrap();
    6214            6 :             modification.commit(&ctx).await.unwrap();
    6215            6 :         }
    6216            6 : 
    6217            6 :         assert_eq!(
    6218            6 :             tline.get_switch_aux_file_policy(),
    6219            6 :             AuxFilePolicy::V1,
    6220            6 :             "wanted state has been updated again, even if invalid request"
    6221            6 :         );
    6222            6 : 
    6223            6 :         assert_eq!(
    6224            6 :             tline.last_aux_file_policy.load(),
    6225            6 :             Some(AuxFilePolicy::V2),
    6226            6 :             "ingesting a file should apply the wanted switch state when applicable"
    6227            6 :         );
    6228            6 : 
    6229            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6230            6 :         assert_eq!(
    6231            6 :             files.get("pg_logical/mappings/test1"),
    6232            6 :             Some(&bytes::Bytes::from_static(b"first"))
    6233            6 :         );
    6234            6 :         assert_eq!(
    6235            6 :             files.get("pg_logical/mappings/test2"),
    6236            6 :             Some(&bytes::Bytes::from_static(b"third"))
    6237            6 :         );
    6238            6 : 
    6239            6 :         // mimic again by trying to flip it from from V1 to V2 (not switched to while ingesting a file)
    6240            6 :         tenant.set_new_location_config(
    6241            6 :             AttachedTenantConf::try_from(LocationConf::attached_single(
    6242            6 :                 TenantConfOpt {
    6243            6 :                     switch_aux_file_policy: Some(AuxFilePolicy::V2),
    6244            6 :                     ..Default::default()
    6245            6 :                 },
    6246            6 :                 tenant.generation,
    6247            6 :                 &pageserver_api::models::ShardParameters::default(),
    6248            6 :             ))
    6249            6 :             .unwrap(),
    6250            6 :         );
    6251            6 : 
    6252            6 :         {
    6253            6 :             lsn += 8;
    6254            6 :             let mut modification = tline.begin_modification(lsn);
    6255            6 :             modification
    6256            6 :                 .put_file("pg_logical/mappings/test3", b"last", &ctx)
    6257            6 :                 .await
    6258            6 :                 .unwrap();
    6259            6 :             modification.commit(&ctx).await.unwrap();
    6260            6 :         }
    6261            6 : 
    6262            6 :         assert_eq!(tline.get_switch_aux_file_policy(), AuxFilePolicy::V2);
    6263            6 : 
    6264            6 :         assert_eq!(tline.last_aux_file_policy.load(), Some(AuxFilePolicy::V2));
    6265            6 : 
    6266            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6267            6 :         assert_eq!(
    6268            6 :             files.get("pg_logical/mappings/test1"),
    6269            6 :             Some(&bytes::Bytes::from_static(b"first"))
    6270            6 :         );
    6271            6 :         assert_eq!(
    6272            6 :             files.get("pg_logical/mappings/test2"),
    6273            6 :             Some(&bytes::Bytes::from_static(b"third"))
    6274            6 :         );
    6275            6 :         assert_eq!(
    6276            6 :             files.get("pg_logical/mappings/test3"),
    6277            6 :             Some(&bytes::Bytes::from_static(b"last"))
    6278            6 :         );
    6279            6 :     }
    6280              : 
    6281              :     #[tokio::test]
    6282            6 :     async fn aux_file_policy_force_switch() {
    6283            6 :         let mut harness = TenantHarness::create("aux_file_policy_force_switch")
    6284            6 :             .await
    6285            6 :             .unwrap();
    6286            6 :         harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::V1;
    6287           24 :         let (tenant, ctx) = harness.load().await;
    6288            6 : 
    6289            6 :         let mut lsn = Lsn(0x08);
    6290            6 : 
    6291            6 :         let tline: Arc<Timeline> = tenant
    6292            6 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    6293           12 :             .await
    6294            6 :             .unwrap();
    6295            6 : 
    6296            6 :         assert_eq!(
    6297            6 :             tline.last_aux_file_policy.load(),
    6298            6 :             None,
    6299            6 :             "no aux file is written so it should be unset"
    6300            6 :         );
    6301            6 : 
    6302            6 :         {
    6303            6 :             lsn += 8;
    6304            6 :             let mut modification = tline.begin_modification(lsn);
    6305            6 :             modification
    6306            6 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    6307           15 :                 .await
    6308            6 :                 .unwrap();
    6309            6 :             modification.commit(&ctx).await.unwrap();
    6310            6 :         }
    6311            6 : 
    6312            6 :         tline.do_switch_aux_policy(AuxFilePolicy::V2).unwrap();
    6313            6 : 
    6314            6 :         assert_eq!(
    6315            6 :             tline.last_aux_file_policy.load(),
    6316            6 :             Some(AuxFilePolicy::V2),
    6317            6 :             "dirty index_part.json reflected state is yet to be updated"
    6318            6 :         );
    6319            6 : 
    6320            6 :         // lose all data from v1
    6321            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6322            6 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    6323            6 : 
    6324            6 :         {
    6325            6 :             lsn += 8;
    6326            6 :             let mut modification = tline.begin_modification(lsn);
    6327            6 :             modification
    6328            6 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    6329            6 :                 .await
    6330            6 :                 .unwrap();
    6331            6 :             modification.commit(&ctx).await.unwrap();
    6332            6 :         }
    6333            6 : 
    6334            6 :         // read data ingested in v2
    6335            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6336            6 :         assert_eq!(
    6337            6 :             files.get("pg_logical/mappings/test2"),
    6338            6 :             Some(&bytes::Bytes::from_static(b"second"))
    6339            6 :         );
    6340            6 :         // lose all data from v1
    6341            6 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    6342            6 :     }
    6343              : 
    6344              :     #[tokio::test]
    6345            6 :     async fn aux_file_policy_auto_detect() {
    6346            6 :         let mut harness = TenantHarness::create("aux_file_policy_auto_detect")
    6347            6 :             .await
    6348            6 :             .unwrap();
    6349            6 :         harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::V2; // set to cross-validation mode
    6350           24 :         let (tenant, ctx) = harness.load().await;
    6351            6 : 
    6352            6 :         let mut lsn = Lsn(0x08);
    6353            6 : 
    6354            6 :         let tline: Arc<Timeline> = tenant
    6355            6 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    6356           12 :             .await
    6357            6 :             .unwrap();
    6358            6 : 
    6359            6 :         assert_eq!(
    6360            6 :             tline.last_aux_file_policy.load(),
    6361            6 :             None,
    6362            6 :             "no aux file is written so it should be unset"
    6363            6 :         );
    6364            6 : 
    6365            6 :         {
    6366            6 :             lsn += 8;
    6367            6 :             let mut modification = tline.begin_modification(lsn);
    6368            6 :             let buf = AuxFilesDirectory::ser(&AuxFilesDirectory {
    6369            6 :                 files: vec![(
    6370            6 :                     "test_file".to_string(),
    6371            6 :                     Bytes::copy_from_slice(b"test_file"),
    6372            6 :                 )]
    6373            6 :                 .into_iter()
    6374            6 :                 .collect(),
    6375            6 :             })
    6376            6 :             .unwrap();
    6377            6 :             modification.put_for_test(AUX_FILES_KEY, Value::Image(Bytes::from(buf)));
    6378            6 :             modification.commit(&ctx).await.unwrap();
    6379            6 :         }
    6380            6 : 
    6381            6 :         {
    6382            6 :             lsn += 8;
    6383            6 :             let mut modification = tline.begin_modification(lsn);
    6384            6 :             modification
    6385            6 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    6386            6 :                 .await
    6387            6 :                 .unwrap();
    6388            6 :             modification.commit(&ctx).await.unwrap();
    6389            6 :         }
    6390            6 : 
    6391            6 :         assert_eq!(
    6392            6 :             tline.last_aux_file_policy.load(),
    6393            6 :             Some(AuxFilePolicy::V1),
    6394            6 :             "keep using v1 because there are aux files writting with v1"
    6395            6 :         );
    6396            6 : 
    6397            6 :         // we can still read the auxfile v1
    6398            6 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    6399            6 :         assert_eq!(
    6400            6 :             files.get("pg_logical/mappings/test1"),
    6401            6 :             Some(&bytes::Bytes::from_static(b"first"))
    6402            6 :         );
    6403            6 :         assert_eq!(
    6404            6 :             files.get("test_file"),
    6405            6 :             Some(&bytes::Bytes::from_static(b"test_file"))
    6406            6 :         );
    6407            6 :     }
    6408              : 
    6409              :     #[tokio::test]
    6410            6 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    6411            6 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    6412           24 :         let (tenant, ctx) = harness.load().await;
    6413            6 :         let tline = tenant
    6414            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6415           12 :             .await?;
    6416            6 : 
    6417            6 :         const NUM_KEYS: usize = 1000;
    6418            6 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    6419            6 : 
    6420            6 :         let cancel = CancellationToken::new();
    6421            6 : 
    6422            6 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    6423            6 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    6424            6 :         let mut test_key = base_key;
    6425            6 :         let mut lsn = Lsn(0x10);
    6426            6 : 
    6427           24 :         async fn scan_with_statistics(
    6428           24 :             tline: &Timeline,
    6429           24 :             keyspace: &KeySpace,
    6430           24 :             lsn: Lsn,
    6431           24 :             ctx: &RequestContext,
    6432           24 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    6433           24 :             let mut reconstruct_state = ValuesReconstructState::default();
    6434           24 :             let res = tline
    6435           24 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    6436         4023 :                 .await?;
    6437           24 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    6438           24 :         }
    6439            6 : 
    6440            6 :         #[allow(clippy::needless_range_loop)]
    6441         6006 :         for blknum in 0..NUM_KEYS {
    6442         6000 :             lsn = Lsn(lsn.0 + 0x10);
    6443         6000 :             test_key.field6 = (blknum * STEP) as u32;
    6444         6000 :             let mut writer = tline.writer().await;
    6445         6000 :             writer
    6446         6000 :                 .put(
    6447         6000 :                     test_key,
    6448         6000 :                     lsn,
    6449         6000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6450         6000 :                     &ctx,
    6451         6000 :                 )
    6452            6 :                 .await?;
    6453         6000 :             writer.finish_write(lsn);
    6454         6000 :             drop(writer);
    6455            6 :         }
    6456            6 : 
    6457            6 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    6458            6 : 
    6459           66 :         for iter in 1..=10 {
    6460        60060 :             for _ in 0..NUM_KEYS {
    6461        60000 :                 lsn = Lsn(lsn.0 + 0x10);
    6462        60000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6463        60000 :                 test_key.field6 = (blknum * STEP) as u32;
    6464        60000 :                 let mut writer = tline.writer().await;
    6465        60000 :                 writer
    6466        60000 :                     .put(
    6467        60000 :                         test_key,
    6468        60000 :                         lsn,
    6469        60000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6470        60000 :                         &ctx,
    6471        60000 :                     )
    6472          103 :                     .await?;
    6473        60000 :                 writer.finish_write(lsn);
    6474        60000 :                 drop(writer);
    6475            6 :             }
    6476            6 : 
    6477           60 :             tline.freeze_and_flush().await?;
    6478            6 : 
    6479           60 :             if iter % 5 == 0 {
    6480           12 :                 let (_, before_delta_file_accessed) =
    6481         3997 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    6482           12 :                 tline
    6483           12 :                     .compact(
    6484           12 :                         &cancel,
    6485           12 :                         {
    6486           12 :                             let mut flags = EnumSet::new();
    6487           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    6488           12 :                             flags.insert(CompactFlags::ForceRepartition);
    6489           12 :                             flags
    6490           12 :                         },
    6491           12 :                         &ctx,
    6492           12 :                     )
    6493        18565 :                     .await?;
    6494           12 :                 let (_, after_delta_file_accessed) =
    6495           26 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    6496           12 :                 assert!(after_delta_file_accessed < before_delta_file_accessed, "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}");
    6497            6 :                 // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
    6498           12 :                 assert!(
    6499           12 :                     after_delta_file_accessed <= 2,
    6500            6 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    6501            6 :                 );
    6502           48 :             }
    6503            6 :         }
    6504            6 : 
    6505            6 :         Ok(())
    6506            6 :     }
    6507              : 
    6508              :     #[tokio::test]
    6509            6 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    6510            6 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    6511           24 :         let (tenant, ctx) = harness.load().await;
    6512            6 : 
    6513            6 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    6514            6 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    6515            6 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    6516            6 : 
    6517            6 :         let tline = tenant
    6518            6 :             .create_test_timeline_with_layers(
    6519            6 :                 TIMELINE_ID,
    6520            6 :                 Lsn(0x10),
    6521            6 :                 DEFAULT_PG_VERSION,
    6522            6 :                 &ctx,
    6523            6 :                 Vec::new(), // delta layers
    6524            6 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    6525            6 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    6526            6 :             )
    6527           33 :             .await?;
    6528            6 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    6529            6 : 
    6530            6 :         let child = tenant
    6531            6 :             .branch_timeline_test_with_layers(
    6532            6 :                 &tline,
    6533            6 :                 NEW_TIMELINE_ID,
    6534            6 :                 Some(Lsn(0x20)),
    6535            6 :                 &ctx,
    6536            6 :                 Vec::new(), // delta layers
    6537            6 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    6538            6 :                 Lsn(0x30),
    6539            6 :             )
    6540           21 :             .await
    6541            6 :             .unwrap();
    6542            6 : 
    6543            6 :         let lsn = Lsn(0x30);
    6544            6 : 
    6545            6 :         // test vectored get on parent timeline
    6546            6 :         assert_eq!(
    6547           12 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    6548            6 :             Some(test_img("data key 1"))
    6549            6 :         );
    6550            6 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    6551            9 :             .await
    6552            6 :             .unwrap_err()
    6553            6 :             .is_missing_key_error());
    6554            6 :         assert!(
    6555            6 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    6556            6 :                 .await
    6557            6 :                 .unwrap_err()
    6558            6 :                 .is_missing_key_error()
    6559            6 :         );
    6560            6 : 
    6561            6 :         // test vectored get on child timeline
    6562            6 :         assert_eq!(
    6563            6 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    6564            6 :             Some(test_img("data key 1"))
    6565            6 :         );
    6566            6 :         assert_eq!(
    6567           12 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    6568            6 :             Some(test_img("data key 2"))
    6569            6 :         );
    6570            6 :         assert!(
    6571            6 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    6572            6 :                 .await
    6573            6 :                 .unwrap_err()
    6574            6 :                 .is_missing_key_error()
    6575            6 :         );
    6576            6 : 
    6577            6 :         Ok(())
    6578            6 :     }
    6579              : 
    6580              :     #[tokio::test]
    6581            6 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    6582            6 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    6583           24 :         let (tenant, ctx) = harness.load().await;
    6584            6 : 
    6585            6 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    6586            6 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    6587            6 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    6588            6 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    6589            6 : 
    6590            6 :         let tline = tenant
    6591            6 :             .create_test_timeline_with_layers(
    6592            6 :                 TIMELINE_ID,
    6593            6 :                 Lsn(0x10),
    6594            6 :                 DEFAULT_PG_VERSION,
    6595            6 :                 &ctx,
    6596            6 :                 Vec::new(), // delta layers
    6597            6 :                 vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
    6598            6 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    6599            6 :             )
    6600           33 :             .await?;
    6601            6 : 
    6602            6 :         let child = tenant
    6603            6 :             .branch_timeline_test_with_layers(
    6604            6 :                 &tline,
    6605            6 :                 NEW_TIMELINE_ID,
    6606            6 :                 Some(Lsn(0x20)),
    6607            6 :                 &ctx,
    6608            6 :                 Vec::new(), // delta layers
    6609            6 :                 vec![(
    6610            6 :                     Lsn(0x30),
    6611            6 :                     vec![(base_key_child, test_img("metadata key 2"))],
    6612            6 :                 )], // image layers
    6613            6 :                 Lsn(0x30),
    6614            6 :             )
    6615           21 :             .await
    6616            6 :             .unwrap();
    6617            6 : 
    6618            6 :         let lsn = Lsn(0x30);
    6619            6 : 
    6620            6 :         // test vectored get on parent timeline
    6621            6 :         assert_eq!(
    6622           12 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    6623            6 :             Some(test_img("metadata key 1"))
    6624            6 :         );
    6625            6 :         assert_eq!(
    6626            6 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    6627            6 :             None
    6628            6 :         );
    6629            6 :         assert_eq!(
    6630            6 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    6631            6 :             None
    6632            6 :         );
    6633            6 : 
    6634            6 :         // test vectored get on child timeline
    6635            6 :         assert_eq!(
    6636            6 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    6637            6 :             None
    6638            6 :         );
    6639            6 :         assert_eq!(
    6640           12 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    6641            6 :             Some(test_img("metadata key 2"))
    6642            6 :         );
    6643            6 :         assert_eq!(
    6644            6 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    6645            6 :             None
    6646            6 :         );
    6647            6 : 
    6648            6 :         Ok(())
    6649            6 :     }
    6650              : 
    6651          108 :     async fn get_vectored_impl_wrapper(
    6652          108 :         tline: &Arc<Timeline>,
    6653          108 :         key: Key,
    6654          108 :         lsn: Lsn,
    6655          108 :         ctx: &RequestContext,
    6656          108 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    6657          108 :         let mut reconstruct_state = ValuesReconstructState::new();
    6658          108 :         let mut res = tline
    6659          108 :             .get_vectored_impl(
    6660          108 :                 KeySpace::single(key..key.next()),
    6661          108 :                 lsn,
    6662          108 :                 &mut reconstruct_state,
    6663          108 :                 ctx,
    6664          108 :             )
    6665           99 :             .await?;
    6666           90 :         Ok(res.pop_last().map(|(k, v)| {
    6667           54 :             assert_eq!(k, key);
    6668           54 :             v.unwrap()
    6669           90 :         }))
    6670          108 :     }
    6671              : 
    6672              :     #[tokio::test]
    6673            6 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    6674            6 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    6675           24 :         let (tenant, ctx) = harness.load().await;
    6676            6 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    6677            6 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    6678            6 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    6679            6 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    6680            6 : 
    6681            6 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    6682            6 :         // Lsn 0x30 key0, key3, no key1+key2
    6683            6 :         // Lsn 0x20 key1+key2 tomestones
    6684            6 :         // Lsn 0x10 key1 in image, key2 in delta
    6685            6 :         let tline = tenant
    6686            6 :             .create_test_timeline_with_layers(
    6687            6 :                 TIMELINE_ID,
    6688            6 :                 Lsn(0x10),
    6689            6 :                 DEFAULT_PG_VERSION,
    6690            6 :                 &ctx,
    6691            6 :                 // delta layers
    6692            6 :                 vec![
    6693            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6694            6 :                         Lsn(0x10)..Lsn(0x20),
    6695            6 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    6696            6 :                     ),
    6697            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6698            6 :                         Lsn(0x20)..Lsn(0x30),
    6699            6 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    6700            6 :                     ),
    6701            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6702            6 :                         Lsn(0x20)..Lsn(0x30),
    6703            6 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    6704            6 :                     ),
    6705            6 :                 ],
    6706            6 :                 // image layers
    6707            6 :                 vec![
    6708            6 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    6709            6 :                     (
    6710            6 :                         Lsn(0x30),
    6711            6 :                         vec![
    6712            6 :                             (key0, test_img("metadata key 0")),
    6713            6 :                             (key3, test_img("metadata key 3")),
    6714            6 :                         ],
    6715            6 :                     ),
    6716            6 :                 ],
    6717            6 :                 Lsn(0x30),
    6718            6 :             )
    6719          114 :             .await?;
    6720            6 : 
    6721            6 :         let lsn = Lsn(0x30);
    6722            6 :         let old_lsn = Lsn(0x20);
    6723            6 : 
    6724            6 :         assert_eq!(
    6725           12 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    6726            6 :             Some(test_img("metadata key 0"))
    6727            6 :         );
    6728            6 :         assert_eq!(
    6729            6 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    6730            6 :             None,
    6731            6 :         );
    6732            6 :         assert_eq!(
    6733            6 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    6734            6 :             None,
    6735            6 :         );
    6736            6 :         assert_eq!(
    6737           12 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    6738            6 :             Some(Bytes::new()),
    6739            6 :         );
    6740            6 :         assert_eq!(
    6741           12 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    6742            6 :             Some(Bytes::new()),
    6743            6 :         );
    6744            6 :         assert_eq!(
    6745            6 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    6746            6 :             Some(test_img("metadata key 3"))
    6747            6 :         );
    6748            6 : 
    6749            6 :         Ok(())
    6750            6 :     }
    6751              : 
    6752              :     #[tokio::test]
    6753            6 :     async fn test_metadata_tombstone_image_creation() {
    6754            6 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    6755            6 :             .await
    6756            6 :             .unwrap();
    6757           24 :         let (tenant, ctx) = harness.load().await;
    6758            6 : 
    6759            6 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    6760            6 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    6761            6 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    6762            6 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    6763            6 : 
    6764            6 :         let tline = tenant
    6765            6 :             .create_test_timeline_with_layers(
    6766            6 :                 TIMELINE_ID,
    6767            6 :                 Lsn(0x10),
    6768            6 :                 DEFAULT_PG_VERSION,
    6769            6 :                 &ctx,
    6770            6 :                 // delta layers
    6771            6 :                 vec![
    6772            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6773            6 :                         Lsn(0x10)..Lsn(0x20),
    6774            6 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    6775            6 :                     ),
    6776            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6777            6 :                         Lsn(0x20)..Lsn(0x30),
    6778            6 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    6779            6 :                     ),
    6780            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6781            6 :                         Lsn(0x20)..Lsn(0x30),
    6782            6 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    6783            6 :                     ),
    6784            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6785            6 :                         Lsn(0x30)..Lsn(0x40),
    6786            6 :                         vec![
    6787            6 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    6788            6 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    6789            6 :                         ],
    6790            6 :                     ),
    6791            6 :                 ],
    6792            6 :                 // image layers
    6793            6 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    6794            6 :                 Lsn(0x40),
    6795            6 :             )
    6796          105 :             .await
    6797            6 :             .unwrap();
    6798            6 : 
    6799            6 :         let cancel = CancellationToken::new();
    6800            6 : 
    6801            6 :         tline
    6802            6 :             .compact(
    6803            6 :                 &cancel,
    6804            6 :                 {
    6805            6 :                     let mut flags = EnumSet::new();
    6806            6 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    6807            6 :                     flags.insert(CompactFlags::ForceRepartition);
    6808            6 :                     flags
    6809            6 :                 },
    6810            6 :                 &ctx,
    6811            6 :             )
    6812          165 :             .await
    6813            6 :             .unwrap();
    6814            6 : 
    6815            6 :         // Image layers are created at last_record_lsn
    6816            6 :         let images = tline
    6817            6 :             .inspect_image_layers(Lsn(0x40), &ctx)
    6818           24 :             .await
    6819            6 :             .unwrap()
    6820            6 :             .into_iter()
    6821           54 :             .filter(|(k, _)| k.is_metadata_key())
    6822            6 :             .collect::<Vec<_>>();
    6823            6 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    6824            6 :     }
    6825              : 
    6826              :     #[tokio::test]
    6827            6 :     async fn test_metadata_tombstone_empty_image_creation() {
    6828            6 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    6829            6 :             .await
    6830            6 :             .unwrap();
    6831           24 :         let (tenant, ctx) = harness.load().await;
    6832            6 : 
    6833            6 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    6834            6 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    6835            6 : 
    6836            6 :         let tline = tenant
    6837            6 :             .create_test_timeline_with_layers(
    6838            6 :                 TIMELINE_ID,
    6839            6 :                 Lsn(0x10),
    6840            6 :                 DEFAULT_PG_VERSION,
    6841            6 :                 &ctx,
    6842            6 :                 // delta layers
    6843            6 :                 vec![
    6844            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6845            6 :                         Lsn(0x10)..Lsn(0x20),
    6846            6 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    6847            6 :                     ),
    6848            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6849            6 :                         Lsn(0x20)..Lsn(0x30),
    6850            6 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    6851            6 :                     ),
    6852            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    6853            6 :                         Lsn(0x20)..Lsn(0x30),
    6854            6 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    6855            6 :                     ),
    6856            6 :                 ],
    6857            6 :                 // image layers
    6858            6 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    6859            6 :                 Lsn(0x30),
    6860            6 :             )
    6861           87 :             .await
    6862            6 :             .unwrap();
    6863            6 : 
    6864            6 :         let cancel = CancellationToken::new();
    6865            6 : 
    6866            6 :         tline
    6867            6 :             .compact(
    6868            6 :                 &cancel,
    6869            6 :                 {
    6870            6 :                     let mut flags = EnumSet::new();
    6871            6 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    6872            6 :                     flags.insert(CompactFlags::ForceRepartition);
    6873            6 :                     flags
    6874            6 :                 },
    6875            6 :                 &ctx,
    6876            6 :             )
    6877          129 :             .await
    6878            6 :             .unwrap();
    6879            6 : 
    6880            6 :         // Image layers are created at last_record_lsn
    6881            6 :         let images = tline
    6882            6 :             .inspect_image_layers(Lsn(0x30), &ctx)
    6883           12 :             .await
    6884            6 :             .unwrap()
    6885            6 :             .into_iter()
    6886           42 :             .filter(|(k, _)| k.is_metadata_key())
    6887            6 :             .collect::<Vec<_>>();
    6888            6 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    6889            6 :     }
    6890              : 
    6891              :     #[tokio::test]
    6892            6 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    6893            6 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    6894           24 :         let (tenant, ctx) = harness.load().await;
    6895            6 : 
    6896          294 :         fn get_key(id: u32) -> Key {
    6897          294 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    6898          294 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    6899          294 :             key.field6 = id;
    6900          294 :             key
    6901          294 :         }
    6902            6 : 
    6903            6 :         // We create
    6904            6 :         // - one bottom-most image layer,
    6905            6 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    6906            6 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    6907            6 :         // - a delta layer D3 above the horizon.
    6908            6 :         //
    6909            6 :         //                             | D3 |
    6910            6 :         //  | D1 |
    6911            6 :         // -|    |-- gc horizon -----------------
    6912            6 :         //  |    |                | D2 |
    6913            6 :         // --------- img layer ------------------
    6914            6 :         //
    6915            6 :         // What we should expact from this compaction is:
    6916            6 :         //                             | D3 |
    6917            6 :         //  | Part of D1 |
    6918            6 :         // --------- img layer with D1+D2 at GC horizon------------------
    6919            6 : 
    6920            6 :         // img layer at 0x10
    6921            6 :         let img_layer = (0..10)
    6922           60 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    6923            6 :             .collect_vec();
    6924            6 : 
    6925            6 :         let delta1 = vec![
    6926            6 :             (
    6927            6 :                 get_key(1),
    6928            6 :                 Lsn(0x20),
    6929            6 :                 Value::Image(Bytes::from("value 1@0x20")),
    6930            6 :             ),
    6931            6 :             (
    6932            6 :                 get_key(2),
    6933            6 :                 Lsn(0x30),
    6934            6 :                 Value::Image(Bytes::from("value 2@0x30")),
    6935            6 :             ),
    6936            6 :             (
    6937            6 :                 get_key(3),
    6938            6 :                 Lsn(0x40),
    6939            6 :                 Value::Image(Bytes::from("value 3@0x40")),
    6940            6 :             ),
    6941            6 :         ];
    6942            6 :         let delta2 = vec![
    6943            6 :             (
    6944            6 :                 get_key(5),
    6945            6 :                 Lsn(0x20),
    6946            6 :                 Value::Image(Bytes::from("value 5@0x20")),
    6947            6 :             ),
    6948            6 :             (
    6949            6 :                 get_key(6),
    6950            6 :                 Lsn(0x20),
    6951            6 :                 Value::Image(Bytes::from("value 6@0x20")),
    6952            6 :             ),
    6953            6 :         ];
    6954            6 :         let delta3 = vec![
    6955            6 :             (
    6956            6 :                 get_key(8),
    6957            6 :                 Lsn(0x48),
    6958            6 :                 Value::Image(Bytes::from("value 8@0x48")),
    6959            6 :             ),
    6960            6 :             (
    6961            6 :                 get_key(9),
    6962            6 :                 Lsn(0x48),
    6963            6 :                 Value::Image(Bytes::from("value 9@0x48")),
    6964            6 :             ),
    6965            6 :         ];
    6966            6 : 
    6967            6 :         let tline = tenant
    6968            6 :             .create_test_timeline_with_layers(
    6969            6 :                 TIMELINE_ID,
    6970            6 :                 Lsn(0x10),
    6971            6 :                 DEFAULT_PG_VERSION,
    6972            6 :                 &ctx,
    6973            6 :                 vec![
    6974            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    6975            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    6976            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    6977            6 :                 ], // delta layers
    6978            6 :                 vec![(Lsn(0x10), img_layer)], // image layers
    6979            6 :                 Lsn(0x50),
    6980            6 :             )
    6981          141 :             .await?;
    6982            6 :         {
    6983            6 :             // Update GC info
    6984            6 :             let mut guard = tline.gc_info.write().unwrap();
    6985            6 :             guard.cutoffs.time = Lsn(0x30);
    6986            6 :             guard.cutoffs.space = Lsn(0x30);
    6987            6 :         }
    6988            6 : 
    6989            6 :         let expected_result = [
    6990            6 :             Bytes::from_static(b"value 0@0x10"),
    6991            6 :             Bytes::from_static(b"value 1@0x20"),
    6992            6 :             Bytes::from_static(b"value 2@0x30"),
    6993            6 :             Bytes::from_static(b"value 3@0x40"),
    6994            6 :             Bytes::from_static(b"value 4@0x10"),
    6995            6 :             Bytes::from_static(b"value 5@0x20"),
    6996            6 :             Bytes::from_static(b"value 6@0x20"),
    6997            6 :             Bytes::from_static(b"value 7@0x10"),
    6998            6 :             Bytes::from_static(b"value 8@0x48"),
    6999            6 :             Bytes::from_static(b"value 9@0x48"),
    7000            6 :         ];
    7001            6 : 
    7002           60 :         for (idx, expected) in expected_result.iter().enumerate() {
    7003           60 :             assert_eq!(
    7004           60 :                 tline
    7005           60 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7006           69 :                     .await
    7007           60 :                     .unwrap(),
    7008            6 :                 expected
    7009            6 :             );
    7010            6 :         }
    7011            6 : 
    7012            6 :         let cancel = CancellationToken::new();
    7013            6 :         tline
    7014            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7015          159 :             .await
    7016            6 :             .unwrap();
    7017            6 : 
    7018           60 :         for (idx, expected) in expected_result.iter().enumerate() {
    7019           60 :             assert_eq!(
    7020           60 :                 tline
    7021           60 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7022           48 :                     .await
    7023           60 :                     .unwrap(),
    7024            6 :                 expected
    7025            6 :             );
    7026            6 :         }
    7027            6 : 
    7028            6 :         // Check if the image layer at the GC horizon contains exactly what we want
    7029            6 :         let image_at_gc_horizon = tline
    7030            6 :             .inspect_image_layers(Lsn(0x30), &ctx)
    7031            6 :             .await
    7032            6 :             .unwrap()
    7033            6 :             .into_iter()
    7034          102 :             .filter(|(k, _)| k.is_metadata_key())
    7035            6 :             .collect::<Vec<_>>();
    7036            6 : 
    7037            6 :         assert_eq!(image_at_gc_horizon.len(), 10);
    7038            6 :         let expected_result = [
    7039            6 :             Bytes::from_static(b"value 0@0x10"),
    7040            6 :             Bytes::from_static(b"value 1@0x20"),
    7041            6 :             Bytes::from_static(b"value 2@0x30"),
    7042            6 :             Bytes::from_static(b"value 3@0x10"),
    7043            6 :             Bytes::from_static(b"value 4@0x10"),
    7044            6 :             Bytes::from_static(b"value 5@0x20"),
    7045            6 :             Bytes::from_static(b"value 6@0x20"),
    7046            6 :             Bytes::from_static(b"value 7@0x10"),
    7047            6 :             Bytes::from_static(b"value 8@0x10"),
    7048            6 :             Bytes::from_static(b"value 9@0x10"),
    7049            6 :         ];
    7050           66 :         for idx in 0..10 {
    7051           60 :             assert_eq!(
    7052           60 :                 image_at_gc_horizon[idx],
    7053           60 :                 (get_key(idx as u32), expected_result[idx].clone())
    7054           60 :             );
    7055            6 :         }
    7056            6 : 
    7057            6 :         // Check if old layers are removed / new layers have the expected LSN
    7058            6 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
    7059           12 :         all_layers.sort_by(|k1, k2| {
    7060           12 :             (
    7061           12 :                 k1.is_delta,
    7062           12 :                 k1.key_range.start,
    7063           12 :                 k1.key_range.end,
    7064           12 :                 k1.lsn_range.start,
    7065           12 :                 k1.lsn_range.end,
    7066           12 :             )
    7067           12 :                 .cmp(&(
    7068           12 :                     k2.is_delta,
    7069           12 :                     k2.key_range.start,
    7070           12 :                     k2.key_range.end,
    7071           12 :                     k2.lsn_range.start,
    7072           12 :                     k2.lsn_range.end,
    7073           12 :                 ))
    7074           12 :         });
    7075            6 :         assert_eq!(
    7076            6 :             all_layers,
    7077            6 :             vec![
    7078            6 :                 // Image layer at GC horizon
    7079            6 :                 PersistentLayerKey {
    7080            6 :                     key_range: Key::MIN..Key::NON_L0_MAX,
    7081            6 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    7082            6 :                     is_delta: false
    7083            6 :                 },
    7084            6 :                 // The delta layer covers the full range (with the layer key hack to avoid being recognized as L0)
    7085            6 :                 PersistentLayerKey {
    7086            6 :                     key_range: Key::MIN..Key::NON_L0_MAX,
    7087            6 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    7088            6 :                     is_delta: true
    7089            6 :                 },
    7090            6 :                 // The delta3 layer that should not be picked for the compaction
    7091            6 :                 PersistentLayerKey {
    7092            6 :                     key_range: get_key(8)..get_key(10),
    7093            6 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    7094            6 :                     is_delta: true
    7095            6 :                 }
    7096            6 :             ]
    7097            6 :         );
    7098            6 : 
    7099            6 :         // increase GC horizon and compact again
    7100            6 :         {
    7101            6 :             // Update GC info
    7102            6 :             let mut guard = tline.gc_info.write().unwrap();
    7103            6 :             guard.cutoffs.time = Lsn(0x40);
    7104            6 :             guard.cutoffs.space = Lsn(0x40);
    7105            6 :         }
    7106            6 :         tline
    7107            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7108          129 :             .await
    7109            6 :             .unwrap();
    7110            6 : 
    7111            6 :         Ok(())
    7112            6 :     }
    7113              : 
    7114              :     #[tokio::test]
    7115            6 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    7116            6 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    7117           24 :         let (tenant, ctx) = harness.load().await;
    7118            6 : 
    7119           72 :         fn get_key(id: u32) -> Key {
    7120           72 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7121           72 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7122           72 :             key.field6 = id;
    7123           72 :             key
    7124           72 :         }
    7125            6 : 
    7126            6 :         let delta1 = vec![
    7127            6 :             (
    7128            6 :                 get_key(1),
    7129            6 :                 Lsn(0x20),
    7130            6 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    7131            6 :             ),
    7132            6 :             (
    7133            6 :                 get_key(1),
    7134            6 :                 Lsn(0x30),
    7135            6 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    7136            6 :             ),
    7137            6 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    7138            6 :             (
    7139            6 :                 get_key(2),
    7140            6 :                 Lsn(0x20),
    7141            6 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    7142            6 :             ),
    7143            6 :             (
    7144            6 :                 get_key(2),
    7145            6 :                 Lsn(0x30),
    7146            6 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    7147            6 :             ),
    7148            6 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    7149            6 :             (
    7150            6 :                 get_key(3),
    7151            6 :                 Lsn(0x20),
    7152            6 :                 Value::WalRecord(NeonWalRecord::wal_clear()),
    7153            6 :             ),
    7154            6 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    7155            6 :             (
    7156            6 :                 get_key(4),
    7157            6 :                 Lsn(0x20),
    7158            6 :                 Value::WalRecord(NeonWalRecord::wal_init()),
    7159            6 :             ),
    7160            6 :         ];
    7161            6 :         let image1 = vec![(get_key(1), "0x10".into())];
    7162            6 : 
    7163            6 :         let tline = tenant
    7164            6 :             .create_test_timeline_with_layers(
    7165            6 :                 TIMELINE_ID,
    7166            6 :                 Lsn(0x10),
    7167            6 :                 DEFAULT_PG_VERSION,
    7168            6 :                 &ctx,
    7169            6 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    7170            6 :                     Lsn(0x10)..Lsn(0x40),
    7171            6 :                     delta1,
    7172            6 :                 )], // delta layers
    7173            6 :                 vec![(Lsn(0x10), image1)], // image layers
    7174            6 :                 Lsn(0x50),
    7175            6 :             )
    7176           51 :             .await?;
    7177            6 : 
    7178            6 :         assert_eq!(
    7179           24 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    7180            6 :             Bytes::from_static(b"0x10,0x20,0x30")
    7181            6 :         );
    7182            6 :         assert_eq!(
    7183            6 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    7184            6 :             Bytes::from_static(b"0x10,0x20,0x30")
    7185            6 :         );
    7186            6 : 
    7187            6 :         // Need to remove the limit of "Neon WAL redo requires base image".
    7188            6 : 
    7189            6 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    7190            6 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    7191            6 : 
    7192            6 :         Ok(())
    7193            6 :     }
    7194              : 
    7195              :     #[tokio::test]
    7196            6 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    7197           24 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease").await?.load().await;
    7198            6 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7199            6 : 
    7200            6 :         let end_lsn = Lsn(0x100);
    7201            6 :         let image_layers = (0x20..=0x90)
    7202            6 :             .step_by(0x10)
    7203           48 :             .map(|n| {
    7204           48 :                 (
    7205           48 :                     Lsn(n),
    7206           48 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    7207           48 :                 )
    7208           48 :             })
    7209            6 :             .collect();
    7210            6 : 
    7211            6 :         let timeline = tenant
    7212            6 :             .create_test_timeline_with_layers(
    7213            6 :                 TIMELINE_ID,
    7214            6 :                 Lsn(0x10),
    7215            6 :                 DEFAULT_PG_VERSION,
    7216            6 :                 &ctx,
    7217            6 :                 Vec::new(),
    7218            6 :                 image_layers,
    7219            6 :                 end_lsn,
    7220            6 :             )
    7221          180 :             .await?;
    7222            6 : 
    7223            6 :         let leased_lsns = [0x30, 0x50, 0x70];
    7224            6 :         let mut leases = Vec::new();
    7225           18 :         let _: anyhow::Result<_> = leased_lsns.iter().try_for_each(|n| {
    7226           18 :             leases.push(timeline.make_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)?);
    7227           18 :             Ok(())
    7228           18 :         });
    7229            6 : 
    7230            6 :         // Renewing with shorter lease should not change the lease.
    7231            6 :         let updated_lease_0 =
    7232            6 :             timeline.make_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)?;
    7233            6 :         assert_eq!(updated_lease_0.valid_until, leases[0].valid_until);
    7234            6 : 
    7235            6 :         // Renewing with a long lease should renew lease with later expiration time.
    7236            6 :         let updated_lease_1 = timeline.make_lsn_lease(
    7237            6 :             Lsn(leased_lsns[1]),
    7238            6 :             timeline.get_lsn_lease_length() * 2,
    7239            6 :             &ctx,
    7240            6 :         )?;
    7241            6 : 
    7242            6 :         assert!(updated_lease_1.valid_until > leases[1].valid_until);
    7243            6 : 
    7244            6 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    7245            6 :         info!(
    7246            6 :             "latest_gc_cutoff_lsn: {}",
    7247            0 :             *timeline.get_latest_gc_cutoff_lsn()
    7248            6 :         );
    7249            6 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    7250            6 : 
    7251            6 :         let res = tenant
    7252            6 :             .gc_iteration(
    7253            6 :                 Some(TIMELINE_ID),
    7254            6 :                 0,
    7255            6 :                 Duration::ZERO,
    7256            6 :                 &CancellationToken::new(),
    7257            6 :                 &ctx,
    7258            6 :             )
    7259            6 :             .await?;
    7260            6 : 
    7261            6 :         // Keeping everything <= Lsn(0x80) b/c leases:
    7262            6 :         // 0/10: initdb layer
    7263            6 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    7264            6 :         assert_eq!(res.layers_needed_by_leases, 7);
    7265            6 :         // Keeping 0/90 b/c it is the latest layer.
    7266            6 :         assert_eq!(res.layers_not_updated, 1);
    7267            6 :         // Removed 0/80.
    7268            6 :         assert_eq!(res.layers_removed, 1);
    7269            6 : 
    7270            6 :         // Make lease on a already GC-ed LSN.
    7271            6 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    7272            6 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    7273            6 :         let res = timeline.make_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx);
    7274            6 :         assert!(res.is_err());
    7275            6 : 
    7276            6 :         // Should still be able to renew a currently valid lease
    7277            6 :         // Assumption: original lease to is still valid for 0/50.
    7278            6 :         let _ =
    7279            6 :             timeline.make_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)?;
    7280            6 : 
    7281            6 :         Ok(())
    7282            6 :     }
    7283              : 
    7284              :     #[tokio::test]
    7285            6 :     async fn test_simple_bottom_most_compaction_deltas() -> anyhow::Result<()> {
    7286            6 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_deltas").await?;
    7287           23 :         let (tenant, ctx) = harness.load().await;
    7288            6 : 
    7289          354 :         fn get_key(id: u32) -> Key {
    7290          354 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7291          354 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7292          354 :             key.field6 = id;
    7293          354 :             key
    7294          354 :         }
    7295            6 : 
    7296            6 :         // We create
    7297            6 :         // - one bottom-most image layer,
    7298            6 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    7299            6 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    7300            6 :         // - a delta layer D3 above the horizon.
    7301            6 :         //
    7302            6 :         //                             | D3 |
    7303            6 :         //  | D1 |
    7304            6 :         // -|    |-- gc horizon -----------------
    7305            6 :         //  |    |                | D2 |
    7306            6 :         // --------- img layer ------------------
    7307            6 :         //
    7308            6 :         // What we should expact from this compaction is:
    7309            6 :         //                             | D3 |
    7310            6 :         //  | Part of D1 |
    7311            6 :         // --------- img layer with D1+D2 at GC horizon------------------
    7312            6 : 
    7313            6 :         // img layer at 0x10
    7314            6 :         let img_layer = (0..10)
    7315           60 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    7316            6 :             .collect_vec();
    7317            6 : 
    7318            6 :         let delta1 = vec![
    7319            6 :             (
    7320            6 :                 get_key(1),
    7321            6 :                 Lsn(0x20),
    7322            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7323            6 :             ),
    7324            6 :             (
    7325            6 :                 get_key(2),
    7326            6 :                 Lsn(0x30),
    7327            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    7328            6 :             ),
    7329            6 :             (
    7330            6 :                 get_key(3),
    7331            6 :                 Lsn(0x28),
    7332            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    7333            6 :             ),
    7334            6 :             (
    7335            6 :                 get_key(3),
    7336            6 :                 Lsn(0x30),
    7337            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    7338            6 :             ),
    7339            6 :             (
    7340            6 :                 get_key(3),
    7341            6 :                 Lsn(0x40),
    7342            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    7343            6 :             ),
    7344            6 :         ];
    7345            6 :         let delta2 = vec![
    7346            6 :             (
    7347            6 :                 get_key(5),
    7348            6 :                 Lsn(0x20),
    7349            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7350            6 :             ),
    7351            6 :             (
    7352            6 :                 get_key(6),
    7353            6 :                 Lsn(0x20),
    7354            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7355            6 :             ),
    7356            6 :         ];
    7357            6 :         let delta3 = vec![
    7358            6 :             (
    7359            6 :                 get_key(8),
    7360            6 :                 Lsn(0x48),
    7361            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    7362            6 :             ),
    7363            6 :             (
    7364            6 :                 get_key(9),
    7365            6 :                 Lsn(0x48),
    7366            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    7367            6 :             ),
    7368            6 :         ];
    7369            6 : 
    7370            6 :         let tline = tenant
    7371            6 :             .create_test_timeline_with_layers(
    7372            6 :                 TIMELINE_ID,
    7373            6 :                 Lsn(0x10),
    7374            6 :                 DEFAULT_PG_VERSION,
    7375            6 :                 &ctx,
    7376            6 :                 vec![
    7377            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    7378            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    7379            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    7380            6 :                 ], // delta layers
    7381            6 :                 vec![(Lsn(0x10), img_layer)], // image layers
    7382            6 :                 Lsn(0x50),
    7383            6 :             )
    7384          141 :             .await?;
    7385            6 :         {
    7386            6 :             // Update GC info
    7387            6 :             let mut guard = tline.gc_info.write().unwrap();
    7388            6 :             *guard = GcInfo {
    7389            6 :                 retain_lsns: vec![],
    7390            6 :                 cutoffs: GcCutoffs {
    7391            6 :                     time: Lsn(0x30),
    7392            6 :                     space: Lsn(0x30),
    7393            6 :                 },
    7394            6 :                 leases: Default::default(),
    7395            6 :                 within_ancestor_pitr: false,
    7396            6 :             };
    7397            6 :         }
    7398            6 : 
    7399            6 :         let expected_result = [
    7400            6 :             Bytes::from_static(b"value 0@0x10"),
    7401            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    7402            6 :             Bytes::from_static(b"value 2@0x10@0x30"),
    7403            6 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    7404            6 :             Bytes::from_static(b"value 4@0x10"),
    7405            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    7406            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    7407            6 :             Bytes::from_static(b"value 7@0x10"),
    7408            6 :             Bytes::from_static(b"value 8@0x10@0x48"),
    7409            6 :             Bytes::from_static(b"value 9@0x10@0x48"),
    7410            6 :         ];
    7411            6 : 
    7412            6 :         let expected_result_at_gc_horizon = [
    7413            6 :             Bytes::from_static(b"value 0@0x10"),
    7414            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    7415            6 :             Bytes::from_static(b"value 2@0x10@0x30"),
    7416            6 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    7417            6 :             Bytes::from_static(b"value 4@0x10"),
    7418            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    7419            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    7420            6 :             Bytes::from_static(b"value 7@0x10"),
    7421            6 :             Bytes::from_static(b"value 8@0x10"),
    7422            6 :             Bytes::from_static(b"value 9@0x10"),
    7423            6 :         ];
    7424            6 : 
    7425           66 :         for idx in 0..10 {
    7426           60 :             assert_eq!(
    7427           60 :                 tline
    7428           60 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7429           93 :                     .await
    7430           60 :                     .unwrap(),
    7431           60 :                 &expected_result[idx]
    7432            6 :             );
    7433           60 :             assert_eq!(
    7434           60 :                 tline
    7435           60 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    7436           45 :                     .await
    7437           60 :                     .unwrap(),
    7438           60 :                 &expected_result_at_gc_horizon[idx]
    7439            6 :             );
    7440            6 :         }
    7441            6 : 
    7442            6 :         let cancel = CancellationToken::new();
    7443            6 :         tline
    7444            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7445          156 :             .await
    7446            6 :             .unwrap();
    7447            6 : 
    7448           66 :         for idx in 0..10 {
    7449           60 :             assert_eq!(
    7450           60 :                 tline
    7451           60 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7452           63 :                     .await
    7453           60 :                     .unwrap(),
    7454           60 :                 &expected_result[idx]
    7455            6 :             );
    7456           60 :             assert_eq!(
    7457           60 :                 tline
    7458           60 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    7459           30 :                     .await
    7460           60 :                     .unwrap(),
    7461           60 :                 &expected_result_at_gc_horizon[idx]
    7462            6 :             );
    7463            6 :         }
    7464            6 : 
    7465            6 :         // increase GC horizon and compact again
    7466            6 :         {
    7467            6 :             // Update GC info
    7468            6 :             let mut guard = tline.gc_info.write().unwrap();
    7469            6 :             guard.cutoffs.time = Lsn(0x40);
    7470            6 :             guard.cutoffs.space = Lsn(0x40);
    7471            6 :         }
    7472            6 :         tline
    7473            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7474          126 :             .await
    7475            6 :             .unwrap();
    7476            6 : 
    7477            6 :         Ok(())
    7478            6 :     }
    7479              : 
    7480              :     #[tokio::test]
    7481            6 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    7482            6 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    7483           24 :         let (tenant, ctx) = harness.load().await;
    7484            6 :         let tline = tenant
    7485            6 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7486           12 :             .await?;
    7487            6 :         tline.force_advance_lsn(Lsn(0x70));
    7488            6 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7489            6 :         let history = vec![
    7490            6 :             (
    7491            6 :                 key,
    7492            6 :                 Lsn(0x10),
    7493            6 :                 Value::Image(Bytes::copy_from_slice(b"0x10")),
    7494            6 :             ),
    7495            6 :             (
    7496            6 :                 key,
    7497            6 :                 Lsn(0x20),
    7498            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    7499            6 :             ),
    7500            6 :             (
    7501            6 :                 key,
    7502            6 :                 Lsn(0x30),
    7503            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    7504            6 :             ),
    7505            6 :             (
    7506            6 :                 key,
    7507            6 :                 Lsn(0x40),
    7508            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    7509            6 :             ),
    7510            6 :             (
    7511            6 :                 key,
    7512            6 :                 Lsn(0x50),
    7513            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    7514            6 :             ),
    7515            6 :             (
    7516            6 :                 key,
    7517            6 :                 Lsn(0x60),
    7518            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    7519            6 :             ),
    7520            6 :             (
    7521            6 :                 key,
    7522            6 :                 Lsn(0x70),
    7523            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7524            6 :             ),
    7525            6 :             (
    7526            6 :                 key,
    7527            6 :                 Lsn(0x80),
    7528            6 :                 Value::Image(Bytes::copy_from_slice(
    7529            6 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    7530            6 :                 )),
    7531            6 :             ),
    7532            6 :             (
    7533            6 :                 key,
    7534            6 :                 Lsn(0x90),
    7535            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    7536            6 :             ),
    7537            6 :         ];
    7538            6 :         let res = tline
    7539            6 :             .generate_key_retention(
    7540            6 :                 key,
    7541            6 :                 &history,
    7542            6 :                 Lsn(0x60),
    7543            6 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    7544            6 :                 3,
    7545            6 :                 None,
    7546            6 :             )
    7547            6 :             .await
    7548            6 :             .unwrap();
    7549            6 :         let expected_res = KeyHistoryRetention {
    7550            6 :             below_horizon: vec![
    7551            6 :                 (
    7552            6 :                     Lsn(0x20),
    7553            6 :                     KeyLogAtLsn(vec![(
    7554            6 :                         Lsn(0x20),
    7555            6 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20")),
    7556            6 :                     )]),
    7557            6 :                 ),
    7558            6 :                 (
    7559            6 :                     Lsn(0x40),
    7560            6 :                     KeyLogAtLsn(vec![
    7561            6 :                         (
    7562            6 :                             Lsn(0x30),
    7563            6 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    7564            6 :                         ),
    7565            6 :                         (
    7566            6 :                             Lsn(0x40),
    7567            6 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    7568            6 :                         ),
    7569            6 :                     ]),
    7570            6 :                 ),
    7571            6 :                 (
    7572            6 :                     Lsn(0x50),
    7573            6 :                     KeyLogAtLsn(vec![(
    7574            6 :                         Lsn(0x50),
    7575            6 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    7576            6 :                     )]),
    7577            6 :                 ),
    7578            6 :                 (
    7579            6 :                     Lsn(0x60),
    7580            6 :                     KeyLogAtLsn(vec![(
    7581            6 :                         Lsn(0x60),
    7582            6 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    7583            6 :                     )]),
    7584            6 :                 ),
    7585            6 :             ],
    7586            6 :             above_horizon: KeyLogAtLsn(vec![
    7587            6 :                 (
    7588            6 :                     Lsn(0x70),
    7589            6 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7590            6 :                 ),
    7591            6 :                 (
    7592            6 :                     Lsn(0x80),
    7593            6 :                     Value::Image(Bytes::copy_from_slice(
    7594            6 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    7595            6 :                     )),
    7596            6 :                 ),
    7597            6 :                 (
    7598            6 :                     Lsn(0x90),
    7599            6 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    7600            6 :                 ),
    7601            6 :             ]),
    7602            6 :         };
    7603            6 :         assert_eq!(res, expected_res);
    7604            6 : 
    7605            6 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    7606            6 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    7607            6 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    7608            6 :         // For example, we have
    7609            6 :         // ```plain
    7610            6 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    7611            6 :         // ```
    7612            6 :         // Now the GC horizon moves up, and we have
    7613            6 :         // ```plain
    7614            6 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    7615            6 :         // ```
    7616            6 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    7617            6 :         // We will end up with
    7618            6 :         // ```plain
    7619            6 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    7620            6 :         // ```
    7621            6 :         // Now we run the GC-compaction, and this key does not have a full history.
    7622            6 :         // We should be able to handle this partial history and drop everything before the
    7623            6 :         // gc_horizon image.
    7624            6 : 
    7625            6 :         let history = vec![
    7626            6 :             (
    7627            6 :                 key,
    7628            6 :                 Lsn(0x20),
    7629            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    7630            6 :             ),
    7631            6 :             (
    7632            6 :                 key,
    7633            6 :                 Lsn(0x30),
    7634            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    7635            6 :             ),
    7636            6 :             (
    7637            6 :                 key,
    7638            6 :                 Lsn(0x40),
    7639            6 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    7640            6 :             ),
    7641            6 :             (
    7642            6 :                 key,
    7643            6 :                 Lsn(0x50),
    7644            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    7645            6 :             ),
    7646            6 :             (
    7647            6 :                 key,
    7648            6 :                 Lsn(0x60),
    7649            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    7650            6 :             ),
    7651            6 :             (
    7652            6 :                 key,
    7653            6 :                 Lsn(0x70),
    7654            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7655            6 :             ),
    7656            6 :             (
    7657            6 :                 key,
    7658            6 :                 Lsn(0x80),
    7659            6 :                 Value::Image(Bytes::copy_from_slice(
    7660            6 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    7661            6 :                 )),
    7662            6 :             ),
    7663            6 :             (
    7664            6 :                 key,
    7665            6 :                 Lsn(0x90),
    7666            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    7667            6 :             ),
    7668            6 :         ];
    7669            6 :         let res = tline
    7670            6 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    7671            6 :             .await
    7672            6 :             .unwrap();
    7673            6 :         let expected_res = KeyHistoryRetention {
    7674            6 :             below_horizon: vec![
    7675            6 :                 (
    7676            6 :                     Lsn(0x40),
    7677            6 :                     KeyLogAtLsn(vec![(
    7678            6 :                         Lsn(0x40),
    7679            6 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    7680            6 :                     )]),
    7681            6 :                 ),
    7682            6 :                 (
    7683            6 :                     Lsn(0x50),
    7684            6 :                     KeyLogAtLsn(vec![(
    7685            6 :                         Lsn(0x50),
    7686            6 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    7687            6 :                     )]),
    7688            6 :                 ),
    7689            6 :                 (
    7690            6 :                     Lsn(0x60),
    7691            6 :                     KeyLogAtLsn(vec![(
    7692            6 :                         Lsn(0x60),
    7693            6 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    7694            6 :                     )]),
    7695            6 :                 ),
    7696            6 :             ],
    7697            6 :             above_horizon: KeyLogAtLsn(vec![
    7698            6 :                 (
    7699            6 :                     Lsn(0x70),
    7700            6 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7701            6 :                 ),
    7702            6 :                 (
    7703            6 :                     Lsn(0x80),
    7704            6 :                     Value::Image(Bytes::copy_from_slice(
    7705            6 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    7706            6 :                     )),
    7707            6 :                 ),
    7708            6 :                 (
    7709            6 :                     Lsn(0x90),
    7710            6 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    7711            6 :                 ),
    7712            6 :             ]),
    7713            6 :         };
    7714            6 :         assert_eq!(res, expected_res);
    7715            6 : 
    7716            6 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    7717            6 :         // the ancestor image in the test case.
    7718            6 : 
    7719            6 :         let history = vec![
    7720            6 :             (
    7721            6 :                 key,
    7722            6 :                 Lsn(0x20),
    7723            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    7724            6 :             ),
    7725            6 :             (
    7726            6 :                 key,
    7727            6 :                 Lsn(0x30),
    7728            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    7729            6 :             ),
    7730            6 :             (
    7731            6 :                 key,
    7732            6 :                 Lsn(0x40),
    7733            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    7734            6 :             ),
    7735            6 :             (
    7736            6 :                 key,
    7737            6 :                 Lsn(0x70),
    7738            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7739            6 :             ),
    7740            6 :         ];
    7741            6 :         let res = tline
    7742            6 :             .generate_key_retention(
    7743            6 :                 key,
    7744            6 :                 &history,
    7745            6 :                 Lsn(0x60),
    7746            6 :                 &[],
    7747            6 :                 3,
    7748            6 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    7749            6 :             )
    7750            6 :             .await
    7751            6 :             .unwrap();
    7752            6 :         let expected_res = KeyHistoryRetention {
    7753            6 :             below_horizon: vec![(
    7754            6 :                 Lsn(0x60),
    7755            6 :                 KeyLogAtLsn(vec![(
    7756            6 :                     Lsn(0x60),
    7757            6 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    7758            6 :                 )]),
    7759            6 :             )],
    7760            6 :             above_horizon: KeyLogAtLsn(vec![(
    7761            6 :                 Lsn(0x70),
    7762            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7763            6 :             )]),
    7764            6 :         };
    7765            6 :         assert_eq!(res, expected_res);
    7766            6 : 
    7767            6 :         let history = vec![
    7768            6 :             (
    7769            6 :                 key,
    7770            6 :                 Lsn(0x20),
    7771            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    7772            6 :             ),
    7773            6 :             (
    7774            6 :                 key,
    7775            6 :                 Lsn(0x40),
    7776            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    7777            6 :             ),
    7778            6 :             (
    7779            6 :                 key,
    7780            6 :                 Lsn(0x60),
    7781            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    7782            6 :             ),
    7783            6 :             (
    7784            6 :                 key,
    7785            6 :                 Lsn(0x70),
    7786            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7787            6 :             ),
    7788            6 :         ];
    7789            6 :         let res = tline
    7790            6 :             .generate_key_retention(
    7791            6 :                 key,
    7792            6 :                 &history,
    7793            6 :                 Lsn(0x60),
    7794            6 :                 &[Lsn(0x30)],
    7795            6 :                 3,
    7796            6 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    7797            6 :             )
    7798            6 :             .await
    7799            6 :             .unwrap();
    7800            6 :         let expected_res = KeyHistoryRetention {
    7801            6 :             below_horizon: vec![
    7802            6 :                 (
    7803            6 :                     Lsn(0x30),
    7804            6 :                     KeyLogAtLsn(vec![(
    7805            6 :                         Lsn(0x20),
    7806            6 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    7807            6 :                     )]),
    7808            6 :                 ),
    7809            6 :                 (
    7810            6 :                     Lsn(0x60),
    7811            6 :                     KeyLogAtLsn(vec![(
    7812            6 :                         Lsn(0x60),
    7813            6 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    7814            6 :                     )]),
    7815            6 :                 ),
    7816            6 :             ],
    7817            6 :             above_horizon: KeyLogAtLsn(vec![(
    7818            6 :                 Lsn(0x70),
    7819            6 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    7820            6 :             )]),
    7821            6 :         };
    7822            6 :         assert_eq!(res, expected_res);
    7823            6 : 
    7824            6 :         Ok(())
    7825            6 :     }
    7826              : 
    7827              :     #[tokio::test]
    7828            6 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    7829            6 :         let harness =
    7830            6 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    7831           24 :         let (tenant, ctx) = harness.load().await;
    7832            6 : 
    7833         1554 :         fn get_key(id: u32) -> Key {
    7834         1554 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7835         1554 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7836         1554 :             key.field6 = id;
    7837         1554 :             key
    7838         1554 :         }
    7839            6 : 
    7840            6 :         let img_layer = (0..10)
    7841           60 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    7842            6 :             .collect_vec();
    7843            6 : 
    7844            6 :         let delta1 = vec![
    7845            6 :             (
    7846            6 :                 get_key(1),
    7847            6 :                 Lsn(0x20),
    7848            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7849            6 :             ),
    7850            6 :             (
    7851            6 :                 get_key(2),
    7852            6 :                 Lsn(0x30),
    7853            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    7854            6 :             ),
    7855            6 :             (
    7856            6 :                 get_key(3),
    7857            6 :                 Lsn(0x28),
    7858            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    7859            6 :             ),
    7860            6 :             (
    7861            6 :                 get_key(3),
    7862            6 :                 Lsn(0x30),
    7863            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    7864            6 :             ),
    7865            6 :             (
    7866            6 :                 get_key(3),
    7867            6 :                 Lsn(0x40),
    7868            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    7869            6 :             ),
    7870            6 :         ];
    7871            6 :         let delta2 = vec![
    7872            6 :             (
    7873            6 :                 get_key(5),
    7874            6 :                 Lsn(0x20),
    7875            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7876            6 :             ),
    7877            6 :             (
    7878            6 :                 get_key(6),
    7879            6 :                 Lsn(0x20),
    7880            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7881            6 :             ),
    7882            6 :         ];
    7883            6 :         let delta3 = vec![
    7884            6 :             (
    7885            6 :                 get_key(8),
    7886            6 :                 Lsn(0x48),
    7887            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    7888            6 :             ),
    7889            6 :             (
    7890            6 :                 get_key(9),
    7891            6 :                 Lsn(0x48),
    7892            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    7893            6 :             ),
    7894            6 :         ];
    7895            6 : 
    7896            6 :         let tline = tenant
    7897            6 :             .create_test_timeline_with_layers(
    7898            6 :                 TIMELINE_ID,
    7899            6 :                 Lsn(0x10),
    7900            6 :                 DEFAULT_PG_VERSION,
    7901            6 :                 &ctx,
    7902            6 :                 vec![
    7903            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    7904            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    7905            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    7906            6 :                 ], // delta layers
    7907            6 :                 vec![(Lsn(0x10), img_layer)], // image layers
    7908            6 :                 Lsn(0x50),
    7909            6 :             )
    7910          141 :             .await?;
    7911            6 :         {
    7912            6 :             // Update GC info
    7913            6 :             let mut guard = tline.gc_info.write().unwrap();
    7914            6 :             *guard = GcInfo {
    7915            6 :                 retain_lsns: vec![
    7916            6 :                     (Lsn(0x10), tline.timeline_id),
    7917            6 :                     (Lsn(0x20), tline.timeline_id),
    7918            6 :                 ],
    7919            6 :                 cutoffs: GcCutoffs {
    7920            6 :                     time: Lsn(0x30),
    7921            6 :                     space: Lsn(0x30),
    7922            6 :                 },
    7923            6 :                 leases: Default::default(),
    7924            6 :                 within_ancestor_pitr: false,
    7925            6 :             };
    7926            6 :         }
    7927            6 : 
    7928            6 :         let expected_result = [
    7929            6 :             Bytes::from_static(b"value 0@0x10"),
    7930            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    7931            6 :             Bytes::from_static(b"value 2@0x10@0x30"),
    7932            6 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    7933            6 :             Bytes::from_static(b"value 4@0x10"),
    7934            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    7935            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    7936            6 :             Bytes::from_static(b"value 7@0x10"),
    7937            6 :             Bytes::from_static(b"value 8@0x10@0x48"),
    7938            6 :             Bytes::from_static(b"value 9@0x10@0x48"),
    7939            6 :         ];
    7940            6 : 
    7941            6 :         let expected_result_at_gc_horizon = [
    7942            6 :             Bytes::from_static(b"value 0@0x10"),
    7943            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    7944            6 :             Bytes::from_static(b"value 2@0x10@0x30"),
    7945            6 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    7946            6 :             Bytes::from_static(b"value 4@0x10"),
    7947            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    7948            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    7949            6 :             Bytes::from_static(b"value 7@0x10"),
    7950            6 :             Bytes::from_static(b"value 8@0x10"),
    7951            6 :             Bytes::from_static(b"value 9@0x10"),
    7952            6 :         ];
    7953            6 : 
    7954            6 :         let expected_result_at_lsn_20 = [
    7955            6 :             Bytes::from_static(b"value 0@0x10"),
    7956            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    7957            6 :             Bytes::from_static(b"value 2@0x10"),
    7958            6 :             Bytes::from_static(b"value 3@0x10"),
    7959            6 :             Bytes::from_static(b"value 4@0x10"),
    7960            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    7961            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    7962            6 :             Bytes::from_static(b"value 7@0x10"),
    7963            6 :             Bytes::from_static(b"value 8@0x10"),
    7964            6 :             Bytes::from_static(b"value 9@0x10"),
    7965            6 :         ];
    7966            6 : 
    7967            6 :         let expected_result_at_lsn_10 = [
    7968            6 :             Bytes::from_static(b"value 0@0x10"),
    7969            6 :             Bytes::from_static(b"value 1@0x10"),
    7970            6 :             Bytes::from_static(b"value 2@0x10"),
    7971            6 :             Bytes::from_static(b"value 3@0x10"),
    7972            6 :             Bytes::from_static(b"value 4@0x10"),
    7973            6 :             Bytes::from_static(b"value 5@0x10"),
    7974            6 :             Bytes::from_static(b"value 6@0x10"),
    7975            6 :             Bytes::from_static(b"value 7@0x10"),
    7976            6 :             Bytes::from_static(b"value 8@0x10"),
    7977            6 :             Bytes::from_static(b"value 9@0x10"),
    7978            6 :         ];
    7979            6 : 
    7980           36 :         let verify_result = || async {
    7981           36 :             let gc_horizon = {
    7982           36 :                 let gc_info = tline.gc_info.read().unwrap();
    7983           36 :                 gc_info.cutoffs.time
    7984           36 :             };
    7985          396 :             for idx in 0..10 {
    7986          360 :                 assert_eq!(
    7987          360 :                     tline
    7988          360 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7989          366 :                         .await
    7990          360 :                         .unwrap(),
    7991          360 :                     &expected_result[idx]
    7992           36 :                 );
    7993          360 :                 assert_eq!(
    7994          360 :                     tline
    7995          360 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    7996          288 :                         .await
    7997          360 :                         .unwrap(),
    7998          360 :                     &expected_result_at_gc_horizon[idx]
    7999           36 :                 );
    8000          360 :                 assert_eq!(
    8001          360 :                     tline
    8002          360 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    8003          243 :                         .await
    8004          360 :                         .unwrap(),
    8005          360 :                     &expected_result_at_lsn_20[idx]
    8006           36 :                 );
    8007          360 :                 assert_eq!(
    8008          360 :                     tline
    8009          360 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    8010          189 :                         .await
    8011          360 :                         .unwrap(),
    8012          360 :                     &expected_result_at_lsn_10[idx]
    8013           36 :                 );
    8014           36 :             }
    8015           36 :         };
    8016            6 : 
    8017          210 :         verify_result().await;
    8018            6 : 
    8019            6 :         let cancel = CancellationToken::new();
    8020            6 :         let mut dryrun_flags = EnumSet::new();
    8021            6 :         dryrun_flags.insert(CompactFlags::DryRun);
    8022            6 : 
    8023            6 :         tline
    8024            6 :             .compact_with_gc(&cancel, dryrun_flags, &ctx)
    8025          129 :             .await
    8026            6 :             .unwrap();
    8027            6 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    8028            6 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    8029          171 :         verify_result().await;
    8030            6 : 
    8031            6 :         tline
    8032            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8033          150 :             .await
    8034            6 :             .unwrap();
    8035          192 :         verify_result().await;
    8036            6 : 
    8037            6 :         // compact again
    8038            6 :         tline
    8039            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8040          117 :             .await
    8041            6 :             .unwrap();
    8042          171 :         verify_result().await;
    8043            6 : 
    8044            6 :         // increase GC horizon and compact again
    8045            6 :         {
    8046            6 :             // Update GC info
    8047            6 :             let mut guard = tline.gc_info.write().unwrap();
    8048            6 :             guard.cutoffs.time = Lsn(0x38);
    8049            6 :             guard.cutoffs.space = Lsn(0x38);
    8050            6 :         }
    8051            6 :         tline
    8052            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8053          117 :             .await
    8054            6 :             .unwrap();
    8055          171 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    8056            6 : 
    8057            6 :         // not increasing the GC horizon and compact again
    8058            6 :         tline
    8059            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8060          117 :             .await
    8061            6 :             .unwrap();
    8062          171 :         verify_result().await;
    8063            6 : 
    8064            6 :         Ok(())
    8065            6 :     }
    8066              : 
    8067              :     #[tokio::test]
    8068            6 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    8069            6 :     {
    8070            6 :         let harness =
    8071            6 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    8072            6 :                 .await?;
    8073           23 :         let (tenant, ctx) = harness.load().await;
    8074            6 : 
    8075         1056 :         fn get_key(id: u32) -> Key {
    8076         1056 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8077         1056 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8078         1056 :             key.field6 = id;
    8079         1056 :             key
    8080         1056 :         }
    8081            6 : 
    8082            6 :         let img_layer = (0..10)
    8083           60 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8084            6 :             .collect_vec();
    8085            6 : 
    8086            6 :         let delta1 = vec![
    8087            6 :             (
    8088            6 :                 get_key(1),
    8089            6 :                 Lsn(0x20),
    8090            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8091            6 :             ),
    8092            6 :             (
    8093            6 :                 get_key(1),
    8094            6 :                 Lsn(0x28),
    8095            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8096            6 :             ),
    8097            6 :         ];
    8098            6 :         let delta2 = vec![
    8099            6 :             (
    8100            6 :                 get_key(1),
    8101            6 :                 Lsn(0x30),
    8102            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8103            6 :             ),
    8104            6 :             (
    8105            6 :                 get_key(1),
    8106            6 :                 Lsn(0x38),
    8107            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    8108            6 :             ),
    8109            6 :         ];
    8110            6 :         let delta3 = vec![
    8111            6 :             (
    8112            6 :                 get_key(8),
    8113            6 :                 Lsn(0x48),
    8114            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8115            6 :             ),
    8116            6 :             (
    8117            6 :                 get_key(9),
    8118            6 :                 Lsn(0x48),
    8119            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8120            6 :             ),
    8121            6 :         ];
    8122            6 : 
    8123            6 :         let tline = tenant
    8124            6 :             .create_test_timeline_with_layers(
    8125            6 :                 TIMELINE_ID,
    8126            6 :                 Lsn(0x10),
    8127            6 :                 DEFAULT_PG_VERSION,
    8128            6 :                 &ctx,
    8129            6 :                 vec![
    8130            6 :                     // delta1 and delta 2 only contain a single key but multiple updates
    8131            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    8132            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    8133            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    8134            6 :                 ], // delta layers
    8135            6 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8136            6 :                 Lsn(0x50),
    8137            6 :             )
    8138          141 :             .await?;
    8139            6 :         {
    8140            6 :             // Update GC info
    8141            6 :             let mut guard = tline.gc_info.write().unwrap();
    8142            6 :             *guard = GcInfo {
    8143            6 :                 retain_lsns: vec![
    8144            6 :                     (Lsn(0x10), tline.timeline_id),
    8145            6 :                     (Lsn(0x20), tline.timeline_id),
    8146            6 :                 ],
    8147            6 :                 cutoffs: GcCutoffs {
    8148            6 :                     time: Lsn(0x30),
    8149            6 :                     space: Lsn(0x30),
    8150            6 :                 },
    8151            6 :                 leases: Default::default(),
    8152            6 :                 within_ancestor_pitr: false,
    8153            6 :             };
    8154            6 :         }
    8155            6 : 
    8156            6 :         let expected_result = [
    8157            6 :             Bytes::from_static(b"value 0@0x10"),
    8158            6 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    8159            6 :             Bytes::from_static(b"value 2@0x10"),
    8160            6 :             Bytes::from_static(b"value 3@0x10"),
    8161            6 :             Bytes::from_static(b"value 4@0x10"),
    8162            6 :             Bytes::from_static(b"value 5@0x10"),
    8163            6 :             Bytes::from_static(b"value 6@0x10"),
    8164            6 :             Bytes::from_static(b"value 7@0x10"),
    8165            6 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8166            6 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8167            6 :         ];
    8168            6 : 
    8169            6 :         let expected_result_at_gc_horizon = [
    8170            6 :             Bytes::from_static(b"value 0@0x10"),
    8171            6 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    8172            6 :             Bytes::from_static(b"value 2@0x10"),
    8173            6 :             Bytes::from_static(b"value 3@0x10"),
    8174            6 :             Bytes::from_static(b"value 4@0x10"),
    8175            6 :             Bytes::from_static(b"value 5@0x10"),
    8176            6 :             Bytes::from_static(b"value 6@0x10"),
    8177            6 :             Bytes::from_static(b"value 7@0x10"),
    8178            6 :             Bytes::from_static(b"value 8@0x10"),
    8179            6 :             Bytes::from_static(b"value 9@0x10"),
    8180            6 :         ];
    8181            6 : 
    8182            6 :         let expected_result_at_lsn_20 = [
    8183            6 :             Bytes::from_static(b"value 0@0x10"),
    8184            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8185            6 :             Bytes::from_static(b"value 2@0x10"),
    8186            6 :             Bytes::from_static(b"value 3@0x10"),
    8187            6 :             Bytes::from_static(b"value 4@0x10"),
    8188            6 :             Bytes::from_static(b"value 5@0x10"),
    8189            6 :             Bytes::from_static(b"value 6@0x10"),
    8190            6 :             Bytes::from_static(b"value 7@0x10"),
    8191            6 :             Bytes::from_static(b"value 8@0x10"),
    8192            6 :             Bytes::from_static(b"value 9@0x10"),
    8193            6 :         ];
    8194            6 : 
    8195            6 :         let expected_result_at_lsn_10 = [
    8196            6 :             Bytes::from_static(b"value 0@0x10"),
    8197            6 :             Bytes::from_static(b"value 1@0x10"),
    8198            6 :             Bytes::from_static(b"value 2@0x10"),
    8199            6 :             Bytes::from_static(b"value 3@0x10"),
    8200            6 :             Bytes::from_static(b"value 4@0x10"),
    8201            6 :             Bytes::from_static(b"value 5@0x10"),
    8202            6 :             Bytes::from_static(b"value 6@0x10"),
    8203            6 :             Bytes::from_static(b"value 7@0x10"),
    8204            6 :             Bytes::from_static(b"value 8@0x10"),
    8205            6 :             Bytes::from_static(b"value 9@0x10"),
    8206            6 :         ];
    8207            6 : 
    8208           24 :         let verify_result = || async {
    8209           24 :             let gc_horizon = {
    8210           24 :                 let gc_info = tline.gc_info.read().unwrap();
    8211           24 :                 gc_info.cutoffs.time
    8212           24 :             };
    8213          264 :             for idx in 0..10 {
    8214          240 :                 assert_eq!(
    8215          240 :                     tline
    8216          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8217          228 :                         .await
    8218          240 :                         .unwrap(),
    8219          240 :                     &expected_result[idx]
    8220           24 :                 );
    8221          240 :                 assert_eq!(
    8222          240 :                     tline
    8223          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    8224          141 :                         .await
    8225          240 :                         .unwrap(),
    8226          240 :                     &expected_result_at_gc_horizon[idx]
    8227           24 :                 );
    8228          240 :                 assert_eq!(
    8229          240 :                     tline
    8230          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    8231          141 :                         .await
    8232          240 :                         .unwrap(),
    8233          240 :                     &expected_result_at_lsn_20[idx]
    8234           24 :                 );
    8235          240 :                 assert_eq!(
    8236          240 :                     tline
    8237          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    8238          120 :                         .await
    8239          240 :                         .unwrap(),
    8240          240 :                     &expected_result_at_lsn_10[idx]
    8241           24 :                 );
    8242           24 :             }
    8243           24 :         };
    8244            6 : 
    8245          183 :         verify_result().await;
    8246            6 : 
    8247            6 :         let cancel = CancellationToken::new();
    8248            6 :         let mut dryrun_flags = EnumSet::new();
    8249            6 :         dryrun_flags.insert(CompactFlags::DryRun);
    8250            6 : 
    8251            6 :         tline
    8252            6 :             .compact_with_gc(&cancel, dryrun_flags, &ctx)
    8253          135 :             .await
    8254            6 :             .unwrap();
    8255            6 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    8256            6 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    8257          147 :         verify_result().await;
    8258            6 : 
    8259            6 :         tline
    8260            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8261          153 :             .await
    8262            6 :             .unwrap();
    8263          159 :         verify_result().await;
    8264            6 : 
    8265            6 :         // compact again
    8266            6 :         tline
    8267            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8268          117 :             .await
    8269            6 :             .unwrap();
    8270          141 :         verify_result().await;
    8271            6 : 
    8272            6 :         Ok(())
    8273            6 :     }
    8274              : 
    8275              :     #[tokio::test]
    8276            6 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    8277            6 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    8278           24 :         let (tenant, ctx) = harness.load().await;
    8279            6 : 
    8280          378 :         fn get_key(id: u32) -> Key {
    8281          378 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8282          378 :             key.field6 = id;
    8283          378 :             key
    8284          378 :         }
    8285            6 : 
    8286            6 :         let img_layer = (0..10)
    8287           60 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8288            6 :             .collect_vec();
    8289            6 : 
    8290            6 :         let delta1 = vec![
    8291            6 :             (
    8292            6 :                 get_key(1),
    8293            6 :                 Lsn(0x20),
    8294            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8295            6 :             ),
    8296            6 :             (
    8297            6 :                 get_key(2),
    8298            6 :                 Lsn(0x30),
    8299            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8300            6 :             ),
    8301            6 :             (
    8302            6 :                 get_key(3),
    8303            6 :                 Lsn(0x28),
    8304            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8305            6 :             ),
    8306            6 :             (
    8307            6 :                 get_key(3),
    8308            6 :                 Lsn(0x30),
    8309            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8310            6 :             ),
    8311            6 :             (
    8312            6 :                 get_key(3),
    8313            6 :                 Lsn(0x40),
    8314            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8315            6 :             ),
    8316            6 :         ];
    8317            6 :         let delta2 = vec![
    8318            6 :             (
    8319            6 :                 get_key(5),
    8320            6 :                 Lsn(0x20),
    8321            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8322            6 :             ),
    8323            6 :             (
    8324            6 :                 get_key(6),
    8325            6 :                 Lsn(0x20),
    8326            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8327            6 :             ),
    8328            6 :         ];
    8329            6 :         let delta3 = vec![
    8330            6 :             (
    8331            6 :                 get_key(8),
    8332            6 :                 Lsn(0x48),
    8333            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8334            6 :             ),
    8335            6 :             (
    8336            6 :                 get_key(9),
    8337            6 :                 Lsn(0x48),
    8338            6 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8339            6 :             ),
    8340            6 :         ];
    8341            6 : 
    8342            6 :         let parent_tline = tenant
    8343            6 :             .create_test_timeline_with_layers(
    8344            6 :                 TIMELINE_ID,
    8345            6 :                 Lsn(0x10),
    8346            6 :                 DEFAULT_PG_VERSION,
    8347            6 :                 &ctx,
    8348            6 :                 vec![],                       // delta layers
    8349            6 :                 vec![(Lsn(0x18), img_layer)], // image layers
    8350            6 :                 Lsn(0x18),
    8351            6 :             )
    8352           87 :             .await?;
    8353            6 : 
    8354            6 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    8355            6 : 
    8356            6 :         let branch_tline = tenant
    8357            6 :             .branch_timeline_test_with_layers(
    8358            6 :                 &parent_tline,
    8359            6 :                 NEW_TIMELINE_ID,
    8360            6 :                 Some(Lsn(0x18)),
    8361            6 :                 &ctx,
    8362            6 :                 vec![
    8363            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8364            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8365            6 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8366            6 :                 ], // delta layers
    8367            6 :                 vec![], // image layers
    8368            6 :                 Lsn(0x50),
    8369            6 :             )
    8370           54 :             .await?;
    8371            6 : 
    8372            6 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    8373            6 : 
    8374            6 :         {
    8375            6 :             // Update GC info
    8376            6 :             let mut guard = parent_tline.gc_info.write().unwrap();
    8377            6 :             *guard = GcInfo {
    8378            6 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id)],
    8379            6 :                 cutoffs: GcCutoffs {
    8380            6 :                     time: Lsn(0x10),
    8381            6 :                     space: Lsn(0x10),
    8382            6 :                 },
    8383            6 :                 leases: Default::default(),
    8384            6 :                 within_ancestor_pitr: false,
    8385            6 :             };
    8386            6 :         }
    8387            6 : 
    8388            6 :         {
    8389            6 :             // Update GC info
    8390            6 :             let mut guard = branch_tline.gc_info.write().unwrap();
    8391            6 :             *guard = GcInfo {
    8392            6 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id)],
    8393            6 :                 cutoffs: GcCutoffs {
    8394            6 :                     time: Lsn(0x50),
    8395            6 :                     space: Lsn(0x50),
    8396            6 :                 },
    8397            6 :                 leases: Default::default(),
    8398            6 :                 within_ancestor_pitr: false,
    8399            6 :             };
    8400            6 :         }
    8401            6 : 
    8402            6 :         let expected_result_at_gc_horizon = [
    8403            6 :             Bytes::from_static(b"value 0@0x10"),
    8404            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8405            6 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8406            6 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8407            6 :             Bytes::from_static(b"value 4@0x10"),
    8408            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8409            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8410            6 :             Bytes::from_static(b"value 7@0x10"),
    8411            6 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8412            6 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8413            6 :         ];
    8414            6 : 
    8415            6 :         let expected_result_at_lsn_40 = [
    8416            6 :             Bytes::from_static(b"value 0@0x10"),
    8417            6 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8418            6 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8419            6 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8420            6 :             Bytes::from_static(b"value 4@0x10"),
    8421            6 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8422            6 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8423            6 :             Bytes::from_static(b"value 7@0x10"),
    8424            6 :             Bytes::from_static(b"value 8@0x10"),
    8425            6 :             Bytes::from_static(b"value 9@0x10"),
    8426            6 :         ];
    8427            6 : 
    8428           12 :         let verify_result = || async {
    8429          132 :             for idx in 0..10 {
    8430          120 :                 assert_eq!(
    8431          120 :                     branch_tline
    8432          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8433          156 :                         .await
    8434          120 :                         .unwrap(),
    8435          120 :                     &expected_result_at_gc_horizon[idx]
    8436           12 :                 );
    8437          120 :                 assert_eq!(
    8438          120 :                     branch_tline
    8439          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    8440           93 :                         .await
    8441          120 :                         .unwrap(),
    8442          120 :                     &expected_result_at_lsn_40[idx]
    8443           12 :                 );
    8444           12 :             }
    8445           12 :         };
    8446            6 : 
    8447          138 :         verify_result().await;
    8448            6 : 
    8449            6 :         let cancel = CancellationToken::new();
    8450            6 :         branch_tline
    8451            6 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8452           48 :             .await
    8453            6 :             .unwrap();
    8454            6 : 
    8455          111 :         verify_result().await;
    8456            6 : 
    8457            6 :         Ok(())
    8458            6 :     }
    8459              : }
        

Generated by: LCOV version 2.1-beta