LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: f8d8f5b90fa487a9e82c42da223f012f5d4fece7.info Lines: 80.1 % 6625 5304
Test Date: 2024-09-19 20:36:02 Functions: 60.2 % 372 224

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

Generated by: LCOV version 2.1-beta