LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 53437f7e869ac68c86c7d3e4c20964c0156f158c.info Lines: 80.0 % 6601 5284
Test Date: 2024-09-20 16:14:12 Functions: 60.0 % 370 222

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

Generated by: LCOV version 2.1-beta