LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 77.6 % 5249 4073
Test Date: 2024-06-25 13:20:00 Functions: 59.5 % 343 204

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

Generated by: LCOV version 2.1-beta