LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 903780b8ddc62f532be8f220102da7b91c63a235.info Lines: 74.5 % 6734 5017
Test Date: 2024-10-25 10:10:57 Functions: 57.0 % 395 225

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

Generated by: LCOV version 2.1-beta