LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: ccf45ed1c149555259baec52d6229a81013dcd6a.info Lines: 80.0 % 6193 4952
Test Date: 2024-08-21 17:32:46 Functions: 59.7 % 362 216

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

Generated by: LCOV version 2.1-beta