LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: bb522999b2ee0ee028df22bb188d3a84170ba700.info Lines: 78.3 % 5315 4159
Test Date: 2024-07-21 16:16:09 Functions: 59.6 % 339 202

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

Generated by: LCOV version 2.1-beta