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

Generated by: LCOV version 2.1-beta