LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 80.0 % 6137 4912
Test Date: 2024-08-02 21:34:27 Functions: 60.0 % 360 216

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

Generated by: LCOV version 2.1-beta