LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 960803fca14b2e843c565dddf575f7017d250bc3.info Lines: 76.2 % 5081 3873
Test Date: 2024-06-22 23:41:44 Functions: 58.5 % 342 200

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

Generated by: LCOV version 2.1-beta