LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 07bee600374ccd486c69370d0972d9035964fe68.info Lines: 76.2 % 8552 6518
Test Date: 2025-02-20 13:11:02 Functions: 59.6 % 448 267

            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 itertools::Itertools as _;
      24              : use pageserver_api::models;
      25              : use pageserver_api::models::CompactInfoResponse;
      26              : use pageserver_api::models::LsnLease;
      27              : use pageserver_api::models::TimelineArchivalState;
      28              : use pageserver_api::models::TimelineState;
      29              : use pageserver_api::models::TopTenantShardItem;
      30              : use pageserver_api::models::WalRedoManagerStatus;
      31              : use pageserver_api::shard::ShardIdentity;
      32              : use pageserver_api::shard::ShardStripeSize;
      33              : use pageserver_api::shard::TenantShardId;
      34              : use remote_storage::DownloadError;
      35              : use remote_storage::GenericRemoteStorage;
      36              : use remote_storage::TimeoutOrCancel;
      37              : use remote_timeline_client::manifest::{
      38              :     OffloadedTimelineManifest, TenantManifest, LATEST_TENANT_MANIFEST_VERSION,
      39              : };
      40              : use remote_timeline_client::UploadQueueNotReadyError;
      41              : use remote_timeline_client::FAILED_REMOTE_OP_RETRIES;
      42              : use remote_timeline_client::FAILED_UPLOAD_WARN_THRESHOLD;
      43              : use secondary::heatmap::HeatMapTenant;
      44              : use secondary::heatmap::HeatMapTimeline;
      45              : use std::collections::BTreeMap;
      46              : use std::fmt;
      47              : use std::future::Future;
      48              : use std::sync::atomic::AtomicBool;
      49              : use std::sync::Weak;
      50              : use std::time::SystemTime;
      51              : use storage_broker::BrokerClientChannel;
      52              : use timeline::compaction::CompactionOutcome;
      53              : use timeline::compaction::GcCompactionQueue;
      54              : use timeline::import_pgdata;
      55              : use timeline::offload::offload_timeline;
      56              : use timeline::offload::OffloadError;
      57              : use timeline::CompactFlags;
      58              : use timeline::CompactOptions;
      59              : use timeline::CompactionError;
      60              : use timeline::PreviousHeatmap;
      61              : use timeline::ShutdownMode;
      62              : use tokio::io::BufReader;
      63              : use tokio::sync::watch;
      64              : use tokio::sync::Notify;
      65              : use tokio::task::JoinSet;
      66              : use tokio_util::sync::CancellationToken;
      67              : use tracing::*;
      68              : use upload_queue::NotInitialized;
      69              : use utils::backoff;
      70              : use utils::circuit_breaker::CircuitBreaker;
      71              : use utils::completion;
      72              : use utils::crashsafe::path_with_suffix_extension;
      73              : use utils::failpoint_support;
      74              : use utils::fs_ext;
      75              : use utils::pausable_failpoint;
      76              : use utils::sync::gate::Gate;
      77              : use utils::sync::gate::GateGuard;
      78              : use utils::timeout::timeout_cancellable;
      79              : use utils::timeout::TimeoutCancellableError;
      80              : use utils::try_rcu::ArcSwapExt;
      81              : use utils::zstd::create_zst_tarball;
      82              : use utils::zstd::extract_zst_tarball;
      83              : 
      84              : use self::config::AttachedLocationConfig;
      85              : use self::config::AttachmentMode;
      86              : use self::config::LocationConf;
      87              : use self::config::TenantConf;
      88              : use self::metadata::TimelineMetadata;
      89              : use self::mgr::GetActiveTenantError;
      90              : use self::mgr::GetTenantError;
      91              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      92              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      93              : use self::timeline::uninit::TimelineCreateGuard;
      94              : use self::timeline::uninit::TimelineExclusionError;
      95              : use self::timeline::uninit::UninitializedTimeline;
      96              : use self::timeline::EvictionTaskTenantState;
      97              : use self::timeline::GcCutoffs;
      98              : use self::timeline::TimelineDeleteProgress;
      99              : use self::timeline::TimelineResources;
     100              : use self::timeline::WaitLsnError;
     101              : use crate::config::PageServerConf;
     102              : use crate::context::{DownloadBehavior, RequestContext};
     103              : use crate::deletion_queue::DeletionQueueClient;
     104              : use crate::deletion_queue::DeletionQueueError;
     105              : use crate::import_datadir;
     106              : use crate::l0_flush::L0FlushGlobalState;
     107              : use crate::metrics::CONCURRENT_INITDBS;
     108              : use crate::metrics::INITDB_RUN_TIME;
     109              : use crate::metrics::INITDB_SEMAPHORE_ACQUISITION_TIME;
     110              : use crate::metrics::TENANT;
     111              : use crate::metrics::{
     112              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
     113              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
     114              : };
     115              : use crate::task_mgr;
     116              : use crate::task_mgr::TaskKind;
     117              : use crate::tenant::config::LocationMode;
     118              : use crate::tenant::config::TenantConfOpt;
     119              : use crate::tenant::gc_result::GcResult;
     120              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     121              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     122              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     123              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     124              : use crate::tenant::storage_layer::DeltaLayer;
     125              : use crate::tenant::storage_layer::ImageLayer;
     126              : use crate::walingest::WalLagCooldown;
     127              : use crate::walredo;
     128              : use crate::InitializationOrder;
     129              : use std::collections::hash_map::Entry;
     130              : use std::collections::HashMap;
     131              : use std::collections::HashSet;
     132              : use std::fmt::Debug;
     133              : use std::fmt::Display;
     134              : use std::fs;
     135              : use std::fs::File;
     136              : use std::sync::atomic::{AtomicU64, Ordering};
     137              : use std::sync::Arc;
     138              : use std::sync::Mutex;
     139              : use std::time::{Duration, Instant};
     140              : 
     141              : use crate::span;
     142              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     143              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     144              : use crate::virtual_file::VirtualFile;
     145              : use crate::walredo::PostgresRedoManager;
     146              : use crate::TEMP_FILE_SUFFIX;
     147              : use once_cell::sync::Lazy;
     148              : pub use pageserver_api::models::TenantState;
     149              : use tokio::sync::Semaphore;
     150              : 
     151            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     152              : use utils::{
     153              :     crashsafe,
     154              :     generation::Generation,
     155              :     id::TimelineId,
     156              :     lsn::{Lsn, RecordLsn},
     157              : };
     158              : 
     159              : pub mod blob_io;
     160              : pub mod block_io;
     161              : pub mod vectored_blob_io;
     162              : 
     163              : pub mod disk_btree;
     164              : pub(crate) mod ephemeral_file;
     165              : pub mod layer_map;
     166              : 
     167              : pub mod metadata;
     168              : pub mod remote_timeline_client;
     169              : pub mod storage_layer;
     170              : 
     171              : pub mod checks;
     172              : pub mod config;
     173              : pub mod mgr;
     174              : pub mod secondary;
     175              : pub mod tasks;
     176              : pub mod upload_queue;
     177              : 
     178              : pub(crate) mod timeline;
     179              : 
     180              : pub mod size;
     181              : 
     182              : mod gc_block;
     183              : mod gc_result;
     184              : pub(crate) mod throttle;
     185              : 
     186              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     187              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     188              : 
     189              : // re-export for use in walreceiver
     190              : pub use crate::tenant::timeline::WalReceiverInfo;
     191              : 
     192              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     193              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     194              : 
     195              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     196              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     197              : 
     198              : /// References to shared objects that are passed into each tenant, such
     199              : /// as the shared remote storage client and process initialization state.
     200              : #[derive(Clone)]
     201              : pub struct TenantSharedResources {
     202              :     pub broker_client: storage_broker::BrokerClientChannel,
     203              :     pub remote_storage: GenericRemoteStorage,
     204              :     pub deletion_queue_client: DeletionQueueClient,
     205              :     pub l0_flush_global_state: L0FlushGlobalState,
     206              : }
     207              : 
     208              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     209              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     210              : /// in this struct.
     211              : #[derive(Clone)]
     212              : pub(super) struct AttachedTenantConf {
     213              :     tenant_conf: TenantConfOpt,
     214              :     location: AttachedLocationConfig,
     215              :     /// The deadline before which we are blocked from GC so that
     216              :     /// leases have a chance to be renewed.
     217              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     218              : }
     219              : 
     220              : impl AttachedTenantConf {
     221          444 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     222              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     223              :         //
     224              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     225              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     226              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     227          444 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     228          444 :             Some(
     229          444 :                 tokio::time::Instant::now()
     230          444 :                     + tenant_conf
     231          444 :                         .lsn_lease_length
     232          444 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     233          444 :             )
     234              :         } else {
     235              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     236              :             // because we don't do GC in these modes.
     237            0 :             None
     238              :         };
     239              : 
     240          444 :         Self {
     241          444 :             tenant_conf,
     242          444 :             location,
     243          444 :             lsn_lease_deadline,
     244          444 :         }
     245          444 :     }
     246              : 
     247          444 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     248          444 :         match &location_conf.mode {
     249          444 :             LocationMode::Attached(attach_conf) => {
     250          444 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     251              :             }
     252              :             LocationMode::Secondary(_) => {
     253            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     254              :             }
     255              :         }
     256          444 :     }
     257              : 
     258         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     259         1524 :         self.lsn_lease_deadline
     260         1524 :             .map(|d| tokio::time::Instant::now() < d)
     261         1524 :             .unwrap_or(false)
     262         1524 :     }
     263              : }
     264              : struct TimelinePreload {
     265              :     timeline_id: TimelineId,
     266              :     client: RemoteTimelineClient,
     267              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     268              :     previous_heatmap: Option<PreviousHeatmap>,
     269              : }
     270              : 
     271              : pub(crate) struct TenantPreload {
     272              :     tenant_manifest: TenantManifest,
     273              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     274              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     275              : }
     276              : 
     277              : /// When we spawn a tenant, there is a special mode for tenant creation that
     278              : /// avoids trying to read anything from remote storage.
     279              : pub(crate) enum SpawnMode {
     280              :     /// Activate as soon as possible
     281              :     Eager,
     282              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     283              :     Lazy,
     284              : }
     285              : 
     286              : ///
     287              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     288              : ///
     289              : pub struct Tenant {
     290              :     // Global pageserver config parameters
     291              :     pub conf: &'static PageServerConf,
     292              : 
     293              :     /// The value creation timestamp, used to measure activation delay, see:
     294              :     /// <https://github.com/neondatabase/neon/issues/4025>
     295              :     constructed_at: Instant,
     296              : 
     297              :     state: watch::Sender<TenantState>,
     298              : 
     299              :     // Overridden tenant-specific config parameters.
     300              :     // We keep TenantConfOpt sturct here to preserve the information
     301              :     // about parameters that are not set.
     302              :     // This is necessary to allow global config updates.
     303              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     304              : 
     305              :     tenant_shard_id: TenantShardId,
     306              : 
     307              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     308              :     shard_identity: ShardIdentity,
     309              : 
     310              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     311              :     /// Does not change over the lifetime of the [`Tenant`] object.
     312              :     ///
     313              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     314              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     315              :     generation: Generation,
     316              : 
     317              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     318              : 
     319              :     /// During timeline creation, we first insert the TimelineId to the
     320              :     /// creating map, then `timelines`, then remove it from the creating map.
     321              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     322              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     323              : 
     324              :     /// Possibly offloaded and archived timelines
     325              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     326              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     327              : 
     328              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     329              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     330              :     /// each other (this could be optimized to coalesce writes if necessary).
     331              :     ///
     332              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     333              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     334              : 
     335              :     // This mutex prevents creation of new timelines during GC.
     336              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     337              :     // `timelines` mutex during all GC iteration
     338              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     339              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     340              :     // timeout...
     341              :     gc_cs: tokio::sync::Mutex<()>,
     342              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     343              : 
     344              :     // provides access to timeline data sitting in the remote storage
     345              :     pub(crate) remote_storage: GenericRemoteStorage,
     346              : 
     347              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     348              :     deletion_queue_client: DeletionQueueClient,
     349              : 
     350              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     351              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     352              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     353              : 
     354              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     355              : 
     356              :     /// Track repeated failures to compact, so that we can back off.
     357              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     358              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     359              : 
     360              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     361              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     362              : 
     363              :     /// Scheduled gc-compaction tasks.
     364              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     365              : 
     366              :     /// If the tenant is in Activating state, notify this to encourage it
     367              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     368              :     /// background warmup.
     369              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     370              : 
     371              :     /// Time it took for the tenant to activate. Zero if not active yet.
     372              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     373              : 
     374              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     375              :     // Timelines' cancellation token.
     376              :     pub(crate) cancel: CancellationToken,
     377              : 
     378              :     // Users of the Tenant such as the page service must take this Gate to avoid
     379              :     // trying to use a Tenant which is shutting down.
     380              :     pub(crate) gate: Gate,
     381              : 
     382              :     /// Throttle applied at the top of [`Timeline::get`].
     383              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     384              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     385              : 
     386              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     387              : 
     388              :     /// An ongoing timeline detach concurrency limiter.
     389              :     ///
     390              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     391              :     /// to have two running at the same time. A different one can be started if an earlier one
     392              :     /// has failed for whatever reason.
     393              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     394              : 
     395              :     /// `index_part.json` based gc blocking reason tracking.
     396              :     ///
     397              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     398              :     /// proceeding.
     399              :     pub(crate) gc_block: gc_block::GcBlock,
     400              : 
     401              :     l0_flush_global_state: L0FlushGlobalState,
     402              : }
     403              : impl std::fmt::Debug for Tenant {
     404            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     405            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     406            0 :     }
     407              : }
     408              : 
     409              : pub(crate) enum WalRedoManager {
     410              :     Prod(WalredoManagerId, PostgresRedoManager),
     411              :     #[cfg(test)]
     412              :     Test(harness::TestRedoManager),
     413              : }
     414              : 
     415              : #[derive(thiserror::Error, Debug)]
     416              : #[error("pageserver is shutting down")]
     417              : pub(crate) struct GlobalShutDown;
     418              : 
     419              : impl WalRedoManager {
     420            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     421            0 :         let id = WalredoManagerId::next();
     422            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     423            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     424            0 :         match &mut *guard {
     425            0 :             Some(map) => {
     426            0 :                 map.insert(id, Arc::downgrade(&arc));
     427            0 :                 Ok(arc)
     428              :             }
     429            0 :             None => Err(GlobalShutDown),
     430              :         }
     431            0 :     }
     432              : }
     433              : 
     434              : impl Drop for WalRedoManager {
     435           20 :     fn drop(&mut self) {
     436           20 :         match self {
     437            0 :             Self::Prod(id, _) => {
     438            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     439            0 :                 if let Some(map) = &mut *guard {
     440            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     441            0 :                 }
     442              :             }
     443              :             #[cfg(test)]
     444           20 :             Self::Test(_) => {
     445           20 :                 // Not applicable to test redo manager
     446           20 :             }
     447              :         }
     448           20 :     }
     449              : }
     450              : 
     451              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     452              : /// the walredo processes outside of the regular order.
     453              : ///
     454              : /// This is necessary to work around a systemd bug where it freezes if there are
     455              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     456              : #[allow(clippy::type_complexity)]
     457              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     458              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     459            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     460              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     461              : pub(crate) struct WalredoManagerId(u64);
     462              : impl WalredoManagerId {
     463            0 :     pub fn next() -> Self {
     464              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     465            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     466            0 :         if id == 0 {
     467            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     468            0 :         }
     469            0 :         Self(id)
     470            0 :     }
     471              : }
     472              : 
     473              : #[cfg(test)]
     474              : impl From<harness::TestRedoManager> for WalRedoManager {
     475          444 :     fn from(mgr: harness::TestRedoManager) -> Self {
     476          444 :         Self::Test(mgr)
     477          444 :     }
     478              : }
     479              : 
     480              : impl WalRedoManager {
     481           12 :     pub(crate) async fn shutdown(&self) -> bool {
     482           12 :         match self {
     483            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     484              :             #[cfg(test)]
     485              :             Self::Test(_) => {
     486              :                 // Not applicable to test redo manager
     487           12 :                 true
     488              :             }
     489              :         }
     490           12 :     }
     491              : 
     492            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     493            0 :         match self {
     494            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     495            0 :             #[cfg(test)]
     496            0 :             Self::Test(_) => {
     497            0 :                 // Not applicable to test redo manager
     498            0 :             }
     499            0 :         }
     500            0 :     }
     501              : 
     502              :     /// # Cancel-Safety
     503              :     ///
     504              :     /// This method is cancellation-safe.
     505         1636 :     pub async fn request_redo(
     506         1636 :         &self,
     507         1636 :         key: pageserver_api::key::Key,
     508         1636 :         lsn: Lsn,
     509         1636 :         base_img: Option<(Lsn, bytes::Bytes)>,
     510         1636 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     511         1636 :         pg_version: u32,
     512         1636 :     ) -> Result<bytes::Bytes, walredo::Error> {
     513         1636 :         match self {
     514            0 :             Self::Prod(_, mgr) => {
     515            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     516            0 :                     .await
     517              :             }
     518              :             #[cfg(test)]
     519         1636 :             Self::Test(mgr) => {
     520         1636 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     521         1636 :                     .await
     522              :             }
     523              :         }
     524         1636 :     }
     525              : 
     526            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     527            0 :         match self {
     528            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     529            0 :             #[cfg(test)]
     530            0 :             WalRedoManager::Test(_) => None,
     531            0 :         }
     532            0 :     }
     533              : }
     534              : 
     535              : /// A very lightweight memory representation of an offloaded timeline.
     536              : ///
     537              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     538              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     539              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     540              : /// more offloaded timelines than we can manage ones that aren't.
     541              : pub struct OffloadedTimeline {
     542              :     pub tenant_shard_id: TenantShardId,
     543              :     pub timeline_id: TimelineId,
     544              :     pub ancestor_timeline_id: Option<TimelineId>,
     545              :     /// Whether to retain the branch lsn at the ancestor or not
     546              :     pub ancestor_retain_lsn: Option<Lsn>,
     547              : 
     548              :     /// When the timeline was archived.
     549              :     ///
     550              :     /// Present for future flattening deliberations.
     551              :     pub archived_at: NaiveDateTime,
     552              : 
     553              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     554              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     555              :     pub delete_progress: TimelineDeleteProgress,
     556              : 
     557              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     558              :     pub deleted_from_ancestor: AtomicBool,
     559              : }
     560              : 
     561              : impl OffloadedTimeline {
     562              :     /// Obtains an offloaded timeline from a given timeline object.
     563              :     ///
     564              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     565              :     /// the timeline is not in a stopped state.
     566              :     /// Panics if the timeline is not archived.
     567            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     568            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     569            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     570            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     571            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     572            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     573            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     574            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     575              :             } else {
     576            0 :                 (None, None)
     577              :             };
     578            4 :         let archived_at = timeline
     579            4 :             .remote_client
     580            4 :             .archived_at_stopped_queue()?
     581            4 :             .expect("must be called on an archived timeline");
     582            4 :         Ok(Self {
     583            4 :             tenant_shard_id: timeline.tenant_shard_id,
     584            4 :             timeline_id: timeline.timeline_id,
     585            4 :             ancestor_timeline_id,
     586            4 :             ancestor_retain_lsn,
     587            4 :             archived_at,
     588            4 : 
     589            4 :             delete_progress: timeline.delete_progress.clone(),
     590            4 :             deleted_from_ancestor: AtomicBool::new(false),
     591            4 :         })
     592            4 :     }
     593            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     594            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     595            0 :         // by the `initialize_gc_info` function.
     596            0 :         let OffloadedTimelineManifest {
     597            0 :             timeline_id,
     598            0 :             ancestor_timeline_id,
     599            0 :             ancestor_retain_lsn,
     600            0 :             archived_at,
     601            0 :         } = *manifest;
     602            0 :         Self {
     603            0 :             tenant_shard_id,
     604            0 :             timeline_id,
     605            0 :             ancestor_timeline_id,
     606            0 :             ancestor_retain_lsn,
     607            0 :             archived_at,
     608            0 :             delete_progress: TimelineDeleteProgress::default(),
     609            0 :             deleted_from_ancestor: AtomicBool::new(false),
     610            0 :         }
     611            0 :     }
     612            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     613            4 :         let Self {
     614            4 :             timeline_id,
     615            4 :             ancestor_timeline_id,
     616            4 :             ancestor_retain_lsn,
     617            4 :             archived_at,
     618            4 :             ..
     619            4 :         } = self;
     620            4 :         OffloadedTimelineManifest {
     621            4 :             timeline_id: *timeline_id,
     622            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     623            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     624            4 :             archived_at: *archived_at,
     625            4 :         }
     626            4 :     }
     627              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     628            0 :     fn delete_from_ancestor_with_timelines(
     629            0 :         &self,
     630            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     631            0 :     ) {
     632            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     633            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     634              :         {
     635            0 :             if let Some((_, ancestor_timeline)) = timelines
     636            0 :                 .iter()
     637            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     638              :             {
     639            0 :                 let removal_happened = ancestor_timeline
     640            0 :                     .gc_info
     641            0 :                     .write()
     642            0 :                     .unwrap()
     643            0 :                     .remove_child_offloaded(self.timeline_id);
     644            0 :                 if !removal_happened {
     645            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     646            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     647            0 :                 }
     648            0 :             }
     649            0 :         }
     650            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     651            0 :     }
     652              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     653              :     ///
     654              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     655            4 :     fn defuse_for_tenant_drop(&self) {
     656            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     657            4 :     }
     658              : }
     659              : 
     660              : impl fmt::Debug for OffloadedTimeline {
     661            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     662            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     663            0 :     }
     664              : }
     665              : 
     666              : impl Drop for OffloadedTimeline {
     667            4 :     fn drop(&mut self) {
     668            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     669            0 :             tracing::warn!(
     670            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     671              :                 self.timeline_id
     672              :             );
     673            4 :         }
     674            4 :     }
     675              : }
     676              : 
     677              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     678              : pub enum MaybeOffloaded {
     679              :     Yes,
     680              :     No,
     681              : }
     682              : 
     683              : #[derive(Clone, Debug)]
     684              : pub enum TimelineOrOffloaded {
     685              :     Timeline(Arc<Timeline>),
     686              :     Offloaded(Arc<OffloadedTimeline>),
     687              : }
     688              : 
     689              : impl TimelineOrOffloaded {
     690            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     691            0 :         match self {
     692            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     693            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     694              :             }
     695            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     696            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     697              :             }
     698              :         }
     699            0 :     }
     700            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     701            0 :         self.arc_ref().tenant_shard_id()
     702            0 :     }
     703            0 :     pub fn timeline_id(&self) -> TimelineId {
     704            0 :         self.arc_ref().timeline_id()
     705            0 :     }
     706            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     707            4 :         match self {
     708            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     709            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     710              :         }
     711            4 :     }
     712            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     713            0 :         match self {
     714            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     715            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     716              :         }
     717            0 :     }
     718              : }
     719              : 
     720              : pub enum TimelineOrOffloadedArcRef<'a> {
     721              :     Timeline(&'a Arc<Timeline>),
     722              :     Offloaded(&'a Arc<OffloadedTimeline>),
     723              : }
     724              : 
     725              : impl TimelineOrOffloadedArcRef<'_> {
     726            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     727            0 :         match self {
     728            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     729            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     730              :         }
     731            0 :     }
     732            0 :     pub fn timeline_id(&self) -> TimelineId {
     733            0 :         match self {
     734            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     735            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     736              :         }
     737            0 :     }
     738              : }
     739              : 
     740              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     741            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     742            0 :         Self::Timeline(timeline)
     743            0 :     }
     744              : }
     745              : 
     746              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     747            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     748            0 :         Self::Offloaded(timeline)
     749            0 :     }
     750              : }
     751              : 
     752              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     753              : pub enum GetTimelineError {
     754              :     #[error("Timeline is shutting down")]
     755              :     ShuttingDown,
     756              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     757              :     NotActive {
     758              :         tenant_id: TenantShardId,
     759              :         timeline_id: TimelineId,
     760              :         state: TimelineState,
     761              :     },
     762              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     763              :     NotFound {
     764              :         tenant_id: TenantShardId,
     765              :         timeline_id: TimelineId,
     766              :     },
     767              : }
     768              : 
     769              : #[derive(Debug, thiserror::Error)]
     770              : pub enum LoadLocalTimelineError {
     771              :     #[error("FailedToLoad")]
     772              :     Load(#[source] anyhow::Error),
     773              :     #[error("FailedToResumeDeletion")]
     774              :     ResumeDeletion(#[source] anyhow::Error),
     775              : }
     776              : 
     777              : #[derive(thiserror::Error)]
     778              : pub enum DeleteTimelineError {
     779              :     #[error("NotFound")]
     780              :     NotFound,
     781              : 
     782              :     #[error("HasChildren")]
     783              :     HasChildren(Vec<TimelineId>),
     784              : 
     785              :     #[error("Timeline deletion is already in progress")]
     786              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     787              : 
     788              :     #[error("Cancelled")]
     789              :     Cancelled,
     790              : 
     791              :     #[error(transparent)]
     792              :     Other(#[from] anyhow::Error),
     793              : }
     794              : 
     795              : impl Debug for DeleteTimelineError {
     796            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     797            0 :         match self {
     798            0 :             Self::NotFound => write!(f, "NotFound"),
     799            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     800            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     801            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     802            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     803              :         }
     804            0 :     }
     805              : }
     806              : 
     807              : #[derive(thiserror::Error)]
     808              : pub enum TimelineArchivalError {
     809              :     #[error("NotFound")]
     810              :     NotFound,
     811              : 
     812              :     #[error("Timeout")]
     813              :     Timeout,
     814              : 
     815              :     #[error("Cancelled")]
     816              :     Cancelled,
     817              : 
     818              :     #[error("ancestor is archived: {}", .0)]
     819              :     HasArchivedParent(TimelineId),
     820              : 
     821              :     #[error("HasUnarchivedChildren")]
     822              :     HasUnarchivedChildren(Vec<TimelineId>),
     823              : 
     824              :     #[error("Timeline archival is already in progress")]
     825              :     AlreadyInProgress,
     826              : 
     827              :     #[error(transparent)]
     828              :     Other(anyhow::Error),
     829              : }
     830              : 
     831              : #[derive(thiserror::Error, Debug)]
     832              : pub(crate) enum TenantManifestError {
     833              :     #[error("Remote storage error: {0}")]
     834              :     RemoteStorage(anyhow::Error),
     835              : 
     836              :     #[error("Cancelled")]
     837              :     Cancelled,
     838              : }
     839              : 
     840              : impl From<TenantManifestError> for TimelineArchivalError {
     841            0 :     fn from(e: TenantManifestError) -> Self {
     842            0 :         match e {
     843            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     844            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     845              :         }
     846            0 :     }
     847              : }
     848              : 
     849              : impl Debug for TimelineArchivalError {
     850            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     851            0 :         match self {
     852            0 :             Self::NotFound => write!(f, "NotFound"),
     853            0 :             Self::Timeout => write!(f, "Timeout"),
     854            0 :             Self::Cancelled => write!(f, "Cancelled"),
     855            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     856            0 :             Self::HasUnarchivedChildren(c) => {
     857            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     858              :             }
     859            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     860            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     861              :         }
     862            0 :     }
     863              : }
     864              : 
     865              : pub enum SetStoppingError {
     866              :     AlreadyStopping(completion::Barrier),
     867              :     Broken,
     868              : }
     869              : 
     870              : impl Debug for SetStoppingError {
     871            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     872            0 :         match self {
     873            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     874            0 :             Self::Broken => write!(f, "Broken"),
     875              :         }
     876            0 :     }
     877              : }
     878              : 
     879              : /// Arguments to [`Tenant::create_timeline`].
     880              : ///
     881              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     882              : /// is `None`, the result of the timeline create call is not deterministic.
     883              : ///
     884              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     885              : #[derive(Debug)]
     886              : pub(crate) enum CreateTimelineParams {
     887              :     Bootstrap(CreateTimelineParamsBootstrap),
     888              :     Branch(CreateTimelineParamsBranch),
     889              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     890              : }
     891              : 
     892              : #[derive(Debug)]
     893              : pub(crate) struct CreateTimelineParamsBootstrap {
     894              :     pub(crate) new_timeline_id: TimelineId,
     895              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     896              :     pub(crate) pg_version: u32,
     897              : }
     898              : 
     899              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     900              : #[derive(Debug)]
     901              : pub(crate) struct CreateTimelineParamsBranch {
     902              :     pub(crate) new_timeline_id: TimelineId,
     903              :     pub(crate) ancestor_timeline_id: TimelineId,
     904              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     905              : }
     906              : 
     907              : #[derive(Debug)]
     908              : pub(crate) struct CreateTimelineParamsImportPgdata {
     909              :     pub(crate) new_timeline_id: TimelineId,
     910              :     pub(crate) location: import_pgdata::index_part_format::Location,
     911              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     912              : }
     913              : 
     914              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     915              : ///
     916              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     917              : ///
     918              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     919              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     920              : ///
     921              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     922              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     923              : ///
     924              : /// Notes:
     925              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     926              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     927              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     928              : ///
     929              : #[derive(Debug, Clone, PartialEq, Eq)]
     930              : pub(crate) enum CreateTimelineIdempotency {
     931              :     /// NB: special treatment, see comment in [`Self`].
     932              :     FailWithConflict,
     933              :     Bootstrap {
     934              :         pg_version: u32,
     935              :     },
     936              :     /// NB: branches always have the same `pg_version` as their ancestor.
     937              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     938              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     939              :     /// determining the child branch pg_version.
     940              :     Branch {
     941              :         ancestor_timeline_id: TimelineId,
     942              :         ancestor_start_lsn: Lsn,
     943              :     },
     944              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     945              : }
     946              : 
     947              : #[derive(Debug, Clone, PartialEq, Eq)]
     948              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     949              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     950              : }
     951              : 
     952              : /// What is returned by [`Tenant::start_creating_timeline`].
     953              : #[must_use]
     954              : enum StartCreatingTimelineResult {
     955              :     CreateGuard(TimelineCreateGuard),
     956              :     Idempotent(Arc<Timeline>),
     957              : }
     958              : 
     959              : enum TimelineInitAndSyncResult {
     960              :     ReadyToActivate(Arc<Timeline>),
     961              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     962              : }
     963              : 
     964              : impl TimelineInitAndSyncResult {
     965            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     966            0 :         match self {
     967            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     968            0 :             _ => None,
     969              :         }
     970            0 :     }
     971              : }
     972              : 
     973              : #[must_use]
     974              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     975              :     timeline: Arc<Timeline>,
     976              :     import_pgdata: import_pgdata::index_part_format::Root,
     977              :     guard: TimelineCreateGuard,
     978              : }
     979              : 
     980              : /// What is returned by [`Tenant::create_timeline`].
     981              : enum CreateTimelineResult {
     982              :     Created(Arc<Timeline>),
     983              :     Idempotent(Arc<Timeline>),
     984              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     985              :     /// we return this result, nor will this concrete object ever be added there.
     986              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     987              :     ImportSpawned(Arc<Timeline>),
     988              : }
     989              : 
     990              : impl CreateTimelineResult {
     991            0 :     fn discriminant(&self) -> &'static str {
     992            0 :         match self {
     993            0 :             Self::Created(_) => "Created",
     994            0 :             Self::Idempotent(_) => "Idempotent",
     995            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     996              :         }
     997            0 :     }
     998            0 :     fn timeline(&self) -> &Arc<Timeline> {
     999            0 :         match self {
    1000            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1001            0 :         }
    1002            0 :     }
    1003              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
    1004              :     #[cfg(test)]
    1005          460 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
    1006          460 :         match self {
    1007          460 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1008          460 :         }
    1009          460 :     }
    1010              : }
    1011              : 
    1012              : #[derive(thiserror::Error, Debug)]
    1013              : pub enum CreateTimelineError {
    1014              :     #[error("creation of timeline with the given ID is in progress")]
    1015              :     AlreadyCreating,
    1016              :     #[error("timeline already exists with different parameters")]
    1017              :     Conflict,
    1018              :     #[error(transparent)]
    1019              :     AncestorLsn(anyhow::Error),
    1020              :     #[error("ancestor timeline is not active")]
    1021              :     AncestorNotActive,
    1022              :     #[error("ancestor timeline is archived")]
    1023              :     AncestorArchived,
    1024              :     #[error("tenant shutting down")]
    1025              :     ShuttingDown,
    1026              :     #[error(transparent)]
    1027              :     Other(#[from] anyhow::Error),
    1028              : }
    1029              : 
    1030              : #[derive(thiserror::Error, Debug)]
    1031              : pub enum InitdbError {
    1032              :     #[error("Operation was cancelled")]
    1033              :     Cancelled,
    1034              :     #[error(transparent)]
    1035              :     Other(anyhow::Error),
    1036              :     #[error(transparent)]
    1037              :     Inner(postgres_initdb::Error),
    1038              : }
    1039              : 
    1040              : enum CreateTimelineCause {
    1041              :     Load,
    1042              :     Delete,
    1043              : }
    1044              : 
    1045              : enum LoadTimelineCause {
    1046              :     Attach,
    1047              :     Unoffload,
    1048              :     ImportPgdata {
    1049              :         create_guard: TimelineCreateGuard,
    1050              :         activate: ActivateTimelineArgs,
    1051              :     },
    1052              : }
    1053              : 
    1054              : #[derive(thiserror::Error, Debug)]
    1055              : pub(crate) enum GcError {
    1056              :     // The tenant is shutting down
    1057              :     #[error("tenant shutting down")]
    1058              :     TenantCancelled,
    1059              : 
    1060              :     // The tenant is shutting down
    1061              :     #[error("timeline shutting down")]
    1062              :     TimelineCancelled,
    1063              : 
    1064              :     // The tenant is in a state inelegible to run GC
    1065              :     #[error("not active")]
    1066              :     NotActive,
    1067              : 
    1068              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1069              :     #[error("not active")]
    1070              :     BadLsn { why: String },
    1071              : 
    1072              :     // A remote storage error while scheduling updates after compaction
    1073              :     #[error(transparent)]
    1074              :     Remote(anyhow::Error),
    1075              : 
    1076              :     // An error reading while calculating GC cutoffs
    1077              :     #[error(transparent)]
    1078              :     GcCutoffs(PageReconstructError),
    1079              : 
    1080              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1081              :     #[error("timeline not found")]
    1082              :     TimelineNotFound,
    1083              : }
    1084              : 
    1085              : impl From<PageReconstructError> for GcError {
    1086            0 :     fn from(value: PageReconstructError) -> Self {
    1087            0 :         match value {
    1088            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1089            0 :             other => Self::GcCutoffs(other),
    1090              :         }
    1091            0 :     }
    1092              : }
    1093              : 
    1094              : impl From<NotInitialized> for GcError {
    1095            0 :     fn from(value: NotInitialized) -> Self {
    1096            0 :         match value {
    1097            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1098            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1099              :         }
    1100            0 :     }
    1101              : }
    1102              : 
    1103              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1104            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1105            0 :         GcError::TimelineCancelled
    1106            0 :     }
    1107              : }
    1108              : 
    1109              : #[derive(thiserror::Error, Debug)]
    1110              : pub(crate) enum LoadConfigError {
    1111              :     #[error("TOML deserialization error: '{0}'")]
    1112              :     DeserializeToml(#[from] toml_edit::de::Error),
    1113              : 
    1114              :     #[error("Config not found at {0}")]
    1115              :     NotFound(Utf8PathBuf),
    1116              : }
    1117              : 
    1118              : impl Tenant {
    1119              :     /// Yet another helper for timeline initialization.
    1120              :     ///
    1121              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1122              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1123              :     /// - Downloads remote index file and adds remote files to the layer map
    1124              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1125              :     ///
    1126              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1127              :     /// it is marked as Active.
    1128              :     #[allow(clippy::too_many_arguments)]
    1129           12 :     async fn timeline_init_and_sync(
    1130           12 :         self: &Arc<Self>,
    1131           12 :         timeline_id: TimelineId,
    1132           12 :         resources: TimelineResources,
    1133           12 :         mut index_part: IndexPart,
    1134           12 :         metadata: TimelineMetadata,
    1135           12 :         previous_heatmap: Option<PreviousHeatmap>,
    1136           12 :         ancestor: Option<Arc<Timeline>>,
    1137           12 :         cause: LoadTimelineCause,
    1138           12 :         ctx: &RequestContext,
    1139           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1140           12 :         let tenant_id = self.tenant_shard_id;
    1141           12 : 
    1142           12 :         let import_pgdata = index_part.import_pgdata.take();
    1143           12 :         let idempotency = match &import_pgdata {
    1144            0 :             Some(import_pgdata) => {
    1145            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1146            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1147            0 :                 })
    1148              :             }
    1149              :             None => {
    1150           12 :                 if metadata.ancestor_timeline().is_none() {
    1151            8 :                     CreateTimelineIdempotency::Bootstrap {
    1152            8 :                         pg_version: metadata.pg_version(),
    1153            8 :                     }
    1154              :                 } else {
    1155            4 :                     CreateTimelineIdempotency::Branch {
    1156            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1157            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1158            4 :                     }
    1159              :                 }
    1160              :             }
    1161              :         };
    1162              : 
    1163           12 :         let timeline = self.create_timeline_struct(
    1164           12 :             timeline_id,
    1165           12 :             &metadata,
    1166           12 :             previous_heatmap,
    1167           12 :             ancestor.clone(),
    1168           12 :             resources,
    1169           12 :             CreateTimelineCause::Load,
    1170           12 :             idempotency.clone(),
    1171           12 :         )?;
    1172           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1173           12 :         anyhow::ensure!(
    1174           12 :             disk_consistent_lsn.is_valid(),
    1175            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1176              :         );
    1177           12 :         assert_eq!(
    1178           12 :             disk_consistent_lsn,
    1179           12 :             metadata.disk_consistent_lsn(),
    1180            0 :             "these are used interchangeably"
    1181              :         );
    1182              : 
    1183           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1184              : 
    1185           12 :         timeline
    1186           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1187           12 :             .await
    1188           12 :             .with_context(|| {
    1189            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1190           12 :             })?;
    1191              : 
    1192            0 :         match import_pgdata {
    1193            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1194            0 :                 match cause {
    1195            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1196              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1197            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1198              :                     }
    1199              :                 }
    1200            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1201            0 :                 if !guard.insert(timeline_id) {
    1202              :                     // We should never try and load the same timeline twice during startup
    1203            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1204            0 :                 }
    1205            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1206            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1207            0 :                     owning_tenant: self.clone(),
    1208            0 :                     timeline_id,
    1209            0 :                     idempotency,
    1210            0 :                     // The users of this specific return value don't need the timline_path in there.
    1211            0 :                     timeline_path: timeline
    1212            0 :                         .conf
    1213            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1214            0 :                 };
    1215            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1216            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1217            0 :                         timeline,
    1218            0 :                         import_pgdata,
    1219            0 :                         guard: timeline_create_guard,
    1220            0 :                     },
    1221            0 :                 ))
    1222              :             }
    1223              :             Some(_) | None => {
    1224              :                 {
    1225           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1226           12 :                     match timelines_accessor.entry(timeline_id) {
    1227              :                         // We should never try and load the same timeline twice during startup
    1228              :                         Entry::Occupied(_) => {
    1229            0 :                             unreachable!(
    1230            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1231            0 :                         );
    1232              :                         }
    1233           12 :                         Entry::Vacant(v) => {
    1234           12 :                             v.insert(Arc::clone(&timeline));
    1235           12 :                             timeline.maybe_spawn_flush_loop();
    1236           12 :                         }
    1237              :                     }
    1238              :                 }
    1239              : 
    1240              :                 // Sanity check: a timeline should have some content.
    1241           12 :                 anyhow::ensure!(
    1242           12 :                     ancestor.is_some()
    1243            8 :                         || timeline
    1244            8 :                             .layers
    1245            8 :                             .read()
    1246            8 :                             .await
    1247            8 :                             .layer_map()
    1248            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1249            8 :                             .iter_historic_layers()
    1250            8 :                             .next()
    1251            8 :                             .is_some(),
    1252            0 :                     "Timeline has no ancestor and no layer files"
    1253              :                 );
    1254              : 
    1255           12 :                 match cause {
    1256           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1257              :                     LoadTimelineCause::ImportPgdata {
    1258            0 :                         create_guard,
    1259            0 :                         activate,
    1260            0 :                     } => {
    1261            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1262            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1263            0 :                         match activate {
    1264            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1265            0 :                                 info!("activating timeline after reload from pgdata import task");
    1266            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1267              :                             }
    1268            0 :                             ActivateTimelineArgs::No => (),
    1269              :                         }
    1270            0 :                         drop(create_guard);
    1271              :                     }
    1272              :                 }
    1273              : 
    1274           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1275              :             }
    1276              :         }
    1277           12 :     }
    1278              : 
    1279              :     /// Attach a tenant that's available in cloud storage.
    1280              :     ///
    1281              :     /// This returns quickly, after just creating the in-memory object
    1282              :     /// Tenant struct and launching a background task to download
    1283              :     /// the remote index files.  On return, the tenant is most likely still in
    1284              :     /// Attaching state, and it will become Active once the background task
    1285              :     /// finishes. You can use wait_until_active() to wait for the task to
    1286              :     /// complete.
    1287              :     ///
    1288              :     #[allow(clippy::too_many_arguments)]
    1289            0 :     pub(crate) fn spawn(
    1290            0 :         conf: &'static PageServerConf,
    1291            0 :         tenant_shard_id: TenantShardId,
    1292            0 :         resources: TenantSharedResources,
    1293            0 :         attached_conf: AttachedTenantConf,
    1294            0 :         shard_identity: ShardIdentity,
    1295            0 :         init_order: Option<InitializationOrder>,
    1296            0 :         mode: SpawnMode,
    1297            0 :         ctx: &RequestContext,
    1298            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1299            0 :         let wal_redo_manager =
    1300            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1301              : 
    1302              :         let TenantSharedResources {
    1303            0 :             broker_client,
    1304            0 :             remote_storage,
    1305            0 :             deletion_queue_client,
    1306            0 :             l0_flush_global_state,
    1307            0 :         } = resources;
    1308            0 : 
    1309            0 :         let attach_mode = attached_conf.location.attach_mode;
    1310            0 :         let generation = attached_conf.location.generation;
    1311            0 : 
    1312            0 :         let tenant = Arc::new(Tenant::new(
    1313            0 :             TenantState::Attaching,
    1314            0 :             conf,
    1315            0 :             attached_conf,
    1316            0 :             shard_identity,
    1317            0 :             Some(wal_redo_manager),
    1318            0 :             tenant_shard_id,
    1319            0 :             remote_storage.clone(),
    1320            0 :             deletion_queue_client,
    1321            0 :             l0_flush_global_state,
    1322            0 :         ));
    1323            0 : 
    1324            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1325            0 :         // we shut down while attaching.
    1326            0 :         let attach_gate_guard = tenant
    1327            0 :             .gate
    1328            0 :             .enter()
    1329            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1330            0 : 
    1331            0 :         // Do all the hard work in the background
    1332            0 :         let tenant_clone = Arc::clone(&tenant);
    1333            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1334            0 :         task_mgr::spawn(
    1335            0 :             &tokio::runtime::Handle::current(),
    1336            0 :             TaskKind::Attach,
    1337            0 :             tenant_shard_id,
    1338            0 :             None,
    1339            0 :             "attach tenant",
    1340            0 :             async move {
    1341            0 : 
    1342            0 :                 info!(
    1343              :                     ?attach_mode,
    1344            0 :                     "Attaching tenant"
    1345              :                 );
    1346              : 
    1347            0 :                 let _gate_guard = attach_gate_guard;
    1348            0 : 
    1349            0 :                 // Is this tenant being spawned as part of process startup?
    1350            0 :                 let starting_up = init_order.is_some();
    1351            0 :                 scopeguard::defer! {
    1352            0 :                     if starting_up {
    1353            0 :                         TENANT.startup_complete.inc();
    1354            0 :                     }
    1355            0 :                 }
    1356              : 
    1357              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1358              :                 enum BrokenVerbosity {
    1359              :                     Error,
    1360              :                     Info
    1361              :                 }
    1362            0 :                 let make_broken =
    1363            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1364            0 :                         match verbosity {
    1365              :                             BrokenVerbosity::Info => {
    1366            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1367              :                             },
    1368              :                             BrokenVerbosity::Error => {
    1369            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1370              :                             }
    1371              :                         }
    1372            0 :                         t.state.send_modify(|state| {
    1373            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1374            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1375            0 :                             assert!(
    1376            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1377            0 :                                 "the attach task owns the tenant state until activation is complete"
    1378              :                             );
    1379              : 
    1380            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1381            0 :                         });
    1382            0 :                     };
    1383              : 
    1384              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1385            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1386            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1387            0 :                     return Ok(());
    1388            0 :                 }
    1389            0 : 
    1390            0 :                 let mut init_order = init_order;
    1391            0 :                 // take the completion because initial tenant loading will complete when all of
    1392            0 :                 // these tasks complete.
    1393            0 :                 let _completion = init_order
    1394            0 :                     .as_mut()
    1395            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1396            0 :                 let remote_load_completion = init_order
    1397            0 :                     .as_mut()
    1398            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1399              : 
    1400              :                 enum AttachType<'a> {
    1401              :                     /// We are attaching this tenant lazily in the background.
    1402              :                     Warmup {
    1403              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1404              :                         during_startup: bool
    1405              :                     },
    1406              :                     /// We are attaching this tenant as soon as we can, because for example an
    1407              :                     /// endpoint tried to access it.
    1408              :                     OnDemand,
    1409              :                     /// During normal operations after startup, we are attaching a tenant, and
    1410              :                     /// eager attach was requested.
    1411              :                     Normal,
    1412              :                 }
    1413              : 
    1414            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1415              :                     // Before doing any I/O, wait for at least one of:
    1416              :                     // - A client attempting to access to this tenant (on-demand loading)
    1417              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1418              : 
    1419            0 :                     tokio::select!(
    1420            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1421            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1422            0 :                             tracing::info!("Activating tenant (on-demand)");
    1423            0 :                             AttachType::OnDemand
    1424              :                         },
    1425            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1426            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1427            0 :                             tracing::info!("Activating tenant (warmup)");
    1428            0 :                             AttachType::Warmup {
    1429            0 :                                 _permit,
    1430            0 :                                 during_startup: init_order.is_some()
    1431            0 :                             }
    1432              :                         }
    1433            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1434              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1435              :                             // stayed in Activating for such a long time that shutdown found it in
    1436              :                             // that state.
    1437            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1438              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1439              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1440              :                             // just shutting down), but ensures progress.
    1441            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1442            0 :                             return Ok(());
    1443              :                         },
    1444              :                     )
    1445              :                 } else {
    1446              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1447              :                     // concurrent_tenant_warmup queue
    1448            0 :                     AttachType::Normal
    1449              :                 };
    1450              : 
    1451            0 :                 let preload = match &mode {
    1452              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1453            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1454            0 :                         let res = tenant_clone
    1455            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1456            0 :                             .await;
    1457            0 :                         match res {
    1458            0 :                             Ok(p) => Some(p),
    1459            0 :                             Err(e) => {
    1460            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1461            0 :                                 return Ok(());
    1462              :                             }
    1463              :                         }
    1464              :                     }
    1465              : 
    1466              :                 };
    1467              : 
    1468              :                 // Remote preload is complete.
    1469            0 :                 drop(remote_load_completion);
    1470            0 : 
    1471            0 : 
    1472            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1473            0 :                 let attach_start = std::time::Instant::now();
    1474            0 :                 let attached = {
    1475            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1476            0 :                     tenant_clone.attach(preload, &ctx).await
    1477              :                 };
    1478            0 :                 let attach_duration = attach_start.elapsed();
    1479            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1480            0 : 
    1481            0 :                 match attached {
    1482              :                     Ok(()) => {
    1483            0 :                         info!("attach finished, activating");
    1484            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1485              :                     }
    1486            0 :                     Err(e) => {
    1487            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1488            0 :                     }
    1489              :                 }
    1490              : 
    1491              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1492              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1493              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1494              :                 //
    1495              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1496              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1497              :                 // then warmup will wait for that before proceeding to the next tenant.
    1498            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1499            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1500            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1501            0 :                     while futs.next().await.is_some() {}
    1502            0 :                     tracing::info!("Warm-up complete");
    1503            0 :                 }
    1504              : 
    1505            0 :                 Ok(())
    1506            0 :             }
    1507            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1508              :         );
    1509            0 :         Ok(tenant)
    1510            0 :     }
    1511              : 
    1512              :     #[instrument(skip_all)]
    1513              :     pub(crate) async fn preload(
    1514              :         self: &Arc<Self>,
    1515              :         remote_storage: &GenericRemoteStorage,
    1516              :         cancel: CancellationToken,
    1517              :     ) -> anyhow::Result<TenantPreload> {
    1518              :         span::debug_assert_current_span_has_tenant_id();
    1519              :         // Get list of remote timelines
    1520              :         // download index files for every tenant timeline
    1521              :         info!("listing remote timelines");
    1522              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1523              :             remote_storage,
    1524              :             self.tenant_shard_id,
    1525              :             cancel.clone(),
    1526              :         )
    1527              :         .await?;
    1528              :         let (offloaded_add, tenant_manifest) =
    1529              :             match remote_timeline_client::download_tenant_manifest(
    1530              :                 remote_storage,
    1531              :                 &self.tenant_shard_id,
    1532              :                 self.generation,
    1533              :                 &cancel,
    1534              :             )
    1535              :             .await
    1536              :             {
    1537              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1538              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1539              :                     tenant_manifest,
    1540              :                 ),
    1541              :                 Err(DownloadError::NotFound) => {
    1542              :                     ("no manifest".to_string(), TenantManifest::empty())
    1543              :                 }
    1544              :                 Err(e) => Err(e)?,
    1545              :             };
    1546              : 
    1547              :         info!(
    1548              :             "found {} timelines, and {offloaded_add}",
    1549              :             remote_timeline_ids.len()
    1550              :         );
    1551              : 
    1552              :         for k in other_keys {
    1553              :             warn!("Unexpected non timeline key {k}");
    1554              :         }
    1555              : 
    1556              :         // Avoid downloading IndexPart of offloaded timelines.
    1557              :         let mut offloaded_with_prefix = HashSet::new();
    1558              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1559              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1560              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1561              :             } else {
    1562              :                 // We'll take care later of timelines in the manifest without a prefix
    1563              :             }
    1564              :         }
    1565              : 
    1566              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1567              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1568              :         // will kick the secondary in any case and cause a download.
    1569              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1570              : 
    1571              :         let timelines = self
    1572              :             .load_timelines_metadata(
    1573              :                 remote_timeline_ids,
    1574              :                 remote_storage,
    1575              :                 maybe_heatmap_at,
    1576              :                 cancel,
    1577              :             )
    1578              :             .await?;
    1579              : 
    1580              :         Ok(TenantPreload {
    1581              :             tenant_manifest,
    1582              :             timelines: timelines
    1583              :                 .into_iter()
    1584           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1585            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1586              :                 .collect(),
    1587              :         })
    1588              :     }
    1589              : 
    1590          444 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1591          444 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1592          444 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1593            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1594            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1595            0 :                 Err(err) => {
    1596            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1597            0 :                     None
    1598              :                 }
    1599              :             },
    1600          444 :             Err(err) => match err.kind() {
    1601          444 :                 std::io::ErrorKind::NotFound => None,
    1602              :                 _ => {
    1603            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1604            0 :                     None
    1605              :                 }
    1606              :             },
    1607              :         }
    1608          444 :     }
    1609              : 
    1610              :     ///
    1611              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1612              :     ///
    1613              :     /// No background tasks are started as part of this routine.
    1614              :     ///
    1615          444 :     async fn attach(
    1616          444 :         self: &Arc<Tenant>,
    1617          444 :         preload: Option<TenantPreload>,
    1618          444 :         ctx: &RequestContext,
    1619          444 :     ) -> anyhow::Result<()> {
    1620          444 :         span::debug_assert_current_span_has_tenant_id();
    1621          444 : 
    1622          444 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1623              : 
    1624          444 :         let Some(preload) = preload else {
    1625            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1626              :         };
    1627              : 
    1628          444 :         let mut offloaded_timeline_ids = HashSet::new();
    1629          444 :         let mut offloaded_timelines_list = Vec::new();
    1630          444 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1631            0 :             let timeline_id = timeline_manifest.timeline_id;
    1632            0 :             let offloaded_timeline =
    1633            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1634            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1635            0 :             offloaded_timeline_ids.insert(timeline_id);
    1636            0 :         }
    1637              :         // Complete deletions for offloaded timeline id's from manifest.
    1638              :         // The manifest will be uploaded later in this function.
    1639          444 :         offloaded_timelines_list
    1640          444 :             .retain(|(offloaded_id, offloaded)| {
    1641            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1642            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1643            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1644            0 :                 if delete {
    1645            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1646            0 :                     offloaded.defuse_for_tenant_drop();
    1647            0 :                 }
    1648            0 :                 !delete
    1649          444 :         });
    1650          444 : 
    1651          444 :         let mut timelines_to_resume_deletions = vec![];
    1652          444 : 
    1653          444 :         let mut remote_index_and_client = HashMap::new();
    1654          444 :         let mut timeline_ancestors = HashMap::new();
    1655          444 :         let mut existent_timelines = HashSet::new();
    1656          456 :         for (timeline_id, preload) in preload.timelines {
    1657           12 :             let Some(preload) = preload else { continue };
    1658              :             // This is an invariant of the `preload` function's API
    1659           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1660           12 :             let index_part = match preload.index_part {
    1661           12 :                 Ok(i) => {
    1662           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1663              :                     // We found index_part on the remote, this is the standard case.
    1664           12 :                     existent_timelines.insert(timeline_id);
    1665           12 :                     i
    1666              :                 }
    1667              :                 Err(DownloadError::NotFound) => {
    1668              :                     // There is no index_part on the remote. We only get here
    1669              :                     // if there is some prefix for the timeline in the remote storage.
    1670              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1671              :                     // remnant from a prior incomplete creation or deletion attempt.
    1672              :                     // Delete the local directory as the deciding criterion for a
    1673              :                     // timeline's existence is presence of index_part.
    1674            0 :                     info!(%timeline_id, "index_part not found on remote");
    1675            0 :                     continue;
    1676              :                 }
    1677            0 :                 Err(DownloadError::Fatal(why)) => {
    1678            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1679            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1680            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1681            0 :                     anyhow::bail!(why.to_string());
    1682              :                 }
    1683            0 :                 Err(e) => {
    1684            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1685            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1686            0 :                     // as it might be a temporary issue and we don't want to re-download
    1687            0 :                     // everything after it resolves.
    1688            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1689              : 
    1690            0 :                     existent_timelines.insert(timeline_id);
    1691            0 :                     continue;
    1692              :                 }
    1693              :             };
    1694           12 :             match index_part {
    1695           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1696           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1697           12 :                     remote_index_and_client.insert(
    1698           12 :                         timeline_id,
    1699           12 :                         (index_part, preload.client, preload.previous_heatmap),
    1700           12 :                     );
    1701           12 :                 }
    1702            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1703            0 :                     info!(
    1704            0 :                         "timeline {} is deleted, picking to resume deletion",
    1705              :                         timeline_id
    1706              :                     );
    1707            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1708              :                 }
    1709              :             }
    1710              :         }
    1711              : 
    1712          444 :         let mut gc_blocks = HashMap::new();
    1713              : 
    1714              :         // For every timeline, download the metadata file, scan the local directory,
    1715              :         // and build a layer map that contains an entry for each remote and local
    1716              :         // layer file.
    1717          444 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1718          456 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1719           12 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1720           12 :                 .remove(&timeline_id)
    1721           12 :                 .expect("just put it in above");
    1722              : 
    1723           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1724              :                 // could just filter these away, but it helps while testing
    1725            0 :                 anyhow::ensure!(
    1726            0 :                     !blocking.reasons.is_empty(),
    1727            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1728              :                 );
    1729            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1730            0 :                 assert!(prev.is_none());
    1731           12 :             }
    1732              : 
    1733              :             // TODO again handle early failure
    1734           12 :             let effect = self
    1735           12 :                 .load_remote_timeline(
    1736           12 :                     timeline_id,
    1737           12 :                     index_part,
    1738           12 :                     remote_metadata,
    1739           12 :                     previous_heatmap,
    1740           12 :                     self.get_timeline_resources_for(remote_client),
    1741           12 :                     LoadTimelineCause::Attach,
    1742           12 :                     ctx,
    1743           12 :                 )
    1744           12 :                 .await
    1745           12 :                 .with_context(|| {
    1746            0 :                     format!(
    1747            0 :                         "failed to load remote timeline {} for tenant {}",
    1748            0 :                         timeline_id, self.tenant_shard_id
    1749            0 :                     )
    1750           12 :                 })?;
    1751              : 
    1752           12 :             match effect {
    1753           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1754           12 :                     // activation happens later, on Tenant::activate
    1755           12 :                 }
    1756              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1757              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1758            0 :                         timeline,
    1759            0 :                         import_pgdata,
    1760            0 :                         guard,
    1761            0 :                     },
    1762            0 :                 ) => {
    1763            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1764            0 :                         timeline,
    1765            0 :                         import_pgdata,
    1766            0 :                         ActivateTimelineArgs::No,
    1767            0 :                         guard,
    1768            0 :                     ));
    1769            0 :                 }
    1770              :             }
    1771              :         }
    1772              : 
    1773              :         // Walk through deleted timelines, resume deletion
    1774          444 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1775            0 :             remote_timeline_client
    1776            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1777            0 :                 .context("init queue stopped")
    1778            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1779              : 
    1780            0 :             DeleteTimelineFlow::resume_deletion(
    1781            0 :                 Arc::clone(self),
    1782            0 :                 timeline_id,
    1783            0 :                 &index_part.metadata,
    1784            0 :                 remote_timeline_client,
    1785            0 :             )
    1786            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1787            0 :             .await
    1788            0 :             .context("resume_deletion")
    1789            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1790              :         }
    1791          444 :         let needs_manifest_upload =
    1792          444 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1793          444 :         {
    1794          444 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1795          444 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1796          444 :         }
    1797          444 :         if needs_manifest_upload {
    1798            0 :             self.store_tenant_manifest().await?;
    1799          444 :         }
    1800              : 
    1801              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1802              :         // IndexPart is the source of truth.
    1803          444 :         self.clean_up_timelines(&existent_timelines)?;
    1804              : 
    1805          444 :         self.gc_block.set_scanned(gc_blocks);
    1806          444 : 
    1807          444 :         fail::fail_point!("attach-before-activate", |_| {
    1808            0 :             anyhow::bail!("attach-before-activate");
    1809          444 :         });
    1810          444 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1811              : 
    1812          444 :         info!("Done");
    1813              : 
    1814          444 :         Ok(())
    1815          444 :     }
    1816              : 
    1817              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1818              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1819              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1820          444 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1821          444 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1822              : 
    1823          444 :         let entries = match timelines_dir.read_dir_utf8() {
    1824          444 :             Ok(d) => d,
    1825            0 :             Err(e) => {
    1826            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1827            0 :                     return Ok(());
    1828              :                 } else {
    1829            0 :                     return Err(e).context("list timelines directory for tenant");
    1830              :                 }
    1831              :             }
    1832              :         };
    1833              : 
    1834          460 :         for entry in entries {
    1835           16 :             let entry = entry.context("read timeline dir entry")?;
    1836           16 :             let entry_path = entry.path();
    1837              : 
    1838           16 :             let purge = if crate::is_temporary(entry_path) {
    1839            0 :                 true
    1840              :             } else {
    1841           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1842           16 :                     Ok(i) => {
    1843           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1844           16 :                         !existent_timelines.contains(&i)
    1845              :                     }
    1846            0 :                     Err(e) => {
    1847            0 :                         tracing::warn!(
    1848            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1849              :                         );
    1850              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1851            0 :                         false
    1852              :                     }
    1853              :                 }
    1854              :             };
    1855              : 
    1856           16 :             if purge {
    1857            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1858            4 :                 if let Err(e) = match entry.file_type() {
    1859            4 :                     Ok(t) => if t.is_dir() {
    1860            4 :                         std::fs::remove_dir_all(entry_path)
    1861              :                     } else {
    1862            0 :                         std::fs::remove_file(entry_path)
    1863              :                     }
    1864            4 :                     .or_else(fs_ext::ignore_not_found),
    1865            0 :                     Err(e) => Err(e),
    1866              :                 } {
    1867            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1868            4 :                 }
    1869           12 :             }
    1870              :         }
    1871              : 
    1872          444 :         Ok(())
    1873          444 :     }
    1874              : 
    1875              :     /// Get sum of all remote timelines sizes
    1876              :     ///
    1877              :     /// This function relies on the index_part instead of listing the remote storage
    1878            0 :     pub fn remote_size(&self) -> u64 {
    1879            0 :         let mut size = 0;
    1880              : 
    1881            0 :         for timeline in self.list_timelines() {
    1882            0 :             size += timeline.remote_client.get_remote_physical_size();
    1883            0 :         }
    1884              : 
    1885            0 :         size
    1886            0 :     }
    1887              : 
    1888              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1889              :     #[allow(clippy::too_many_arguments)]
    1890              :     async fn load_remote_timeline(
    1891              :         self: &Arc<Self>,
    1892              :         timeline_id: TimelineId,
    1893              :         index_part: IndexPart,
    1894              :         remote_metadata: TimelineMetadata,
    1895              :         previous_heatmap: Option<PreviousHeatmap>,
    1896              :         resources: TimelineResources,
    1897              :         cause: LoadTimelineCause,
    1898              :         ctx: &RequestContext,
    1899              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1900              :         span::debug_assert_current_span_has_tenant_id();
    1901              : 
    1902              :         info!("downloading index file for timeline {}", timeline_id);
    1903              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1904              :             .await
    1905              :             .context("Failed to create new timeline directory")?;
    1906              : 
    1907              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1908              :             let timelines = self.timelines.lock().unwrap();
    1909              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1910            0 :                 || {
    1911            0 :                     anyhow::anyhow!(
    1912            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1913            0 :                     )
    1914            0 :                 },
    1915              :             )?))
    1916              :         } else {
    1917              :             None
    1918              :         };
    1919              : 
    1920              :         self.timeline_init_and_sync(
    1921              :             timeline_id,
    1922              :             resources,
    1923              :             index_part,
    1924              :             remote_metadata,
    1925              :             previous_heatmap,
    1926              :             ancestor,
    1927              :             cause,
    1928              :             ctx,
    1929              :         )
    1930              :         .await
    1931              :     }
    1932              : 
    1933          444 :     async fn load_timelines_metadata(
    1934          444 :         self: &Arc<Tenant>,
    1935          444 :         timeline_ids: HashSet<TimelineId>,
    1936          444 :         remote_storage: &GenericRemoteStorage,
    1937          444 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1938          444 :         cancel: CancellationToken,
    1939          444 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1940          444 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1941          444 : 
    1942          444 :         let mut part_downloads = JoinSet::new();
    1943          456 :         for timeline_id in timeline_ids {
    1944           12 :             let cancel_clone = cancel.clone();
    1945           12 : 
    1946           12 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1947            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1948            0 :                     heatmap: h,
    1949            0 :                     read_at: hs.1,
    1950            0 :                 })
    1951           12 :             });
    1952           12 :             part_downloads.spawn(
    1953           12 :                 self.load_timeline_metadata(
    1954           12 :                     timeline_id,
    1955           12 :                     remote_storage.clone(),
    1956           12 :                     previous_timeline_heatmap,
    1957           12 :                     cancel_clone,
    1958           12 :                 )
    1959           12 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1960              :             );
    1961              :         }
    1962              : 
    1963          444 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1964              : 
    1965              :         loop {
    1966          456 :             tokio::select!(
    1967          456 :                 next = part_downloads.join_next() => {
    1968          456 :                     match next {
    1969           12 :                         Some(result) => {
    1970           12 :                             let preload = result.context("join preload task")?;
    1971           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1972              :                         },
    1973              :                         None => {
    1974          444 :                             break;
    1975              :                         }
    1976              :                     }
    1977              :                 },
    1978          456 :                 _ = cancel.cancelled() => {
    1979            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1980              :                 }
    1981              :             )
    1982              :         }
    1983              : 
    1984          444 :         Ok(timeline_preloads)
    1985          444 :     }
    1986              : 
    1987           12 :     fn build_timeline_client(
    1988           12 :         &self,
    1989           12 :         timeline_id: TimelineId,
    1990           12 :         remote_storage: GenericRemoteStorage,
    1991           12 :     ) -> RemoteTimelineClient {
    1992           12 :         RemoteTimelineClient::new(
    1993           12 :             remote_storage.clone(),
    1994           12 :             self.deletion_queue_client.clone(),
    1995           12 :             self.conf,
    1996           12 :             self.tenant_shard_id,
    1997           12 :             timeline_id,
    1998           12 :             self.generation,
    1999           12 :             &self.tenant_conf.load().location,
    2000           12 :         )
    2001           12 :     }
    2002              : 
    2003           12 :     fn load_timeline_metadata(
    2004           12 :         self: &Arc<Tenant>,
    2005           12 :         timeline_id: TimelineId,
    2006           12 :         remote_storage: GenericRemoteStorage,
    2007           12 :         previous_heatmap: Option<PreviousHeatmap>,
    2008           12 :         cancel: CancellationToken,
    2009           12 :     ) -> impl Future<Output = TimelinePreload> {
    2010           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2011           12 :         async move {
    2012           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2013           12 :             debug!("starting index part download");
    2014              : 
    2015           12 :             let index_part = client.download_index_file(&cancel).await;
    2016              : 
    2017           12 :             debug!("finished index part download");
    2018              : 
    2019           12 :             TimelinePreload {
    2020           12 :                 client,
    2021           12 :                 timeline_id,
    2022           12 :                 index_part,
    2023           12 :                 previous_heatmap,
    2024           12 :             }
    2025           12 :         }
    2026           12 :     }
    2027              : 
    2028            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2029            0 :         timeline_id: TimelineId,
    2030            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2031            0 :     ) -> Result<(), TimelineArchivalError> {
    2032            0 :         let children: Vec<TimelineId> = timelines
    2033            0 :             .iter()
    2034            0 :             .filter_map(|(id, entry)| {
    2035            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2036            0 :                     return None;
    2037            0 :                 }
    2038            0 :                 if entry.is_archived() == Some(true) {
    2039            0 :                     return None;
    2040            0 :                 }
    2041            0 :                 Some(*id)
    2042            0 :             })
    2043            0 :             .collect();
    2044            0 : 
    2045            0 :         if !children.is_empty() {
    2046            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2047            0 :         }
    2048            0 :         Ok(())
    2049            0 :     }
    2050              : 
    2051            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2052            0 :         ancestor_timeline_id: TimelineId,
    2053            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2054            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2055            0 :             '_,
    2056            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2057            0 :         >,
    2058            0 :     ) -> Result<(), TimelineArchivalError> {
    2059            0 :         let has_archived_parent =
    2060            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2061            0 :                 ancestor_timeline.is_archived() == Some(true)
    2062            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2063            0 :                 true
    2064              :             } else {
    2065            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2066            0 :                 if cfg!(debug_assertions) {
    2067            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2068            0 :                 }
    2069            0 :                 return Err(TimelineArchivalError::NotFound);
    2070              :             };
    2071            0 :         if has_archived_parent {
    2072            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2073            0 :                 ancestor_timeline_id,
    2074            0 :             ));
    2075            0 :         }
    2076            0 :         Ok(())
    2077            0 :     }
    2078              : 
    2079            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2080            0 :         timeline: &Arc<Timeline>,
    2081            0 :     ) -> Result<(), TimelineArchivalError> {
    2082            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2083            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2084            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2085            0 :                     ancestor_timeline.timeline_id,
    2086            0 :                 ));
    2087            0 :             }
    2088            0 :         }
    2089            0 :         Ok(())
    2090            0 :     }
    2091              : 
    2092              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2093              :     ///
    2094              :     /// Counterpart to [`offload_timeline`].
    2095            0 :     async fn unoffload_timeline(
    2096            0 :         self: &Arc<Self>,
    2097            0 :         timeline_id: TimelineId,
    2098            0 :         broker_client: storage_broker::BrokerClientChannel,
    2099            0 :         ctx: RequestContext,
    2100            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2101            0 :         info!("unoffloading timeline");
    2102              : 
    2103              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2104              :         // We expect callers of this function to ensure this.
    2105            0 :         match self.current_state() {
    2106              :             TenantState::Activating { .. }
    2107              :             | TenantState::Attaching
    2108              :             | TenantState::Broken { .. } => {
    2109            0 :                 panic!("Timeline expected to be active")
    2110              :             }
    2111            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2112            0 :             TenantState::Active => {}
    2113            0 :         }
    2114            0 :         let cancel = self.cancel.clone();
    2115            0 : 
    2116            0 :         // Protect against concurrent attempts to use this TimelineId
    2117            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2118            0 :         let allow_offloaded = true;
    2119            0 :         let _create_guard = self
    2120            0 :             .create_timeline_create_guard(
    2121            0 :                 timeline_id,
    2122            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2123            0 :                 allow_offloaded,
    2124            0 :             )
    2125            0 :             .map_err(|err| match err {
    2126            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2127              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2128            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2129              :                 }
    2130            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2131            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2132            0 :             })?;
    2133              : 
    2134            0 :         let timeline_preload = self
    2135            0 :             .load_timeline_metadata(
    2136            0 :                 timeline_id,
    2137            0 :                 self.remote_storage.clone(),
    2138            0 :                 None,
    2139            0 :                 cancel.clone(),
    2140            0 :             )
    2141            0 :             .await;
    2142              : 
    2143            0 :         let index_part = match timeline_preload.index_part {
    2144            0 :             Ok(index_part) => {
    2145            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2146            0 :                 index_part
    2147              :             }
    2148              :             Err(DownloadError::NotFound) => {
    2149            0 :                 error!(%timeline_id, "index_part not found on remote");
    2150            0 :                 return Err(TimelineArchivalError::NotFound);
    2151              :             }
    2152            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2153            0 :             Err(e) => {
    2154            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2155            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2156            0 :                 return Err(TimelineArchivalError::Other(
    2157            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2158            0 :                 ));
    2159              :             }
    2160              :         };
    2161            0 :         let index_part = match index_part {
    2162            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2163            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2164            0 :                 info!("timeline is deleted according to index_part.json");
    2165            0 :                 return Err(TimelineArchivalError::NotFound);
    2166              :             }
    2167              :         };
    2168            0 :         let remote_metadata = index_part.metadata.clone();
    2169            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2170            0 :         self.load_remote_timeline(
    2171            0 :             timeline_id,
    2172            0 :             index_part,
    2173            0 :             remote_metadata,
    2174            0 :             None,
    2175            0 :             timeline_resources,
    2176            0 :             LoadTimelineCause::Unoffload,
    2177            0 :             &ctx,
    2178            0 :         )
    2179            0 :         .await
    2180            0 :         .with_context(|| {
    2181            0 :             format!(
    2182            0 :                 "failed to load remote timeline {} for tenant {}",
    2183            0 :                 timeline_id, self.tenant_shard_id
    2184            0 :             )
    2185            0 :         })
    2186            0 :         .map_err(TimelineArchivalError::Other)?;
    2187              : 
    2188            0 :         let timeline = {
    2189            0 :             let timelines = self.timelines.lock().unwrap();
    2190            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2191            0 :                 warn!("timeline not available directly after attach");
    2192              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2193              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2194            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2195            0 :                     "timeline not available directly after attach"
    2196            0 :                 )));
    2197              :             };
    2198            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2199            0 :             match offloaded_timelines.remove(&timeline_id) {
    2200            0 :                 Some(offloaded) => {
    2201            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2202            0 :                 }
    2203            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2204              :             }
    2205              : 
    2206            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2207            0 : 
    2208            0 :             Arc::clone(timeline)
    2209            0 :         };
    2210            0 : 
    2211            0 :         // Upload new list of offloaded timelines to S3
    2212            0 :         self.store_tenant_manifest().await?;
    2213              : 
    2214              :         // Activate the timeline (if it makes sense)
    2215            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2216            0 :             let background_jobs_can_start = None;
    2217            0 :             timeline.activate(
    2218            0 :                 self.clone(),
    2219            0 :                 broker_client.clone(),
    2220            0 :                 background_jobs_can_start,
    2221            0 :                 &ctx,
    2222            0 :             );
    2223            0 :         }
    2224              : 
    2225            0 :         info!("timeline unoffloading complete");
    2226            0 :         Ok(timeline)
    2227            0 :     }
    2228              : 
    2229            0 :     pub(crate) async fn apply_timeline_archival_config(
    2230            0 :         self: &Arc<Self>,
    2231            0 :         timeline_id: TimelineId,
    2232            0 :         new_state: TimelineArchivalState,
    2233            0 :         broker_client: storage_broker::BrokerClientChannel,
    2234            0 :         ctx: RequestContext,
    2235            0 :     ) -> Result<(), TimelineArchivalError> {
    2236            0 :         info!("setting timeline archival config");
    2237              :         // First part: figure out what is needed to do, and do validation
    2238            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2239            0 :             let timelines = self.timelines.lock().unwrap();
    2240              : 
    2241            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2242            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2243            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2244            0 :                     return Err(TimelineArchivalError::NotFound);
    2245              :                 };
    2246            0 :                 if new_state == TimelineArchivalState::Archived {
    2247              :                     // It's offloaded already, so nothing to do
    2248            0 :                     return Ok(());
    2249            0 :                 }
    2250            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2251            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2252            0 :                         ancestor_timeline_id,
    2253            0 :                         &timelines,
    2254            0 :                         &offloaded_timelines,
    2255            0 :                     )?;
    2256            0 :                 }
    2257            0 :                 break 'outer None;
    2258              :             };
    2259              : 
    2260              :             // Do some validation. We release the timelines lock below, so there is potential
    2261              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2262              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2263            0 :             match new_state {
    2264              :                 TimelineArchivalState::Unarchived => {
    2265            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2266              :                 }
    2267              :                 TimelineArchivalState::Archived => {
    2268            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2269              :                 }
    2270              :             }
    2271            0 :             Some(Arc::clone(timeline))
    2272              :         };
    2273              : 
    2274              :         // Second part: unoffload timeline (if needed)
    2275            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2276            0 :             timeline
    2277              :         } else {
    2278              :             // Turn offloaded timeline into a non-offloaded one
    2279            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2280            0 :                 .await?
    2281              :         };
    2282              : 
    2283              :         // Third part: upload new timeline archival state and block until it is present in S3
    2284            0 :         let upload_needed = match timeline
    2285            0 :             .remote_client
    2286            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2287              :         {
    2288            0 :             Ok(upload_needed) => upload_needed,
    2289            0 :             Err(e) => {
    2290            0 :                 if timeline.cancel.is_cancelled() {
    2291            0 :                     return Err(TimelineArchivalError::Cancelled);
    2292              :                 } else {
    2293            0 :                     return Err(TimelineArchivalError::Other(e));
    2294              :                 }
    2295              :             }
    2296              :         };
    2297              : 
    2298            0 :         if upload_needed {
    2299            0 :             info!("Uploading new state");
    2300              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2301            0 :             let Ok(v) =
    2302            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2303              :             else {
    2304            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2305            0 :                 return Err(TimelineArchivalError::Timeout);
    2306              :             };
    2307            0 :             v.map_err(|e| match e {
    2308            0 :                 WaitCompletionError::NotInitialized(e) => {
    2309            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2310              :                 }
    2311              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2312            0 :                     TimelineArchivalError::Cancelled
    2313              :                 }
    2314            0 :             })?;
    2315            0 :         }
    2316            0 :         Ok(())
    2317            0 :     }
    2318              : 
    2319            4 :     pub fn get_offloaded_timeline(
    2320            4 :         &self,
    2321            4 :         timeline_id: TimelineId,
    2322            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2323            4 :         self.timelines_offloaded
    2324            4 :             .lock()
    2325            4 :             .unwrap()
    2326            4 :             .get(&timeline_id)
    2327            4 :             .map(Arc::clone)
    2328            4 :             .ok_or(GetTimelineError::NotFound {
    2329            4 :                 tenant_id: self.tenant_shard_id,
    2330            4 :                 timeline_id,
    2331            4 :             })
    2332            4 :     }
    2333              : 
    2334            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2335            8 :         self.tenant_shard_id
    2336            8 :     }
    2337              : 
    2338              :     /// Get Timeline handle for given Neon timeline ID.
    2339              :     /// This function is idempotent. It doesn't change internal state in any way.
    2340          444 :     pub fn get_timeline(
    2341          444 :         &self,
    2342          444 :         timeline_id: TimelineId,
    2343          444 :         active_only: bool,
    2344          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2345          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2346          444 :         let timeline = timelines_accessor
    2347          444 :             .get(&timeline_id)
    2348          444 :             .ok_or(GetTimelineError::NotFound {
    2349          444 :                 tenant_id: self.tenant_shard_id,
    2350          444 :                 timeline_id,
    2351          444 :             })?;
    2352              : 
    2353          440 :         if active_only && !timeline.is_active() {
    2354            0 :             Err(GetTimelineError::NotActive {
    2355            0 :                 tenant_id: self.tenant_shard_id,
    2356            0 :                 timeline_id,
    2357            0 :                 state: timeline.current_state(),
    2358            0 :             })
    2359              :         } else {
    2360          440 :             Ok(Arc::clone(timeline))
    2361              :         }
    2362          444 :     }
    2363              : 
    2364              :     /// Lists timelines the tenant contains.
    2365              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2366            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2367            0 :         self.timelines
    2368            0 :             .lock()
    2369            0 :             .unwrap()
    2370            0 :             .values()
    2371            0 :             .map(Arc::clone)
    2372            0 :             .collect()
    2373            0 :     }
    2374              : 
    2375              :     /// Lists timelines the tenant manages, including offloaded ones.
    2376              :     ///
    2377              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2378            0 :     pub fn list_timelines_and_offloaded(
    2379            0 :         &self,
    2380            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2381            0 :         let timelines = self
    2382            0 :             .timelines
    2383            0 :             .lock()
    2384            0 :             .unwrap()
    2385            0 :             .values()
    2386            0 :             .map(Arc::clone)
    2387            0 :             .collect();
    2388            0 :         let offloaded = self
    2389            0 :             .timelines_offloaded
    2390            0 :             .lock()
    2391            0 :             .unwrap()
    2392            0 :             .values()
    2393            0 :             .map(Arc::clone)
    2394            0 :             .collect();
    2395            0 :         (timelines, offloaded)
    2396            0 :     }
    2397              : 
    2398            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2399            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2400            0 :     }
    2401              : 
    2402              :     /// This is used by tests & import-from-basebackup.
    2403              :     ///
    2404              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2405              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2406              :     ///
    2407              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2408              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2409              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2410              :     /// to the [`Tenant::timelines`].
    2411              :     ///
    2412              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2413          428 :     pub(crate) async fn create_empty_timeline(
    2414          428 :         self: &Arc<Self>,
    2415          428 :         new_timeline_id: TimelineId,
    2416          428 :         initdb_lsn: Lsn,
    2417          428 :         pg_version: u32,
    2418          428 :         _ctx: &RequestContext,
    2419          428 :     ) -> anyhow::Result<UninitializedTimeline> {
    2420          428 :         anyhow::ensure!(
    2421          428 :             self.is_active(),
    2422            0 :             "Cannot create empty timelines on inactive tenant"
    2423              :         );
    2424              : 
    2425              :         // Protect against concurrent attempts to use this TimelineId
    2426          428 :         let create_guard = match self
    2427          428 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2428          428 :             .await?
    2429              :         {
    2430          424 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2431              :             StartCreatingTimelineResult::Idempotent(_) => {
    2432            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2433              :             }
    2434              :         };
    2435              : 
    2436          424 :         let new_metadata = TimelineMetadata::new(
    2437          424 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2438          424 :             // make it valid, before calling finish_creation()
    2439          424 :             Lsn(0),
    2440          424 :             None,
    2441          424 :             None,
    2442          424 :             Lsn(0),
    2443          424 :             initdb_lsn,
    2444          424 :             initdb_lsn,
    2445          424 :             pg_version,
    2446          424 :         );
    2447          424 :         self.prepare_new_timeline(
    2448          424 :             new_timeline_id,
    2449          424 :             &new_metadata,
    2450          424 :             create_guard,
    2451          424 :             initdb_lsn,
    2452          424 :             None,
    2453          424 :         )
    2454          424 :         .await
    2455          428 :     }
    2456              : 
    2457              :     /// Helper for unit tests to create an empty timeline.
    2458              :     ///
    2459              :     /// The timeline is has state value `Active` but its background loops are not running.
    2460              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2461              :     // Our current tests don't need the background loops.
    2462              :     #[cfg(test)]
    2463          408 :     pub async fn create_test_timeline(
    2464          408 :         self: &Arc<Self>,
    2465          408 :         new_timeline_id: TimelineId,
    2466          408 :         initdb_lsn: Lsn,
    2467          408 :         pg_version: u32,
    2468          408 :         ctx: &RequestContext,
    2469          408 :     ) -> anyhow::Result<Arc<Timeline>> {
    2470          408 :         let uninit_tl = self
    2471          408 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2472          408 :             .await?;
    2473          408 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2474          408 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2475              : 
    2476              :         // Setup minimum keys required for the timeline to be usable.
    2477          408 :         let mut modification = tline.begin_modification(initdb_lsn);
    2478          408 :         modification
    2479          408 :             .init_empty_test_timeline()
    2480          408 :             .context("init_empty_test_timeline")?;
    2481          408 :         modification
    2482          408 :             .commit(ctx)
    2483          408 :             .await
    2484          408 :             .context("commit init_empty_test_timeline modification")?;
    2485              : 
    2486              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2487          408 :         tline.maybe_spawn_flush_loop();
    2488          408 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2489              : 
    2490              :         // Make sure the freeze_and_flush reaches remote storage.
    2491          408 :         tline.remote_client.wait_completion().await.unwrap();
    2492              : 
    2493          408 :         let tl = uninit_tl.finish_creation().await?;
    2494              :         // The non-test code would call tl.activate() here.
    2495          408 :         tl.set_state(TimelineState::Active);
    2496          408 :         Ok(tl)
    2497          408 :     }
    2498              : 
    2499              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2500              :     #[cfg(test)]
    2501              :     #[allow(clippy::too_many_arguments)]
    2502           80 :     pub async fn create_test_timeline_with_layers(
    2503           80 :         self: &Arc<Self>,
    2504           80 :         new_timeline_id: TimelineId,
    2505           80 :         initdb_lsn: Lsn,
    2506           80 :         pg_version: u32,
    2507           80 :         ctx: &RequestContext,
    2508           80 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2509           80 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2510           80 :         end_lsn: Lsn,
    2511           80 :     ) -> anyhow::Result<Arc<Timeline>> {
    2512              :         use checks::check_valid_layermap;
    2513              :         use itertools::Itertools;
    2514              : 
    2515           80 :         let tline = self
    2516           80 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2517           80 :             .await?;
    2518           80 :         tline.force_advance_lsn(end_lsn);
    2519          252 :         for deltas in delta_layer_desc {
    2520          172 :             tline
    2521          172 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2522          172 :                 .await?;
    2523              :         }
    2524          192 :         for (lsn, images) in image_layer_desc {
    2525          112 :             tline
    2526          112 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2527          112 :                 .await?;
    2528              :         }
    2529           80 :         let layer_names = tline
    2530           80 :             .layers
    2531           80 :             .read()
    2532           80 :             .await
    2533           80 :             .layer_map()
    2534           80 :             .unwrap()
    2535           80 :             .iter_historic_layers()
    2536          364 :             .map(|layer| layer.layer_name())
    2537           80 :             .collect_vec();
    2538           80 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2539            0 :             bail!("invalid layermap: {err}");
    2540           80 :         }
    2541           80 :         Ok(tline)
    2542           80 :     }
    2543              : 
    2544              :     /// Create a new timeline.
    2545              :     ///
    2546              :     /// Returns the new timeline ID and reference to its Timeline object.
    2547              :     ///
    2548              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2549              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2550              :     #[allow(clippy::too_many_arguments)]
    2551            0 :     pub(crate) async fn create_timeline(
    2552            0 :         self: &Arc<Tenant>,
    2553            0 :         params: CreateTimelineParams,
    2554            0 :         broker_client: storage_broker::BrokerClientChannel,
    2555            0 :         ctx: &RequestContext,
    2556            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2557            0 :         if !self.is_active() {
    2558            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2559            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2560              :             } else {
    2561            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2562            0 :                     "Cannot create timelines on inactive tenant"
    2563            0 :                 )));
    2564              :             }
    2565            0 :         }
    2566              : 
    2567            0 :         let _gate = self
    2568            0 :             .gate
    2569            0 :             .enter()
    2570            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2571              : 
    2572            0 :         let result: CreateTimelineResult = match params {
    2573              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2574            0 :                 new_timeline_id,
    2575            0 :                 existing_initdb_timeline_id,
    2576            0 :                 pg_version,
    2577            0 :             }) => {
    2578            0 :                 self.bootstrap_timeline(
    2579            0 :                     new_timeline_id,
    2580            0 :                     pg_version,
    2581            0 :                     existing_initdb_timeline_id,
    2582            0 :                     ctx,
    2583            0 :                 )
    2584            0 :                 .await?
    2585              :             }
    2586              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2587            0 :                 new_timeline_id,
    2588            0 :                 ancestor_timeline_id,
    2589            0 :                 mut ancestor_start_lsn,
    2590              :             }) => {
    2591            0 :                 let ancestor_timeline = self
    2592            0 :                     .get_timeline(ancestor_timeline_id, false)
    2593            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2594              : 
    2595              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2596              :                 // ready for other purposes either.
    2597            0 :                 if !ancestor_timeline.is_active() {
    2598            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2599            0 :                 }
    2600            0 : 
    2601            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2602            0 :                     info!("tried to branch archived timeline");
    2603            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2604            0 :                 }
    2605              : 
    2606            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2607            0 :                     *lsn = lsn.align();
    2608            0 : 
    2609            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2610            0 :                     if ancestor_ancestor_lsn > *lsn {
    2611              :                         // can we safely just branch from the ancestor instead?
    2612            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2613            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2614            0 :                             lsn,
    2615            0 :                             ancestor_timeline_id,
    2616            0 :                             ancestor_ancestor_lsn,
    2617            0 :                         )));
    2618            0 :                     }
    2619            0 : 
    2620            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2621            0 :                     // to the requested branch point. The repository code itself doesn't
    2622            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2623            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2624            0 :                     // sizes etc. and that would get confused if the previous page versions
    2625            0 :                     // are not in the repository yet.
    2626            0 :                     ancestor_timeline
    2627            0 :                         .wait_lsn(
    2628            0 :                             *lsn,
    2629            0 :                             timeline::WaitLsnWaiter::Tenant,
    2630            0 :                             timeline::WaitLsnTimeout::Default,
    2631            0 :                             ctx,
    2632            0 :                         )
    2633            0 :                         .await
    2634            0 :                         .map_err(|e| match e {
    2635            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2636            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2637              :                             }
    2638            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2639            0 :                         })?;
    2640            0 :                 }
    2641              : 
    2642            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2643            0 :                     .await?
    2644              :             }
    2645            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2646            0 :                 self.create_timeline_import_pgdata(
    2647            0 :                     params,
    2648            0 :                     ActivateTimelineArgs::Yes {
    2649            0 :                         broker_client: broker_client.clone(),
    2650            0 :                     },
    2651            0 :                     ctx,
    2652            0 :                 )
    2653            0 :                 .await?
    2654              :             }
    2655              :         };
    2656              : 
    2657              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2658              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2659              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2660              :         //
    2661              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2662              :         // assume that, because they can see the timeline via API, that the creation is done and
    2663              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2664              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2665              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2666              :         //
    2667              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2668              :         // creation API until it returns success. Only then is durability guaranteed.
    2669            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2670            0 :         result
    2671            0 :             .timeline()
    2672            0 :             .remote_client
    2673            0 :             .wait_completion()
    2674            0 :             .await
    2675            0 :             .map_err(|e| match e {
    2676              :                 WaitCompletionError::NotInitialized(
    2677            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2678            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2679              :                 WaitCompletionError::NotInitialized(_) => {
    2680              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2681            0 :                     debug_assert!(false);
    2682            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2683              :                 }
    2684              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2685            0 :                     CreateTimelineError::ShuttingDown
    2686              :                 }
    2687            0 :             })?;
    2688              : 
    2689              :         // The creating task is responsible for activating the timeline.
    2690              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2691              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2692            0 :         let activated_timeline = match result {
    2693            0 :             CreateTimelineResult::Created(timeline) => {
    2694            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2695            0 :                 timeline
    2696              :             }
    2697            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2698            0 :                 info!(
    2699            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2700              :                 );
    2701            0 :                 timeline
    2702              :             }
    2703            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2704            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2705            0 :                 timeline
    2706              :             }
    2707              :         };
    2708              : 
    2709            0 :         Ok(activated_timeline)
    2710            0 :     }
    2711              : 
    2712              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2713              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2714              :     /// [`Tenant::timelines`] map when the import completes.
    2715              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2716              :     /// for the response.
    2717            0 :     async fn create_timeline_import_pgdata(
    2718            0 :         self: &Arc<Tenant>,
    2719            0 :         params: CreateTimelineParamsImportPgdata,
    2720            0 :         activate: ActivateTimelineArgs,
    2721            0 :         ctx: &RequestContext,
    2722            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2723            0 :         let CreateTimelineParamsImportPgdata {
    2724            0 :             new_timeline_id,
    2725            0 :             location,
    2726            0 :             idempotency_key,
    2727            0 :         } = params;
    2728            0 : 
    2729            0 :         let started_at = chrono::Utc::now().naive_utc();
    2730              : 
    2731              :         //
    2732              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2733              :         // is the canonical way we do it.
    2734              :         // - create an empty timeline in-memory
    2735              :         // - use its remote_timeline_client to do the upload
    2736              :         // - dispose of the uninit timeline
    2737              :         // - keep the creation guard alive
    2738              : 
    2739            0 :         let timeline_create_guard = match self
    2740            0 :             .start_creating_timeline(
    2741            0 :                 new_timeline_id,
    2742            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2743            0 :                     idempotency_key: idempotency_key.clone(),
    2744            0 :                 }),
    2745            0 :             )
    2746            0 :             .await?
    2747              :         {
    2748            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2749            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2750            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2751              :             }
    2752              :         };
    2753              : 
    2754            0 :         let mut uninit_timeline = {
    2755            0 :             let this = &self;
    2756            0 :             let initdb_lsn = Lsn(0);
    2757            0 :             let _ctx = ctx;
    2758            0 :             async move {
    2759            0 :                 let new_metadata = TimelineMetadata::new(
    2760            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2761            0 :                     // make it valid, before calling finish_creation()
    2762            0 :                     Lsn(0),
    2763            0 :                     None,
    2764            0 :                     None,
    2765            0 :                     Lsn(0),
    2766            0 :                     initdb_lsn,
    2767            0 :                     initdb_lsn,
    2768            0 :                     15,
    2769            0 :                 );
    2770            0 :                 this.prepare_new_timeline(
    2771            0 :                     new_timeline_id,
    2772            0 :                     &new_metadata,
    2773            0 :                     timeline_create_guard,
    2774            0 :                     initdb_lsn,
    2775            0 :                     None,
    2776            0 :                 )
    2777            0 :                 .await
    2778            0 :             }
    2779            0 :         }
    2780            0 :         .await?;
    2781              : 
    2782            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2783            0 :             idempotency_key,
    2784            0 :             location,
    2785            0 :             started_at,
    2786            0 :         };
    2787            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2788            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2789            0 :         );
    2790            0 :         uninit_timeline
    2791            0 :             .raw_timeline()
    2792            0 :             .unwrap()
    2793            0 :             .remote_client
    2794            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2795              : 
    2796              :         // wait_completion happens in caller
    2797              : 
    2798            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2799            0 : 
    2800            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2801            0 :             timeline.clone(),
    2802            0 :             index_part,
    2803            0 :             activate,
    2804            0 :             timeline_create_guard,
    2805            0 :         ));
    2806            0 : 
    2807            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2808            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2809            0 :     }
    2810              : 
    2811              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
    2812              :     async fn create_timeline_import_pgdata_task(
    2813              :         self: Arc<Tenant>,
    2814              :         timeline: Arc<Timeline>,
    2815              :         index_part: import_pgdata::index_part_format::Root,
    2816              :         activate: ActivateTimelineArgs,
    2817              :         timeline_create_guard: TimelineCreateGuard,
    2818              :     ) {
    2819              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2820              :         info!("starting");
    2821              :         scopeguard::defer! {info!("exiting")};
    2822              : 
    2823              :         let res = self
    2824              :             .create_timeline_import_pgdata_task_impl(
    2825              :                 timeline,
    2826              :                 index_part,
    2827              :                 activate,
    2828              :                 timeline_create_guard,
    2829              :             )
    2830              :             .await;
    2831              :         if let Err(err) = &res {
    2832              :             error!(?err, "task failed");
    2833              :             // TODO sleep & retry, sensitive to tenant shutdown
    2834              :             // TODO: allow timeline deletion requests => should cancel the task
    2835              :         }
    2836              :     }
    2837              : 
    2838            0 :     async fn create_timeline_import_pgdata_task_impl(
    2839            0 :         self: Arc<Tenant>,
    2840            0 :         timeline: Arc<Timeline>,
    2841            0 :         index_part: import_pgdata::index_part_format::Root,
    2842            0 :         activate: ActivateTimelineArgs,
    2843            0 :         timeline_create_guard: TimelineCreateGuard,
    2844            0 :     ) -> Result<(), anyhow::Error> {
    2845            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2846            0 : 
    2847            0 :         info!("importing pgdata");
    2848            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2849            0 :             .await
    2850            0 :             .context("import")?;
    2851            0 :         info!("import done");
    2852              : 
    2853              :         //
    2854              :         // Reload timeline from remote.
    2855              :         // This proves that the remote state is attachable, and it reuses the code.
    2856              :         //
    2857              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2858              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2859              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2860              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2861              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2862              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2863              :         // to manifest because of the long runtime of this import task.
    2864              : 
    2865              :         //        in theory this shouldn't even .await anything except for coop yield
    2866            0 :         info!("shutting down timeline");
    2867            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2868            0 :         info!("timeline shut down, reloading from remote");
    2869              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2870              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2871              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2872              :         // };
    2873            0 :         let timeline_id = timeline.timeline_id;
    2874            0 : 
    2875            0 :         // load from object storage like Tenant::attach does
    2876            0 :         let resources = self.build_timeline_resources(timeline_id);
    2877            0 :         let index_part = resources
    2878            0 :             .remote_client
    2879            0 :             .download_index_file(&self.cancel)
    2880            0 :             .await?;
    2881            0 :         let index_part = match index_part {
    2882              :             MaybeDeletedIndexPart::Deleted(_) => {
    2883              :                 // likely concurrent delete call, cplane should prevent this
    2884            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2885              :             }
    2886            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2887            0 :         };
    2888            0 :         let metadata = index_part.metadata.clone();
    2889            0 :         self
    2890            0 :             .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
    2891            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2892            0 :             .await?
    2893            0 :             .ready_to_activate()
    2894            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2895              : 
    2896            0 :         anyhow::Ok(())
    2897            0 :     }
    2898              : 
    2899            0 :     pub(crate) async fn delete_timeline(
    2900            0 :         self: Arc<Self>,
    2901            0 :         timeline_id: TimelineId,
    2902            0 :     ) -> Result<(), DeleteTimelineError> {
    2903            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2904              : 
    2905            0 :         Ok(())
    2906            0 :     }
    2907              : 
    2908              :     /// perform one garbage collection iteration, removing old data files from disk.
    2909              :     /// this function is periodically called by gc task.
    2910              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2911              :     ///
    2912              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2913              :     ///
    2914              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2915              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2916              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2917              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2918              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2919              :     /// requires more history to be retained.
    2920              :     //
    2921         1508 :     pub(crate) async fn gc_iteration(
    2922         1508 :         &self,
    2923         1508 :         target_timeline_id: Option<TimelineId>,
    2924         1508 :         horizon: u64,
    2925         1508 :         pitr: Duration,
    2926         1508 :         cancel: &CancellationToken,
    2927         1508 :         ctx: &RequestContext,
    2928         1508 :     ) -> Result<GcResult, GcError> {
    2929         1508 :         // Don't start doing work during shutdown
    2930         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2931            0 :             return Ok(GcResult::default());
    2932         1508 :         }
    2933         1508 : 
    2934         1508 :         // there is a global allowed_error for this
    2935         1508 :         if !self.is_active() {
    2936            0 :             return Err(GcError::NotActive);
    2937         1508 :         }
    2938         1508 : 
    2939         1508 :         {
    2940         1508 :             let conf = self.tenant_conf.load();
    2941         1508 : 
    2942         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2943         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2944         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2945         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2946         1508 :             if !conf.location.may_delete_layers_hint() {
    2947            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2948            0 :                 return Ok(GcResult::default());
    2949         1508 :             }
    2950         1508 : 
    2951         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2952         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2953         1500 :                 return Ok(GcResult::default());
    2954            8 :             }
    2955              :         }
    2956              : 
    2957            8 :         let _guard = match self.gc_block.start().await {
    2958            8 :             Ok(guard) => guard,
    2959            0 :             Err(reasons) => {
    2960            0 :                 info!("Skipping GC: {reasons}");
    2961            0 :                 return Ok(GcResult::default());
    2962              :             }
    2963              :         };
    2964              : 
    2965            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2966            8 :             .await
    2967         1508 :     }
    2968              : 
    2969              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    2970              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    2971              :     /// immediate L0 compaction.
    2972              :     ///
    2973              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    2974            0 :     async fn compaction_iteration(
    2975            0 :         self: &Arc<Self>,
    2976            0 :         cancel: &CancellationToken,
    2977            0 :         ctx: &RequestContext,
    2978            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    2979            0 :         // Don't compact inactive tenants.
    2980            0 :         if !self.is_active() {
    2981            0 :             return Ok(CompactionOutcome::Skipped);
    2982            0 :         }
    2983            0 : 
    2984            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    2985            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    2986            0 :         let location = self.tenant_conf.load().location;
    2987            0 :         if !location.may_upload_layers_hint() {
    2988            0 :             info!("skipping compaction in location state {location:?}");
    2989            0 :             return Ok(CompactionOutcome::Skipped);
    2990            0 :         }
    2991            0 : 
    2992            0 :         // Don't compact if the circuit breaker is tripped.
    2993            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2994            0 :             info!("skipping compaction due to previous failures");
    2995            0 :             return Ok(CompactionOutcome::Skipped);
    2996            0 :         }
    2997            0 : 
    2998            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    2999            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3000            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3001            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3002            0 : 
    3003            0 :         {
    3004            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3005            0 :             let timelines = self.timelines.lock().unwrap();
    3006            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3007              :                 // Skip inactive timelines.
    3008            0 :                 if !timeline.is_active() {
    3009            0 :                     continue;
    3010            0 :                 }
    3011            0 : 
    3012            0 :                 // Schedule the timeline for compaction.
    3013            0 :                 compact.push(timeline.clone());
    3014              : 
    3015              :                 // Schedule the timeline for offloading if eligible.
    3016            0 :                 let can_offload = offload_enabled
    3017            0 :                     && timeline.can_offload().0
    3018            0 :                     && !timelines
    3019            0 :                         .iter()
    3020            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3021            0 :                 if can_offload {
    3022            0 :                     offload.insert(timeline_id);
    3023            0 :                 }
    3024              :             }
    3025              :         } // release timelines lock
    3026              : 
    3027            0 :         for timeline in &compact {
    3028              :             // Collect L0 counts. Can't await while holding lock above.
    3029            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3030            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3031            0 :             }
    3032              :         }
    3033              : 
    3034              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3035              :         // bound read amplification.
    3036              :         //
    3037              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3038              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3039              :         // splitting L0 and image/GC compaction to separate background jobs.
    3040            0 :         if self.get_compaction_l0_first() {
    3041            0 :             let compaction_threshold = self.get_compaction_threshold();
    3042            0 :             let compact_l0 = compact
    3043            0 :                 .iter()
    3044            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3045            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3046            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3047            0 :                 .rev()
    3048            0 :                 .map(|(tli, _)| tli.clone())
    3049            0 :                 .collect_vec();
    3050            0 : 
    3051            0 :             let mut has_pending_l0 = false;
    3052            0 :             for timeline in compact_l0 {
    3053            0 :                 let outcome = timeline
    3054            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3055            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3056            0 :                     .await
    3057            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3058            0 :                 match outcome {
    3059            0 :                     CompactionOutcome::Done => {}
    3060            0 :                     CompactionOutcome::Skipped => {}
    3061            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3062            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3063              :                 }
    3064              :             }
    3065            0 :             if has_pending_l0 {
    3066            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3067            0 :             }
    3068            0 :         }
    3069              : 
    3070              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
    3071              :         // more L0 layers, they may also be compacted here.
    3072              :         //
    3073              :         // NB: image compaction may yield if there is pending L0 compaction.
    3074              :         //
    3075              :         // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
    3076              :         // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
    3077              :         // We leave this for a later PR.
    3078              :         //
    3079              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3080              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3081            0 :         let mut has_pending = false;
    3082            0 :         for timeline in compact {
    3083            0 :             if !timeline.is_active() {
    3084            0 :                 continue;
    3085            0 :             }
    3086              : 
    3087            0 :             let mut outcome = timeline
    3088            0 :                 .compact(cancel, EnumSet::default(), ctx)
    3089            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3090            0 :                 .await
    3091            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3092              : 
    3093              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3094            0 :             if outcome == CompactionOutcome::Done {
    3095            0 :                 let queue = self
    3096            0 :                     .scheduled_compaction_tasks
    3097            0 :                     .lock()
    3098            0 :                     .unwrap()
    3099            0 :                     .get(&timeline.timeline_id)
    3100            0 :                     .cloned();
    3101            0 :                 if let Some(queue) = queue {
    3102            0 :                     outcome = queue
    3103            0 :                         .iteration(cancel, ctx, &self.gc_block, &timeline)
    3104            0 :                         .instrument(
    3105            0 :                             info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3106              :                         )
    3107            0 :                         .await?;
    3108            0 :                 }
    3109            0 :             }
    3110              : 
    3111              :             // If we're done compacting, offload the timeline if requested.
    3112            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3113            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3114            0 :                 offload_timeline(self, &timeline)
    3115            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3116            0 :                     .await
    3117            0 :                     .or_else(|err| match err {
    3118              :                         // Ignore this, we likely raced with unarchival.
    3119            0 :                         OffloadError::NotArchived => Ok(()),
    3120            0 :                         err => Err(err),
    3121            0 :                     })?;
    3122            0 :             }
    3123              : 
    3124            0 :             match outcome {
    3125            0 :                 CompactionOutcome::Done => {}
    3126            0 :                 CompactionOutcome::Skipped => {}
    3127            0 :                 CompactionOutcome::Pending => has_pending = true,
    3128              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3129              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3130            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3131              :             }
    3132              :         }
    3133              : 
    3134              :         // Success! Untrip the breaker if necessary.
    3135            0 :         self.compaction_circuit_breaker
    3136            0 :             .lock()
    3137            0 :             .unwrap()
    3138            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3139            0 : 
    3140            0 :         match has_pending {
    3141            0 :             true => Ok(CompactionOutcome::Pending),
    3142            0 :             false => Ok(CompactionOutcome::Done),
    3143              :         }
    3144            0 :     }
    3145              : 
    3146              :     /// Trips the compaction circuit breaker if appropriate.
    3147            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3148            0 :         match err {
    3149            0 :             CompactionError::ShuttingDown => (),
    3150              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3151              :             // shouldn't block compaction.
    3152            0 :             CompactionError::Offload(_) => {}
    3153            0 :             CompactionError::CollectKeySpaceError(err) => {
    3154            0 :                 self.compaction_circuit_breaker
    3155            0 :                     .lock()
    3156            0 :                     .unwrap()
    3157            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3158            0 :             }
    3159            0 :             CompactionError::Other(err) => {
    3160            0 :                 self.compaction_circuit_breaker
    3161            0 :                     .lock()
    3162            0 :                     .unwrap()
    3163            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3164            0 :             }
    3165              :         }
    3166            0 :     }
    3167              : 
    3168              :     /// Cancel scheduled compaction tasks
    3169            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3170            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3171            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3172            0 :             q.cancel_scheduled();
    3173            0 :         }
    3174            0 :     }
    3175              : 
    3176            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3177            0 :         &self,
    3178            0 :         timeline_id: TimelineId,
    3179            0 :     ) -> Vec<CompactInfoResponse> {
    3180            0 :         let res = {
    3181            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3182            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3183              :         };
    3184            0 :         let Some((running, remaining)) = res else {
    3185            0 :             return Vec::new();
    3186              :         };
    3187            0 :         let mut result = Vec::new();
    3188            0 :         if let Some((id, running)) = running {
    3189            0 :             result.extend(running.into_compact_info_resp(id, true));
    3190            0 :         }
    3191            0 :         for (id, job) in remaining {
    3192            0 :             result.extend(job.into_compact_info_resp(id, false));
    3193            0 :         }
    3194            0 :         result
    3195            0 :     }
    3196              : 
    3197              :     /// Schedule a compaction task for a timeline.
    3198            0 :     pub(crate) async fn schedule_compaction(
    3199            0 :         &self,
    3200            0 :         timeline_id: TimelineId,
    3201            0 :         options: CompactOptions,
    3202            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3203            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3204            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3205            0 :         let q = guard
    3206            0 :             .entry(timeline_id)
    3207            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3208            0 :         q.schedule_manual_compaction(options, Some(tx));
    3209            0 :         Ok(rx)
    3210            0 :     }
    3211              : 
    3212              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3213            0 :     async fn housekeeping(&self) {
    3214            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3215            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3216            0 :         let timelines = self
    3217            0 :             .timelines
    3218            0 :             .lock()
    3219            0 :             .unwrap()
    3220            0 :             .values()
    3221            0 :             .filter(|tli| tli.is_active())
    3222            0 :             .cloned()
    3223            0 :             .collect_vec();
    3224              : 
    3225            0 :         for timeline in timelines {
    3226            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3227              :         }
    3228              : 
    3229              :         // Shut down walredo if idle.
    3230              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3231            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3232            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3233            0 :         }
    3234            0 :     }
    3235              : 
    3236            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3237            0 :         let timelines = self.timelines.lock().unwrap();
    3238            0 :         !timelines
    3239            0 :             .iter()
    3240            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3241            0 :     }
    3242              : 
    3243         3468 :     pub fn current_state(&self) -> TenantState {
    3244         3468 :         self.state.borrow().clone()
    3245         3468 :     }
    3246              : 
    3247         1944 :     pub fn is_active(&self) -> bool {
    3248         1944 :         self.current_state() == TenantState::Active
    3249         1944 :     }
    3250              : 
    3251            0 :     pub fn generation(&self) -> Generation {
    3252            0 :         self.generation
    3253            0 :     }
    3254              : 
    3255            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3256            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3257            0 :     }
    3258              : 
    3259              :     /// Changes tenant status to active, unless shutdown was already requested.
    3260              :     ///
    3261              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3262              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3263            0 :     fn activate(
    3264            0 :         self: &Arc<Self>,
    3265            0 :         broker_client: BrokerClientChannel,
    3266            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3267            0 :         ctx: &RequestContext,
    3268            0 :     ) {
    3269            0 :         span::debug_assert_current_span_has_tenant_id();
    3270            0 : 
    3271            0 :         let mut activating = false;
    3272            0 :         self.state.send_modify(|current_state| {
    3273              :             use pageserver_api::models::ActivatingFrom;
    3274            0 :             match &*current_state {
    3275              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3276            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3277              :                 }
    3278            0 :                 TenantState::Attaching => {
    3279            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3280            0 :                 }
    3281            0 :             }
    3282            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3283            0 :             activating = true;
    3284            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3285            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3286            0 :         });
    3287            0 : 
    3288            0 :         if activating {
    3289            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3290            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3291            0 :             let timelines_to_activate = timelines_accessor
    3292            0 :                 .values()
    3293            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3294            0 : 
    3295            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3296            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3297            0 : 
    3298            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3299            0 :             // down when they notice that the tenant is inactive.
    3300            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3301            0 : 
    3302            0 :             let mut activated_timelines = 0;
    3303              : 
    3304            0 :             for timeline in timelines_to_activate {
    3305            0 :                 timeline.activate(
    3306            0 :                     self.clone(),
    3307            0 :                     broker_client.clone(),
    3308            0 :                     background_jobs_can_start,
    3309            0 :                     ctx,
    3310            0 :                 );
    3311            0 :                 activated_timelines += 1;
    3312            0 :             }
    3313              : 
    3314            0 :             self.state.send_modify(move |current_state| {
    3315            0 :                 assert!(
    3316            0 :                     matches!(current_state, TenantState::Activating(_)),
    3317            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3318              :                 );
    3319            0 :                 *current_state = TenantState::Active;
    3320            0 : 
    3321            0 :                 let elapsed = self.constructed_at.elapsed();
    3322            0 :                 let total_timelines = timelines_accessor.len();
    3323            0 : 
    3324            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3325            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3326            0 :                 info!(
    3327            0 :                     since_creation_millis = elapsed.as_millis(),
    3328            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3329            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3330            0 :                     activated_timelines,
    3331            0 :                     total_timelines,
    3332            0 :                     post_state = <&'static str>::from(&*current_state),
    3333            0 :                     "activation attempt finished"
    3334              :                 );
    3335              : 
    3336            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3337            0 :             });
    3338            0 :         }
    3339            0 :     }
    3340              : 
    3341              :     /// Shutdown the tenant and join all of the spawned tasks.
    3342              :     ///
    3343              :     /// The method caters for all use-cases:
    3344              :     /// - pageserver shutdown (freeze_and_flush == true)
    3345              :     /// - detach + ignore (freeze_and_flush == false)
    3346              :     ///
    3347              :     /// This will attempt to shutdown even if tenant is broken.
    3348              :     ///
    3349              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3350              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3351              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3352              :     /// the ongoing shutdown.
    3353           12 :     async fn shutdown(
    3354           12 :         &self,
    3355           12 :         shutdown_progress: completion::Barrier,
    3356           12 :         shutdown_mode: timeline::ShutdownMode,
    3357           12 :     ) -> Result<(), completion::Barrier> {
    3358           12 :         span::debug_assert_current_span_has_tenant_id();
    3359              : 
    3360              :         // Set tenant (and its timlines) to Stoppping state.
    3361              :         //
    3362              :         // Since we can only transition into Stopping state after activation is complete,
    3363              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3364              :         //
    3365              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3366              :         // 1. Lock out any new requests to the tenants.
    3367              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3368              :         // 3. Signal cancellation for other tenant background loops.
    3369              :         // 4. ???
    3370              :         //
    3371              :         // The waiting for the cancellation is not done uniformly.
    3372              :         // We certainly wait for WAL receivers to shut down.
    3373              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3374              :         // But the tenant background loops are joined-on in our caller.
    3375              :         // It's mesed up.
    3376              :         // we just ignore the failure to stop
    3377              : 
    3378              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3379              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3380              :         // is very slow.
    3381           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3382            0 :             self.cancel.cancel();
    3383            0 : 
    3384            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3385            0 :             // are children of ours, so their flush loops will have shut down already
    3386            0 :             timeline::ShutdownMode::Hard
    3387              :         } else {
    3388           12 :             shutdown_mode
    3389              :         };
    3390              : 
    3391           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3392           12 :             Ok(()) => {}
    3393            0 :             Err(SetStoppingError::Broken) => {
    3394            0 :                 // assume that this is acceptable
    3395            0 :             }
    3396            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3397            0 :                 // give caller the option to wait for this this shutdown
    3398            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3399            0 :                 return Err(other);
    3400              :             }
    3401              :         };
    3402              : 
    3403           12 :         let mut js = tokio::task::JoinSet::new();
    3404           12 :         {
    3405           12 :             let timelines = self.timelines.lock().unwrap();
    3406           12 :             timelines.values().for_each(|timeline| {
    3407           12 :                 let timeline = Arc::clone(timeline);
    3408           12 :                 let timeline_id = timeline.timeline_id;
    3409           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3410           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3411           12 :             });
    3412           12 :         }
    3413           12 :         {
    3414           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3415           12 :             timelines_offloaded.values().for_each(|timeline| {
    3416            0 :                 timeline.defuse_for_tenant_drop();
    3417           12 :             });
    3418           12 :         }
    3419           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3420           12 :         tracing::info!("Waiting for timelines...");
    3421           24 :         while let Some(res) = js.join_next().await {
    3422            0 :             match res {
    3423           12 :                 Ok(()) => {}
    3424            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3425            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3426            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3427              :             }
    3428              :         }
    3429              : 
    3430           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3431            0 :             tracing::info!("Flushing deletion queue");
    3432            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3433            0 :                 match e {
    3434            0 :                     DeletionQueueError::ShuttingDown => {
    3435            0 :                         // This is the only error we expect for now. In the future, if more error
    3436            0 :                         // variants are added, we should handle them here.
    3437            0 :                     }
    3438              :                 }
    3439            0 :             }
    3440           12 :         }
    3441              : 
    3442              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3443              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3444           12 :         tracing::debug!("Cancelling CancellationToken");
    3445           12 :         self.cancel.cancel();
    3446           12 : 
    3447           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3448           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3449           12 :         //
    3450           12 :         // this will additionally shutdown and await all timeline tasks.
    3451           12 :         tracing::debug!("Waiting for tasks...");
    3452           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3453              : 
    3454           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3455           12 :             walredo_mgr.shutdown().await;
    3456            0 :         }
    3457              : 
    3458              :         // Wait for any in-flight operations to complete
    3459           12 :         self.gate.close().await;
    3460              : 
    3461           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3462           12 : 
    3463           12 :         Ok(())
    3464           12 :     }
    3465              : 
    3466              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3467              :     ///
    3468              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3469              :     ///
    3470              :     /// This function is not cancel-safe!
    3471              :     ///
    3472              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3473              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3474           12 :     async fn set_stopping(
    3475           12 :         &self,
    3476           12 :         progress: completion::Barrier,
    3477           12 :         _allow_transition_from_loading: bool,
    3478           12 :         allow_transition_from_attaching: bool,
    3479           12 :     ) -> Result<(), SetStoppingError> {
    3480           12 :         let mut rx = self.state.subscribe();
    3481           12 : 
    3482           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3483           12 :         rx.wait_for(|state| match state {
    3484            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3485              :             TenantState::Activating(_) | TenantState::Attaching => {
    3486            0 :                 info!(
    3487            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3488            0 :                     <&'static str>::from(state)
    3489              :                 );
    3490            0 :                 false
    3491              :             }
    3492           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3493           12 :         })
    3494           12 :         .await
    3495           12 :         .expect("cannot drop self.state while on a &self method");
    3496           12 : 
    3497           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3498           12 :         let mut err = None;
    3499           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3500              :             TenantState::Activating(_) => {
    3501            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3502              :             }
    3503              :             TenantState::Attaching => {
    3504            0 :                 if !allow_transition_from_attaching {
    3505            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3506            0 :                 };
    3507            0 :                 *current_state = TenantState::Stopping { progress };
    3508            0 :                 true
    3509              :             }
    3510              :             TenantState::Active => {
    3511              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3512              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3513              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3514           12 :                 *current_state = TenantState::Stopping { progress };
    3515           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3516           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3517           12 :                 true
    3518              :             }
    3519            0 :             TenantState::Broken { reason, .. } => {
    3520            0 :                 info!(
    3521            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3522              :                 );
    3523            0 :                 err = Some(SetStoppingError::Broken);
    3524            0 :                 false
    3525              :             }
    3526            0 :             TenantState::Stopping { progress } => {
    3527            0 :                 info!("Tenant is already in Stopping state");
    3528            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3529            0 :                 false
    3530              :             }
    3531           12 :         });
    3532           12 :         match (stopping, err) {
    3533           12 :             (true, None) => {} // continue
    3534            0 :             (false, Some(err)) => return Err(err),
    3535            0 :             (true, Some(_)) => unreachable!(
    3536            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3537            0 :             ),
    3538            0 :             (false, None) => unreachable!(
    3539            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3540            0 :             ),
    3541              :         }
    3542              : 
    3543           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3544           12 :         let not_broken_timelines = timelines_accessor
    3545           12 :             .values()
    3546           12 :             .filter(|timeline| !timeline.is_broken());
    3547           24 :         for timeline in not_broken_timelines {
    3548           12 :             timeline.set_state(TimelineState::Stopping);
    3549           12 :         }
    3550           12 :         Ok(())
    3551           12 :     }
    3552              : 
    3553              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3554              :     /// `remove_tenant_from_memory`
    3555              :     ///
    3556              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3557              :     ///
    3558              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3559            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3560            0 :         let mut rx = self.state.subscribe();
    3561            0 : 
    3562            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3563            0 :         // So, wait until it's done.
    3564            0 :         rx.wait_for(|state| match state {
    3565              :             TenantState::Activating(_) | TenantState::Attaching => {
    3566            0 :                 info!(
    3567            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3568            0 :                     <&'static str>::from(state)
    3569              :                 );
    3570            0 :                 false
    3571              :             }
    3572            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3573            0 :         })
    3574            0 :         .await
    3575            0 :         .expect("cannot drop self.state while on a &self method");
    3576            0 : 
    3577            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3578            0 :         self.set_broken_no_wait(reason)
    3579            0 :     }
    3580              : 
    3581            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3582            0 :         let reason = reason.to_string();
    3583            0 :         self.state.send_modify(|current_state| {
    3584            0 :             match *current_state {
    3585              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3586            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3587              :                 }
    3588              :                 TenantState::Active => {
    3589            0 :                     if cfg!(feature = "testing") {
    3590            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3591            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3592              :                     } else {
    3593            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3594              :                     }
    3595              :                 }
    3596              :                 TenantState::Broken { .. } => {
    3597            0 :                     warn!("Tenant is already in Broken state");
    3598              :                 }
    3599              :                 // This is the only "expected" path, any other path is a bug.
    3600              :                 TenantState::Stopping { .. } => {
    3601            0 :                     warn!(
    3602            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3603              :                         reason
    3604              :                     );
    3605            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3606              :                 }
    3607              :            }
    3608            0 :         });
    3609            0 :     }
    3610              : 
    3611            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3612            0 :         self.state.subscribe()
    3613            0 :     }
    3614              : 
    3615              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3616              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3617            0 :     pub(crate) fn activate_now(&self) {
    3618            0 :         self.activate_now_sem.add_permits(1);
    3619            0 :     }
    3620              : 
    3621            0 :     pub(crate) async fn wait_to_become_active(
    3622            0 :         &self,
    3623            0 :         timeout: Duration,
    3624            0 :     ) -> Result<(), GetActiveTenantError> {
    3625            0 :         let mut receiver = self.state.subscribe();
    3626              :         loop {
    3627            0 :             let current_state = receiver.borrow_and_update().clone();
    3628            0 :             match current_state {
    3629              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3630              :                     // in these states, there's a chance that we can reach ::Active
    3631            0 :                     self.activate_now();
    3632            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3633            0 :                         Ok(r) => {
    3634            0 :                             r.map_err(
    3635            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3636              :                                 // Tenant existed but was dropped: report it as non-existent
    3637            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3638            0 :                         )?
    3639              :                         }
    3640              :                         Err(TimeoutCancellableError::Cancelled) => {
    3641            0 :                             return Err(GetActiveTenantError::Cancelled);
    3642              :                         }
    3643              :                         Err(TimeoutCancellableError::Timeout) => {
    3644            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3645            0 :                                 latest_state: Some(self.current_state()),
    3646            0 :                                 wait_time: timeout,
    3647            0 :                             });
    3648              :                         }
    3649              :                     }
    3650              :                 }
    3651              :                 TenantState::Active { .. } => {
    3652            0 :                     return Ok(());
    3653              :                 }
    3654            0 :                 TenantState::Broken { reason, .. } => {
    3655            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3656            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3657            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3658              :                 }
    3659              :                 TenantState::Stopping { .. } => {
    3660              :                     // There's no chance the tenant can transition back into ::Active
    3661            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3662              :                 }
    3663              :             }
    3664              :         }
    3665            0 :     }
    3666              : 
    3667            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3668            0 :         self.tenant_conf.load().location.attach_mode
    3669            0 :     }
    3670              : 
    3671              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3672              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3673              :     /// rare external API calls, like a reconciliation at startup.
    3674            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3675            0 :         let conf = self.tenant_conf.load();
    3676              : 
    3677            0 :         let location_config_mode = match conf.location.attach_mode {
    3678            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3679            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3680            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3681              :         };
    3682              : 
    3683              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3684            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3685            0 : 
    3686            0 :         models::LocationConfig {
    3687            0 :             mode: location_config_mode,
    3688            0 :             generation: self.generation.into(),
    3689            0 :             secondary_conf: None,
    3690            0 :             shard_number: self.shard_identity.number.0,
    3691            0 :             shard_count: self.shard_identity.count.literal(),
    3692            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3693            0 :             tenant_conf: tenant_config,
    3694            0 :         }
    3695            0 :     }
    3696              : 
    3697            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3698            0 :         &self.tenant_shard_id
    3699            0 :     }
    3700              : 
    3701            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3702            0 :         self.shard_identity.stripe_size
    3703            0 :     }
    3704              : 
    3705            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3706            0 :         self.generation
    3707            0 :     }
    3708              : 
    3709              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3710              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3711              :     /// resetting this tenant to a valid state if we fail.
    3712            0 :     pub(crate) async fn split_prepare(
    3713            0 :         &self,
    3714            0 :         child_shards: &Vec<TenantShardId>,
    3715            0 :     ) -> anyhow::Result<()> {
    3716            0 :         let (timelines, offloaded) = {
    3717            0 :             let timelines = self.timelines.lock().unwrap();
    3718            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3719            0 :             (timelines.clone(), offloaded.clone())
    3720            0 :         };
    3721            0 :         let timelines_iter = timelines
    3722            0 :             .values()
    3723            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3724            0 :             .chain(
    3725            0 :                 offloaded
    3726            0 :                     .values()
    3727            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3728            0 :             );
    3729            0 :         for timeline in timelines_iter {
    3730              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3731              :             // to ensure that they do not start a split if currently in the process of doing these.
    3732              : 
    3733            0 :             let timeline_id = timeline.timeline_id();
    3734              : 
    3735            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3736              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3737              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3738              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3739            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3740            0 :                 timeline
    3741            0 :                     .remote_client
    3742            0 :                     .schedule_index_upload_for_file_changes()?;
    3743            0 :                 timeline.remote_client.wait_completion().await?;
    3744            0 :             }
    3745              : 
    3746            0 :             let remote_client = match timeline {
    3747            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3748            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3749            0 :                     let remote_client = self
    3750            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3751            0 :                     Arc::new(remote_client)
    3752              :                 }
    3753              :             };
    3754              : 
    3755              :             // Shut down the timeline's remote client: this means that the indices we write
    3756              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3757            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3758            0 :             remote_client.shutdown().await;
    3759              : 
    3760              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3761              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3762              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3763              :             // we use here really is the remotely persistent one).
    3764            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3765            0 :             let result = remote_client
    3766            0 :                 .download_index_file(&self.cancel)
    3767            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))
    3768            0 :                 .await?;
    3769            0 :             let index_part = match result {
    3770              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3771            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3772              :                 }
    3773            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3774              :             };
    3775              : 
    3776            0 :             for child_shard in child_shards {
    3777            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3778            0 :                 upload_index_part(
    3779            0 :                     &self.remote_storage,
    3780            0 :                     child_shard,
    3781            0 :                     &timeline_id,
    3782            0 :                     self.generation,
    3783            0 :                     &index_part,
    3784            0 :                     &self.cancel,
    3785            0 :                 )
    3786            0 :                 .await?;
    3787              :             }
    3788              :         }
    3789              : 
    3790            0 :         let tenant_manifest = self.build_tenant_manifest();
    3791            0 :         for child_shard in child_shards {
    3792            0 :             tracing::info!(
    3793            0 :                 "Uploading tenant manifest for child {}",
    3794            0 :                 child_shard.to_index()
    3795              :             );
    3796            0 :             upload_tenant_manifest(
    3797            0 :                 &self.remote_storage,
    3798            0 :                 child_shard,
    3799            0 :                 self.generation,
    3800            0 :                 &tenant_manifest,
    3801            0 :                 &self.cancel,
    3802            0 :             )
    3803            0 :             .await?;
    3804              :         }
    3805              : 
    3806            0 :         Ok(())
    3807            0 :     }
    3808              : 
    3809            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3810            0 :         let mut result = TopTenantShardItem {
    3811            0 :             id: self.tenant_shard_id,
    3812            0 :             resident_size: 0,
    3813            0 :             physical_size: 0,
    3814            0 :             max_logical_size: 0,
    3815            0 :         };
    3816              : 
    3817            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3818            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3819            0 : 
    3820            0 :             result.physical_size += timeline
    3821            0 :                 .remote_client
    3822            0 :                 .metrics
    3823            0 :                 .remote_physical_size_gauge
    3824            0 :                 .get();
    3825            0 :             result.max_logical_size = std::cmp::max(
    3826            0 :                 result.max_logical_size,
    3827            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3828            0 :             );
    3829            0 :         }
    3830              : 
    3831            0 :         result
    3832            0 :     }
    3833              : }
    3834              : 
    3835              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3836              : /// perform a topological sort, so that the parent of each timeline comes
    3837              : /// before the children.
    3838              : /// E extracts the ancestor from T
    3839              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3840          444 : fn tree_sort_timelines<T, E>(
    3841          444 :     timelines: HashMap<TimelineId, T>,
    3842          444 :     extractor: E,
    3843          444 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3844          444 : where
    3845          444 :     E: Fn(&T) -> Option<TimelineId>,
    3846          444 : {
    3847          444 :     let mut result = Vec::with_capacity(timelines.len());
    3848          444 : 
    3849          444 :     let mut now = Vec::with_capacity(timelines.len());
    3850          444 :     // (ancestor, children)
    3851          444 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3852          444 :         HashMap::with_capacity(timelines.len());
    3853              : 
    3854          456 :     for (timeline_id, value) in timelines {
    3855           12 :         if let Some(ancestor_id) = extractor(&value) {
    3856            4 :             let children = later.entry(ancestor_id).or_default();
    3857            4 :             children.push((timeline_id, value));
    3858            8 :         } else {
    3859            8 :             now.push((timeline_id, value));
    3860            8 :         }
    3861              :     }
    3862              : 
    3863          456 :     while let Some((timeline_id, metadata)) = now.pop() {
    3864           12 :         result.push((timeline_id, metadata));
    3865              :         // All children of this can be loaded now
    3866           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3867            4 :             now.append(&mut children);
    3868            8 :         }
    3869              :     }
    3870              : 
    3871              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3872          444 :     if !later.is_empty() {
    3873            0 :         for (missing_id, orphan_ids) in later {
    3874            0 :             for (orphan_id, _) in orphan_ids {
    3875            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3876              :             }
    3877              :         }
    3878            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3879          444 :     }
    3880          444 : 
    3881          444 :     Ok(result)
    3882          444 : }
    3883              : 
    3884              : enum ActivateTimelineArgs {
    3885              :     Yes {
    3886              :         broker_client: storage_broker::BrokerClientChannel,
    3887              :     },
    3888              :     No,
    3889              : }
    3890              : 
    3891              : impl Tenant {
    3892            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3893            0 :         self.tenant_conf.load().tenant_conf.clone()
    3894            0 :     }
    3895              : 
    3896            0 :     pub fn effective_config(&self) -> TenantConf {
    3897            0 :         self.tenant_specific_overrides()
    3898            0 :             .merge(self.conf.default_tenant_conf.clone())
    3899            0 :     }
    3900              : 
    3901            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3902            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3903            0 :         tenant_conf
    3904            0 :             .checkpoint_distance
    3905            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3906            0 :     }
    3907              : 
    3908            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3909            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3910            0 :         tenant_conf
    3911            0 :             .checkpoint_timeout
    3912            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3913            0 :     }
    3914              : 
    3915            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3916            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3917            0 :         tenant_conf
    3918            0 :             .compaction_target_size
    3919            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3920            0 :     }
    3921              : 
    3922            0 :     pub fn get_compaction_period(&self) -> Duration {
    3923            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3924            0 :         tenant_conf
    3925            0 :             .compaction_period
    3926            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3927            0 :     }
    3928              : 
    3929            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3930            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3931            0 :         tenant_conf
    3932            0 :             .compaction_threshold
    3933            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3934            0 :     }
    3935              : 
    3936            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3937            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3938            0 :         tenant_conf
    3939            0 :             .rel_size_v2_enabled
    3940            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    3941            0 :     }
    3942              : 
    3943            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3944            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3945            0 :         tenant_conf
    3946            0 :             .compaction_upper_limit
    3947            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3948            0 :     }
    3949              : 
    3950            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    3951            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3952            0 :         tenant_conf
    3953            0 :             .compaction_l0_first
    3954            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    3955            0 :     }
    3956              : 
    3957            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3958            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3959            0 :         tenant_conf
    3960            0 :             .gc_horizon
    3961            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3962            0 :     }
    3963              : 
    3964            0 :     pub fn get_gc_period(&self) -> Duration {
    3965            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3966            0 :         tenant_conf
    3967            0 :             .gc_period
    3968            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3969            0 :     }
    3970              : 
    3971            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3972            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3973            0 :         tenant_conf
    3974            0 :             .image_creation_threshold
    3975            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3976            0 :     }
    3977              : 
    3978            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3979            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3980            0 :         tenant_conf
    3981            0 :             .pitr_interval
    3982            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3983            0 :     }
    3984              : 
    3985            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3986            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3987            0 :         tenant_conf
    3988            0 :             .min_resident_size_override
    3989            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3990            0 :     }
    3991              : 
    3992            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3993            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3994            0 :         let heatmap_period = tenant_conf
    3995            0 :             .heatmap_period
    3996            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3997            0 :         if heatmap_period.is_zero() {
    3998            0 :             None
    3999              :         } else {
    4000            0 :             Some(heatmap_period)
    4001              :         }
    4002            0 :     }
    4003              : 
    4004            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4005            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4006            8 :         tenant_conf
    4007            8 :             .lsn_lease_length
    4008            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4009            8 :     }
    4010              : 
    4011            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4012            0 :         if self.conf.timeline_offloading {
    4013            0 :             return true;
    4014            0 :         }
    4015            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4016            0 :         tenant_conf
    4017            0 :             .timeline_offloading
    4018            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4019            0 :     }
    4020              : 
    4021              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4022            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4023            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    4024            4 : 
    4025            4 :         let mut timeline_manifests = timelines_offloaded
    4026            4 :             .iter()
    4027            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    4028            4 :             .collect::<Vec<_>>();
    4029            4 :         // Sort the manifests so that our output is deterministic
    4030            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    4031            4 : 
    4032            4 :         TenantManifest {
    4033            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4034            4 :             offloaded_timelines: timeline_manifests,
    4035            4 :         }
    4036            4 :     }
    4037              : 
    4038            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    4039            0 :         &self,
    4040            0 :         update: F,
    4041            0 :     ) -> anyhow::Result<TenantConfOpt> {
    4042            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4043            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    4044            0 :         // this race is not possible if both request types come from the storage
    4045            0 :         // controller (as they should!) because an exclusive op lock is required
    4046            0 :         // on the storage controller side.
    4047            0 : 
    4048            0 :         self.tenant_conf
    4049            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4050            0 :                 Ok(Arc::new(AttachedTenantConf {
    4051            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4052            0 :                     location: attached_conf.location,
    4053            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4054              :                 }))
    4055            0 :             })?;
    4056              : 
    4057            0 :         let updated = self.tenant_conf.load();
    4058            0 : 
    4059            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4060            0 :         // Don't hold self.timelines.lock() during the notifies.
    4061            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4062            0 :         // mutexes in struct Timeline in the future.
    4063            0 :         let timelines = self.list_timelines();
    4064            0 :         for timeline in timelines {
    4065            0 :             timeline.tenant_conf_updated(&updated);
    4066            0 :         }
    4067              : 
    4068            0 :         Ok(updated.tenant_conf.clone())
    4069            0 :     }
    4070              : 
    4071            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4072            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4073            0 : 
    4074            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4075            0 : 
    4076            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4077            0 :         // Don't hold self.timelines.lock() during the notifies.
    4078            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4079            0 :         // mutexes in struct Timeline in the future.
    4080            0 :         let timelines = self.list_timelines();
    4081            0 :         for timeline in timelines {
    4082            0 :             timeline.tenant_conf_updated(&new_conf);
    4083            0 :         }
    4084            0 :     }
    4085              : 
    4086          444 :     fn get_pagestream_throttle_config(
    4087          444 :         psconf: &'static PageServerConf,
    4088          444 :         overrides: &TenantConfOpt,
    4089          444 :     ) -> throttle::Config {
    4090          444 :         overrides
    4091          444 :             .timeline_get_throttle
    4092          444 :             .clone()
    4093          444 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4094          444 :     }
    4095              : 
    4096            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    4097            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4098            0 :         self.pagestream_throttle.reconfigure(conf)
    4099            0 :     }
    4100              : 
    4101              :     /// Helper function to create a new Timeline struct.
    4102              :     ///
    4103              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4104              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4105              :     /// map.
    4106              :     ///
    4107              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4108              :     /// and we might not have the ancestor present anymore which is fine for to be
    4109              :     /// deleted timelines.
    4110              :     #[allow(clippy::too_many_arguments)]
    4111          896 :     fn create_timeline_struct(
    4112          896 :         &self,
    4113          896 :         new_timeline_id: TimelineId,
    4114          896 :         new_metadata: &TimelineMetadata,
    4115          896 :         previous_heatmap: Option<PreviousHeatmap>,
    4116          896 :         ancestor: Option<Arc<Timeline>>,
    4117          896 :         resources: TimelineResources,
    4118          896 :         cause: CreateTimelineCause,
    4119          896 :         create_idempotency: CreateTimelineIdempotency,
    4120          896 :     ) -> anyhow::Result<Arc<Timeline>> {
    4121          896 :         let state = match cause {
    4122              :             CreateTimelineCause::Load => {
    4123          896 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4124          896 :                 anyhow::ensure!(
    4125          896 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4126            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4127              :                 );
    4128          896 :                 TimelineState::Loading
    4129              :             }
    4130            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4131              :         };
    4132              : 
    4133          896 :         let pg_version = new_metadata.pg_version();
    4134          896 : 
    4135          896 :         let timeline = Timeline::new(
    4136          896 :             self.conf,
    4137          896 :             Arc::clone(&self.tenant_conf),
    4138          896 :             new_metadata,
    4139          896 :             previous_heatmap,
    4140          896 :             ancestor,
    4141          896 :             new_timeline_id,
    4142          896 :             self.tenant_shard_id,
    4143          896 :             self.generation,
    4144          896 :             self.shard_identity,
    4145          896 :             self.walredo_mgr.clone(),
    4146          896 :             resources,
    4147          896 :             pg_version,
    4148          896 :             state,
    4149          896 :             self.attach_wal_lag_cooldown.clone(),
    4150          896 :             create_idempotency,
    4151          896 :             self.cancel.child_token(),
    4152          896 :         );
    4153          896 : 
    4154          896 :         Ok(timeline)
    4155          896 :     }
    4156              : 
    4157              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4158              :     /// to ensure proper cleanup of background tasks and metrics.
    4159              :     //
    4160              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4161              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4162              :     #[allow(clippy::too_many_arguments)]
    4163          444 :     fn new(
    4164          444 :         state: TenantState,
    4165          444 :         conf: &'static PageServerConf,
    4166          444 :         attached_conf: AttachedTenantConf,
    4167          444 :         shard_identity: ShardIdentity,
    4168          444 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4169          444 :         tenant_shard_id: TenantShardId,
    4170          444 :         remote_storage: GenericRemoteStorage,
    4171          444 :         deletion_queue_client: DeletionQueueClient,
    4172          444 :         l0_flush_global_state: L0FlushGlobalState,
    4173          444 :     ) -> Tenant {
    4174          444 :         debug_assert!(
    4175          444 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4176              :         );
    4177              : 
    4178          444 :         let (state, mut rx) = watch::channel(state);
    4179          444 : 
    4180          444 :         tokio::spawn(async move {
    4181          444 :             // reflect tenant state in metrics:
    4182          444 :             // - global per tenant state: TENANT_STATE_METRIC
    4183          444 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4184          444 :             //
    4185          444 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4186          444 :             // alerting.
    4187          444 : 
    4188          444 :             let tid = tenant_shard_id.to_string();
    4189          444 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4190          444 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4191              : 
    4192          888 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4193          888 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4194          888 :             }
    4195              : 
    4196          444 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4197          444 : 
    4198          444 :             let is_broken = tuple.1;
    4199          444 :             let mut counted_broken = if is_broken {
    4200              :                 // add the id to the set right away, there should not be any updates on the channel
    4201              :                 // after before tenant is removed, if ever
    4202            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4203            0 :                 true
    4204              :             } else {
    4205          444 :                 false
    4206              :             };
    4207              : 
    4208              :             loop {
    4209          888 :                 let labels = &tuple.0;
    4210          888 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4211          888 :                 current.inc();
    4212          888 : 
    4213          888 :                 if rx.changed().await.is_err() {
    4214              :                     // tenant has been dropped
    4215           28 :                     current.dec();
    4216           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4217           28 :                     break;
    4218          444 :                 }
    4219          444 : 
    4220          444 :                 current.dec();
    4221          444 :                 tuple = inspect_state(&rx.borrow_and_update());
    4222          444 : 
    4223          444 :                 let is_broken = tuple.1;
    4224          444 :                 if is_broken && !counted_broken {
    4225            0 :                     counted_broken = true;
    4226            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4227            0 :                     // access
    4228            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4229          444 :                 }
    4230              :             }
    4231          444 :         });
    4232          444 : 
    4233          444 :         Tenant {
    4234          444 :             tenant_shard_id,
    4235          444 :             shard_identity,
    4236          444 :             generation: attached_conf.location.generation,
    4237          444 :             conf,
    4238          444 :             // using now here is good enough approximation to catch tenants with really long
    4239          444 :             // activation times.
    4240          444 :             constructed_at: Instant::now(),
    4241          444 :             timelines: Mutex::new(HashMap::new()),
    4242          444 :             timelines_creating: Mutex::new(HashSet::new()),
    4243          444 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4244          444 :             tenant_manifest_upload: Default::default(),
    4245          444 :             gc_cs: tokio::sync::Mutex::new(()),
    4246          444 :             walredo_mgr,
    4247          444 :             remote_storage,
    4248          444 :             deletion_queue_client,
    4249          444 :             state,
    4250          444 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4251          444 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4252          444 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4253          444 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4254          444 :                 format!("compaction-{tenant_shard_id}"),
    4255          444 :                 5,
    4256          444 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4257          444 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4258          444 :                 // use an extremely long backoff.
    4259          444 :                 Some(Duration::from_secs(3600 * 24)),
    4260          444 :             )),
    4261          444 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4262          444 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4263          444 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4264          444 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4265          444 :             cancel: CancellationToken::default(),
    4266          444 :             gate: Gate::default(),
    4267          444 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4268          444 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4269          444 :             )),
    4270          444 :             pagestream_throttle_metrics: Arc::new(
    4271          444 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4272          444 :             ),
    4273          444 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4274          444 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4275          444 :             gc_block: Default::default(),
    4276          444 :             l0_flush_global_state,
    4277          444 :         }
    4278          444 :     }
    4279              : 
    4280              :     /// Locate and load config
    4281            0 :     pub(super) fn load_tenant_config(
    4282            0 :         conf: &'static PageServerConf,
    4283            0 :         tenant_shard_id: &TenantShardId,
    4284            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4285            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4286            0 : 
    4287            0 :         info!("loading tenant configuration from {config_path}");
    4288              : 
    4289              :         // load and parse file
    4290            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4291            0 :             match e.kind() {
    4292              :                 std::io::ErrorKind::NotFound => {
    4293              :                     // The config should almost always exist for a tenant directory:
    4294              :                     //  - When attaching a tenant, the config is the first thing we write
    4295              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4296              :                     //    before deleting contents.
    4297              :                     //
    4298              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4299              :                     // between creating directory and writing config.  Callers should handle that as if the
    4300              :                     // directory didn't exist.
    4301              : 
    4302            0 :                     LoadConfigError::NotFound(config_path)
    4303              :                 }
    4304              :                 _ => {
    4305              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4306              :                     // that we cannot cleanly recover
    4307            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4308              :                 }
    4309              :             }
    4310            0 :         })?;
    4311              : 
    4312            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4313            0 :     }
    4314              : 
    4315              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4316              :     pub(super) async fn persist_tenant_config(
    4317              :         conf: &'static PageServerConf,
    4318              :         tenant_shard_id: &TenantShardId,
    4319              :         location_conf: &LocationConf,
    4320              :     ) -> std::io::Result<()> {
    4321              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4322              : 
    4323              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4324              :     }
    4325              : 
    4326              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4327              :     pub(super) async fn persist_tenant_config_at(
    4328              :         tenant_shard_id: &TenantShardId,
    4329              :         config_path: &Utf8Path,
    4330              :         location_conf: &LocationConf,
    4331              :     ) -> std::io::Result<()> {
    4332              :         debug!("persisting tenantconf to {config_path}");
    4333              : 
    4334              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4335              : #  It is read in case of pageserver restart.
    4336              : "#
    4337              :         .to_string();
    4338              : 
    4339            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4340            0 :             Err(std::io::Error::new(
    4341            0 :                 std::io::ErrorKind::Other,
    4342            0 :                 "tenant-config-before-write",
    4343            0 :             ))
    4344            0 :         });
    4345              : 
    4346              :         // Convert the config to a toml file.
    4347              :         conf_content +=
    4348              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4349              : 
    4350              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4351              : 
    4352              :         let conf_content = conf_content.into_bytes();
    4353              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4354              :     }
    4355              : 
    4356              :     //
    4357              :     // How garbage collection works:
    4358              :     //
    4359              :     //                    +--bar------------->
    4360              :     //                   /
    4361              :     //             +----+-----foo---------------->
    4362              :     //            /
    4363              :     // ----main--+-------------------------->
    4364              :     //                \
    4365              :     //                 +-----baz-------->
    4366              :     //
    4367              :     //
    4368              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4369              :     //    `gc_infos` are being refreshed
    4370              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4371              :     //    all the points where other timelines have been branched off.
    4372              :     //    We will refrain from removing page versions at those LSNs.
    4373              :     // 3. For each timeline, scan all layer files on the timeline.
    4374              :     //    Remove all files for which a newer file exists and which
    4375              :     //    don't cover any branch point LSNs.
    4376              :     //
    4377              :     // TODO:
    4378              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4379              :     //   don't need to keep that in the parent anymore. But currently
    4380              :     //   we do.
    4381            8 :     async fn gc_iteration_internal(
    4382            8 :         &self,
    4383            8 :         target_timeline_id: Option<TimelineId>,
    4384            8 :         horizon: u64,
    4385            8 :         pitr: Duration,
    4386            8 :         cancel: &CancellationToken,
    4387            8 :         ctx: &RequestContext,
    4388            8 :     ) -> Result<GcResult, GcError> {
    4389            8 :         let mut totals: GcResult = Default::default();
    4390            8 :         let now = Instant::now();
    4391              : 
    4392            8 :         let gc_timelines = self
    4393            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4394            8 :             .await?;
    4395              : 
    4396            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4397              : 
    4398              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4399            8 :         if !gc_timelines.is_empty() {
    4400            8 :             info!("{} timelines need GC", gc_timelines.len());
    4401              :         } else {
    4402            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4403              :         }
    4404              : 
    4405              :         // Perform GC for each timeline.
    4406              :         //
    4407              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4408              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4409              :         // with branch creation.
    4410              :         //
    4411              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4412              :         // creation task can run concurrently with timeline's GC iteration.
    4413           16 :         for timeline in gc_timelines {
    4414            8 :             if cancel.is_cancelled() {
    4415              :                 // We were requested to shut down. Stop and return with the progress we
    4416              :                 // made.
    4417            0 :                 break;
    4418            8 :             }
    4419            8 :             let result = match timeline.gc().await {
    4420              :                 Err(GcError::TimelineCancelled) => {
    4421            0 :                     if target_timeline_id.is_some() {
    4422              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4423            0 :                         return Err(GcError::TimelineCancelled);
    4424              :                     } else {
    4425              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4426              :                         // skip past this and proceed to try GC on other timelines.
    4427            0 :                         continue;
    4428              :                     }
    4429              :                 }
    4430            8 :                 r => r?,
    4431              :             };
    4432            8 :             totals += result;
    4433              :         }
    4434              : 
    4435            8 :         totals.elapsed = now.elapsed();
    4436            8 :         Ok(totals)
    4437            8 :     }
    4438              : 
    4439              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4440              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4441              :     /// [`Tenant::get_gc_horizon`].
    4442              :     ///
    4443              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4444            0 :     pub(crate) async fn refresh_gc_info(
    4445            0 :         &self,
    4446            0 :         cancel: &CancellationToken,
    4447            0 :         ctx: &RequestContext,
    4448            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4449            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4450            0 :         // might be that these configuration values get applied faster than what it was previously,
    4451            0 :         // since these were only read from the gc task.
    4452            0 :         let horizon = self.get_gc_horizon();
    4453            0 :         let pitr = self.get_pitr_interval();
    4454            0 : 
    4455            0 :         // refresh all timelines
    4456            0 :         let target_timeline_id = None;
    4457            0 : 
    4458            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4459            0 :             .await
    4460            0 :     }
    4461              : 
    4462              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4463              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4464              :     ///
    4465              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4466            0 :     fn initialize_gc_info(
    4467            0 :         &self,
    4468            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4469            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4470            0 :         restrict_to_timeline: Option<TimelineId>,
    4471            0 :     ) {
    4472            0 :         if restrict_to_timeline.is_none() {
    4473              :             // This function must be called before activation: after activation timeline create/delete operations
    4474              :             // might happen, and this function is not safe to run concurrently with those.
    4475            0 :             assert!(!self.is_active());
    4476            0 :         }
    4477              : 
    4478              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4479              :         // the branch point where it was created.
    4480            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4481            0 :             BTreeMap::new();
    4482            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4483            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4484            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4485            0 :                 ancestor_children.push((
    4486            0 :                     timeline_entry.get_ancestor_lsn(),
    4487            0 :                     *timeline_id,
    4488            0 :                     MaybeOffloaded::No,
    4489            0 :                 ));
    4490            0 :             }
    4491            0 :         });
    4492            0 :         timelines_offloaded
    4493            0 :             .iter()
    4494            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4495            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4496            0 :                     return;
    4497              :                 };
    4498            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4499            0 :                     return;
    4500              :                 };
    4501            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4502            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4503            0 :             });
    4504            0 : 
    4505            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4506            0 :         let horizon = self.get_gc_horizon();
    4507              : 
    4508              :         // Populate each timeline's GcInfo with information about its child branches
    4509            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4510            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4511              :         } else {
    4512            0 :             itertools::Either::Right(timelines.values())
    4513              :         };
    4514            0 :         for timeline in timelines_to_write {
    4515            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4516            0 :                 .remove(&timeline.timeline_id)
    4517            0 :                 .unwrap_or_default();
    4518            0 : 
    4519            0 :             branchpoints.sort_by_key(|b| b.0);
    4520            0 : 
    4521            0 :             let mut target = timeline.gc_info.write().unwrap();
    4522            0 : 
    4523            0 :             target.retain_lsns = branchpoints;
    4524            0 : 
    4525            0 :             let space_cutoff = timeline
    4526            0 :                 .get_last_record_lsn()
    4527            0 :                 .checked_sub(horizon)
    4528            0 :                 .unwrap_or(Lsn(0));
    4529            0 : 
    4530            0 :             target.cutoffs = GcCutoffs {
    4531            0 :                 space: space_cutoff,
    4532            0 :                 time: Lsn::INVALID,
    4533            0 :             };
    4534            0 :         }
    4535            0 :     }
    4536              : 
    4537            8 :     async fn refresh_gc_info_internal(
    4538            8 :         &self,
    4539            8 :         target_timeline_id: Option<TimelineId>,
    4540            8 :         horizon: u64,
    4541            8 :         pitr: Duration,
    4542            8 :         cancel: &CancellationToken,
    4543            8 :         ctx: &RequestContext,
    4544            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4545            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4546            8 :         // currently visible timelines.
    4547            8 :         let timelines = self
    4548            8 :             .timelines
    4549            8 :             .lock()
    4550            8 :             .unwrap()
    4551            8 :             .values()
    4552            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4553            8 :                 Some(target) => &tl.timeline_id == target,
    4554            0 :                 None => true,
    4555            8 :             })
    4556            8 :             .cloned()
    4557            8 :             .collect::<Vec<_>>();
    4558            8 : 
    4559            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4560              :             // We were to act on a particular timeline and it wasn't found
    4561            0 :             return Err(GcError::TimelineNotFound);
    4562            8 :         }
    4563            8 : 
    4564            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4565            8 :             HashMap::with_capacity(timelines.len());
    4566            8 : 
    4567            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4568            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4569            8 :         for timeline in timelines.iter() {
    4570            8 :             let cutoff = timeline
    4571            8 :                 .get_last_record_lsn()
    4572            8 :                 .checked_sub(horizon)
    4573            8 :                 .unwrap_or(Lsn(0));
    4574              : 
    4575            8 :             let cutoffs = timeline
    4576            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4577            8 :                 .await?;
    4578            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4579            8 :             assert!(old.is_none());
    4580              :         }
    4581              : 
    4582            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4583            0 :             return Err(GcError::TenantCancelled);
    4584            8 :         }
    4585              : 
    4586              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4587              :         // because that will stall branch creation.
    4588            8 :         let gc_cs = self.gc_cs.lock().await;
    4589              : 
    4590              :         // Ok, we now know all the branch points.
    4591              :         // Update the GC information for each timeline.
    4592            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4593           16 :         for timeline in timelines {
    4594              :             // We filtered the timeline list above
    4595            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4596            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4597            0 :             }
    4598              : 
    4599              :             {
    4600            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4601            8 : 
    4602            8 :                 // Cull any expired leases
    4603            8 :                 let now = SystemTime::now();
    4604           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4605            8 : 
    4606            8 :                 timeline
    4607            8 :                     .metrics
    4608            8 :                     .valid_lsn_lease_count_gauge
    4609            8 :                     .set(target.leases.len() as u64);
    4610              : 
    4611              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4612            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4613            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4614            0 :                         target.within_ancestor_pitr =
    4615            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4616            0 :                     }
    4617            8 :                 }
    4618              : 
    4619              :                 // Update metrics that depend on GC state
    4620            8 :                 timeline
    4621            8 :                     .metrics
    4622            8 :                     .archival_size
    4623            8 :                     .set(if target.within_ancestor_pitr {
    4624            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4625              :                     } else {
    4626            8 :                         0
    4627              :                     });
    4628            8 :                 timeline.metrics.pitr_history_size.set(
    4629            8 :                     timeline
    4630            8 :                         .get_last_record_lsn()
    4631            8 :                         .checked_sub(target.cutoffs.time)
    4632            8 :                         .unwrap_or(Lsn(0))
    4633            8 :                         .0,
    4634            8 :                 );
    4635              : 
    4636              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4637              :                 // - this timeline was created while we were finding cutoffs
    4638              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4639            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4640            8 :                     let original_cutoffs = target.cutoffs.clone();
    4641            8 :                     // GC cutoffs should never go back
    4642            8 :                     target.cutoffs = GcCutoffs {
    4643            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4644            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4645            8 :                     }
    4646            0 :                 }
    4647              :             }
    4648              : 
    4649            8 :             gc_timelines.push(timeline);
    4650              :         }
    4651            8 :         drop(gc_cs);
    4652            8 :         Ok(gc_timelines)
    4653            8 :     }
    4654              : 
    4655              :     /// A substitute for `branch_timeline` for use in unit tests.
    4656              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4657              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4658              :     /// timeline background tasks are launched, except the flush loop.
    4659              :     #[cfg(test)]
    4660          464 :     async fn branch_timeline_test(
    4661          464 :         self: &Arc<Self>,
    4662          464 :         src_timeline: &Arc<Timeline>,
    4663          464 :         dst_id: TimelineId,
    4664          464 :         ancestor_lsn: Option<Lsn>,
    4665          464 :         ctx: &RequestContext,
    4666          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4667          464 :         let tl = self
    4668          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4669          464 :             .await?
    4670          456 :             .into_timeline_for_test();
    4671          456 :         tl.set_state(TimelineState::Active);
    4672          456 :         Ok(tl)
    4673          464 :     }
    4674              : 
    4675              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4676              :     #[cfg(test)]
    4677              :     #[allow(clippy::too_many_arguments)]
    4678           12 :     pub async fn branch_timeline_test_with_layers(
    4679           12 :         self: &Arc<Self>,
    4680           12 :         src_timeline: &Arc<Timeline>,
    4681           12 :         dst_id: TimelineId,
    4682           12 :         ancestor_lsn: Option<Lsn>,
    4683           12 :         ctx: &RequestContext,
    4684           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4685           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4686           12 :         end_lsn: Lsn,
    4687           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4688              :         use checks::check_valid_layermap;
    4689              :         use itertools::Itertools;
    4690              : 
    4691           12 :         let tline = self
    4692           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4693           12 :             .await?;
    4694           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4695           12 :             ancestor_lsn
    4696              :         } else {
    4697            0 :             tline.get_last_record_lsn()
    4698              :         };
    4699           12 :         assert!(end_lsn >= ancestor_lsn);
    4700           12 :         tline.force_advance_lsn(end_lsn);
    4701           24 :         for deltas in delta_layer_desc {
    4702           12 :             tline
    4703           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4704           12 :                 .await?;
    4705              :         }
    4706           20 :         for (lsn, images) in image_layer_desc {
    4707            8 :             tline
    4708            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4709            8 :                 .await?;
    4710              :         }
    4711           12 :         let layer_names = tline
    4712           12 :             .layers
    4713           12 :             .read()
    4714           12 :             .await
    4715           12 :             .layer_map()
    4716           12 :             .unwrap()
    4717           12 :             .iter_historic_layers()
    4718           20 :             .map(|layer| layer.layer_name())
    4719           12 :             .collect_vec();
    4720           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4721            0 :             bail!("invalid layermap: {err}");
    4722           12 :         }
    4723           12 :         Ok(tline)
    4724           12 :     }
    4725              : 
    4726              :     /// Branch an existing timeline.
    4727            0 :     async fn branch_timeline(
    4728            0 :         self: &Arc<Self>,
    4729            0 :         src_timeline: &Arc<Timeline>,
    4730            0 :         dst_id: TimelineId,
    4731            0 :         start_lsn: Option<Lsn>,
    4732            0 :         ctx: &RequestContext,
    4733            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4734            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4735            0 :             .await
    4736            0 :     }
    4737              : 
    4738          464 :     async fn branch_timeline_impl(
    4739          464 :         self: &Arc<Self>,
    4740          464 :         src_timeline: &Arc<Timeline>,
    4741          464 :         dst_id: TimelineId,
    4742          464 :         start_lsn: Option<Lsn>,
    4743          464 :         _ctx: &RequestContext,
    4744          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4745          464 :         let src_id = src_timeline.timeline_id;
    4746              : 
    4747              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4748              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4749              :         // valid while we are creating the branch.
    4750          464 :         let _gc_cs = self.gc_cs.lock().await;
    4751              : 
    4752              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4753          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4754            4 :             let lsn = src_timeline.get_last_record_lsn();
    4755            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4756            4 :             lsn
    4757          464 :         });
    4758              : 
    4759              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4760          464 :         let timeline_create_guard = match self
    4761          464 :             .start_creating_timeline(
    4762          464 :                 dst_id,
    4763          464 :                 CreateTimelineIdempotency::Branch {
    4764          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4765          464 :                     ancestor_start_lsn: start_lsn,
    4766          464 :                 },
    4767          464 :             )
    4768          464 :             .await?
    4769              :         {
    4770          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4771            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4772            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4773              :             }
    4774              :         };
    4775              : 
    4776              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4777              :         // horizon on the source timeline
    4778              :         //
    4779              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4780              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4781              :         // planned GC cutoff in 'gc_info' is normally larger than
    4782              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4783              :         // changed the GC settings for the tenant to make the PITR window
    4784              :         // larger, but some of the data was already removed by an earlier GC
    4785              :         // iteration.
    4786              : 
    4787              :         // check against last actual 'latest_gc_cutoff' first
    4788          464 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4789          464 :         {
    4790          464 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4791          464 :             let planned_cutoff = gc_info.min_cutoff();
    4792          464 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4793            0 :                 tracing::info!("skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease", *applied_gc_cutoff_lsn);
    4794              :             } else {
    4795          464 :                 src_timeline
    4796          464 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4797          464 :                     .context(format!(
    4798          464 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4799          464 :                         *applied_gc_cutoff_lsn,
    4800          464 :                     ))
    4801          464 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4802              : 
    4803              :                 // and then the planned GC cutoff
    4804          456 :                 if start_lsn < planned_cutoff {
    4805            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4806            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4807            0 :                     )));
    4808          456 :                 }
    4809              :             }
    4810              :         }
    4811              : 
    4812              :         //
    4813              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4814              :         // so that GC cannot advance the GC cutoff until we are finished.
    4815              :         // Proceed with the branch creation.
    4816              :         //
    4817              : 
    4818              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4819              :         // the timeline was branched at the current end of the source timeline.
    4820              :         let RecordLsn {
    4821          456 :             last: src_last,
    4822          456 :             prev: src_prev,
    4823          456 :         } = src_timeline.get_last_record_rlsn();
    4824          456 :         let dst_prev = if src_last == start_lsn {
    4825          432 :             Some(src_prev)
    4826              :         } else {
    4827           24 :             None
    4828              :         };
    4829              : 
    4830              :         // Create the metadata file, noting the ancestor of the new timeline.
    4831              :         // There is initially no data in it, but all the read-calls know to look
    4832              :         // into the ancestor.
    4833          456 :         let metadata = TimelineMetadata::new(
    4834          456 :             start_lsn,
    4835          456 :             dst_prev,
    4836          456 :             Some(src_id),
    4837          456 :             start_lsn,
    4838          456 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4839          456 :             src_timeline.initdb_lsn,
    4840          456 :             src_timeline.pg_version,
    4841          456 :         );
    4842              : 
    4843          456 :         let uninitialized_timeline = self
    4844          456 :             .prepare_new_timeline(
    4845          456 :                 dst_id,
    4846          456 :                 &metadata,
    4847          456 :                 timeline_create_guard,
    4848          456 :                 start_lsn + 1,
    4849          456 :                 Some(Arc::clone(src_timeline)),
    4850          456 :             )
    4851          456 :             .await?;
    4852              : 
    4853          456 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4854              : 
    4855              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4856              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4857              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4858              :         // could get incorrect information and remove more layers, than needed.
    4859              :         // See also https://github.com/neondatabase/neon/issues/3865
    4860          456 :         new_timeline
    4861          456 :             .remote_client
    4862          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4863          456 :             .context("branch initial metadata upload")?;
    4864              : 
    4865              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4866              : 
    4867          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4868          464 :     }
    4869              : 
    4870              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4871              :     #[cfg(test)]
    4872              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4873              :     pub(crate) async fn bootstrap_timeline_test(
    4874              :         self: &Arc<Self>,
    4875              :         timeline_id: TimelineId,
    4876              :         pg_version: u32,
    4877              :         load_existing_initdb: Option<TimelineId>,
    4878              :         ctx: &RequestContext,
    4879              :     ) -> anyhow::Result<Arc<Timeline>> {
    4880              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4881              :             .await
    4882              :             .map_err(anyhow::Error::new)
    4883            4 :             .map(|r| r.into_timeline_for_test())
    4884              :     }
    4885              : 
    4886              :     /// Get exclusive access to the timeline ID for creation.
    4887              :     ///
    4888              :     /// Timeline-creating code paths must use this function before making changes
    4889              :     /// to in-memory or persistent state.
    4890              :     ///
    4891              :     /// The `state` parameter is a description of the timeline creation operation
    4892              :     /// we intend to perform.
    4893              :     /// If the timeline was already created in the meantime, we check whether this
    4894              :     /// request conflicts or is idempotent , based on `state`.
    4895          896 :     async fn start_creating_timeline(
    4896          896 :         self: &Arc<Self>,
    4897          896 :         new_timeline_id: TimelineId,
    4898          896 :         idempotency: CreateTimelineIdempotency,
    4899          896 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4900          896 :         let allow_offloaded = false;
    4901          896 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4902          892 :             Ok(create_guard) => {
    4903          892 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4904          892 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4905              :             }
    4906            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4907              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4908              :                 // Creation is in progress, we cannot create it again, and we cannot
    4909              :                 // check if this request matches the existing one, so caller must try
    4910              :                 // again later.
    4911            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4912              :             }
    4913            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4914              :             Err(TimelineExclusionError::AlreadyExists {
    4915            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4916            0 :                 ..
    4917            0 :             }) => {
    4918            0 :                 info!("timeline already exists but is offloaded");
    4919            0 :                 Err(CreateTimelineError::Conflict)
    4920              :             }
    4921              :             Err(TimelineExclusionError::AlreadyExists {
    4922            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4923            4 :                 arg,
    4924            4 :             }) => {
    4925            4 :                 {
    4926            4 :                     let existing = &existing.create_idempotency;
    4927            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4928            4 :                     debug!("timeline already exists");
    4929              : 
    4930            4 :                     match (existing, &arg) {
    4931              :                         // FailWithConflict => no idempotency check
    4932              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4933              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4934            4 :                             warn!("timeline already exists, failing request");
    4935            4 :                             return Err(CreateTimelineError::Conflict);
    4936              :                         }
    4937              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4938            0 :                         (x, y) if x == y => {
    4939            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4940              :                             // fallthrough
    4941              :                         }
    4942              :                         (_, _) => {
    4943            0 :                             warn!("idempotency conflict, failing request");
    4944            0 :                             return Err(CreateTimelineError::Conflict);
    4945              :                         }
    4946              :                     }
    4947              :                 }
    4948              : 
    4949            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4950              :             }
    4951              :         }
    4952          896 :     }
    4953              : 
    4954            0 :     async fn upload_initdb(
    4955            0 :         &self,
    4956            0 :         timelines_path: &Utf8PathBuf,
    4957            0 :         pgdata_path: &Utf8PathBuf,
    4958            0 :         timeline_id: &TimelineId,
    4959            0 :     ) -> anyhow::Result<()> {
    4960            0 :         let temp_path = timelines_path.join(format!(
    4961            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4962            0 :         ));
    4963            0 : 
    4964            0 :         scopeguard::defer! {
    4965            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4966            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4967            0 :             }
    4968            0 :         }
    4969              : 
    4970            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4971              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4972            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4973            0 :             warn!(
    4974            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4975              :             );
    4976            0 :         }
    4977              : 
    4978            0 :         pausable_failpoint!("before-initdb-upload");
    4979              : 
    4980            0 :         backoff::retry(
    4981            0 :             || async {
    4982            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4983            0 :                     &self.remote_storage,
    4984            0 :                     &self.tenant_shard_id.tenant_id,
    4985            0 :                     timeline_id,
    4986            0 :                     pgdata_zstd.try_clone().await?,
    4987            0 :                     tar_zst_size,
    4988            0 :                     &self.cancel,
    4989            0 :                 )
    4990            0 :                 .await
    4991            0 :             },
    4992            0 :             |_| false,
    4993            0 :             3,
    4994            0 :             u32::MAX,
    4995            0 :             "persist_initdb_tar_zst",
    4996            0 :             &self.cancel,
    4997            0 :         )
    4998            0 :         .await
    4999            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5000            0 :         .and_then(|x| x)
    5001            0 :     }
    5002              : 
    5003              :     /// - run initdb to init temporary instance and get bootstrap data
    5004              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5005            4 :     async fn bootstrap_timeline(
    5006            4 :         self: &Arc<Self>,
    5007            4 :         timeline_id: TimelineId,
    5008            4 :         pg_version: u32,
    5009            4 :         load_existing_initdb: Option<TimelineId>,
    5010            4 :         ctx: &RequestContext,
    5011            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5012            4 :         let timeline_create_guard = match self
    5013            4 :             .start_creating_timeline(
    5014            4 :                 timeline_id,
    5015            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5016            4 :             )
    5017            4 :             .await?
    5018              :         {
    5019            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5020            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5021            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    5022              :             }
    5023              :         };
    5024              : 
    5025              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5026              :         // temporary directory for basebackup files for the given timeline.
    5027              : 
    5028            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5029            4 :         let pgdata_path = path_with_suffix_extension(
    5030            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5031            4 :             TEMP_FILE_SUFFIX,
    5032            4 :         );
    5033            4 : 
    5034            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5035            4 :         // we won't race with other creations or existent timelines with the same path.
    5036            4 :         if pgdata_path.exists() {
    5037            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5038            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5039            0 :             })?;
    5040            4 :         }
    5041              : 
    5042              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5043            4 :         let pgdata_path_deferred = pgdata_path.clone();
    5044            4 :         scopeguard::defer! {
    5045            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
    5046            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5047            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5048            4 :             }
    5049            4 :         }
    5050            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5051            4 :             if existing_initdb_timeline_id != timeline_id {
    5052            0 :                 let source_path = &remote_initdb_archive_path(
    5053            0 :                     &self.tenant_shard_id.tenant_id,
    5054            0 :                     &existing_initdb_timeline_id,
    5055            0 :                 );
    5056            0 :                 let dest_path =
    5057            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5058            0 : 
    5059            0 :                 // if this fails, it will get retried by retried control plane requests
    5060            0 :                 self.remote_storage
    5061            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5062            0 :                     .await
    5063            0 :                     .context("copy initdb tar")?;
    5064            4 :             }
    5065            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5066            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5067            4 :                     self.conf,
    5068            4 :                     &self.remote_storage,
    5069            4 :                     &self.tenant_shard_id,
    5070            4 :                     &existing_initdb_timeline_id,
    5071            4 :                     &self.cancel,
    5072            4 :                 )
    5073            4 :                 .await
    5074            4 :                 .context("download initdb tar")?;
    5075              : 
    5076            4 :             scopeguard::defer! {
    5077            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5078            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5079            4 :                 }
    5080            4 :             }
    5081            4 : 
    5082            4 :             let buf_read =
    5083            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5084            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    5085            4 :                 .await
    5086            4 :                 .context("extract initdb tar")?;
    5087              :         } else {
    5088              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5089            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5090            0 :                 .await
    5091            0 :                 .context("run initdb")?;
    5092              : 
    5093              :             // Upload the created data dir to S3
    5094            0 :             if self.tenant_shard_id().is_shard_zero() {
    5095            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5096            0 :                     .await?;
    5097            0 :             }
    5098              :         }
    5099            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5100            4 : 
    5101            4 :         // Import the contents of the data directory at the initial checkpoint
    5102            4 :         // LSN, and any WAL after that.
    5103            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5104            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5105            4 :         let new_metadata = TimelineMetadata::new(
    5106            4 :             Lsn(0),
    5107            4 :             None,
    5108            4 :             None,
    5109            4 :             Lsn(0),
    5110            4 :             pgdata_lsn,
    5111            4 :             pgdata_lsn,
    5112            4 :             pg_version,
    5113            4 :         );
    5114            4 :         let mut raw_timeline = self
    5115            4 :             .prepare_new_timeline(
    5116            4 :                 timeline_id,
    5117            4 :                 &new_metadata,
    5118            4 :                 timeline_create_guard,
    5119            4 :                 pgdata_lsn,
    5120            4 :                 None,
    5121            4 :             )
    5122            4 :             .await?;
    5123              : 
    5124            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5125            4 :         raw_timeline
    5126            4 :             .write(|unfinished_timeline| async move {
    5127            4 :                 import_datadir::import_timeline_from_postgres_datadir(
    5128            4 :                     &unfinished_timeline,
    5129            4 :                     &pgdata_path,
    5130            4 :                     pgdata_lsn,
    5131            4 :                     ctx,
    5132            4 :                 )
    5133            4 :                 .await
    5134            4 :                 .with_context(|| {
    5135            0 :                     format!(
    5136            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5137            0 :                     )
    5138            4 :                 })?;
    5139              : 
    5140            4 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5141            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5142            0 :                         "failpoint before-checkpoint-new-timeline"
    5143            0 :                     )))
    5144            4 :                 });
    5145              : 
    5146            4 :                 Ok(())
    5147            8 :             })
    5148            4 :             .await?;
    5149              : 
    5150              :         // All done!
    5151            4 :         let timeline = raw_timeline.finish_creation().await?;
    5152              : 
    5153              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5154              : 
    5155            4 :         Ok(CreateTimelineResult::Created(timeline))
    5156            4 :     }
    5157              : 
    5158          884 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5159          884 :         RemoteTimelineClient::new(
    5160          884 :             self.remote_storage.clone(),
    5161          884 :             self.deletion_queue_client.clone(),
    5162          884 :             self.conf,
    5163          884 :             self.tenant_shard_id,
    5164          884 :             timeline_id,
    5165          884 :             self.generation,
    5166          884 :             &self.tenant_conf.load().location,
    5167          884 :         )
    5168          884 :     }
    5169              : 
    5170              :     /// Builds required resources for a new timeline.
    5171          884 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5172          884 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5173          884 :         self.get_timeline_resources_for(remote_client)
    5174          884 :     }
    5175              : 
    5176              :     /// Builds timeline resources for the given remote client.
    5177          896 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5178          896 :         TimelineResources {
    5179          896 :             remote_client,
    5180          896 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5181          896 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5182          896 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5183          896 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5184          896 :         }
    5185          896 :     }
    5186              : 
    5187              :     /// Creates intermediate timeline structure and its files.
    5188              :     ///
    5189              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5190              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5191              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5192          884 :     async fn prepare_new_timeline<'a>(
    5193          884 :         &'a self,
    5194          884 :         new_timeline_id: TimelineId,
    5195          884 :         new_metadata: &TimelineMetadata,
    5196          884 :         create_guard: TimelineCreateGuard,
    5197          884 :         start_lsn: Lsn,
    5198          884 :         ancestor: Option<Arc<Timeline>>,
    5199          884 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5200          884 :         let tenant_shard_id = self.tenant_shard_id;
    5201          884 : 
    5202          884 :         let resources = self.build_timeline_resources(new_timeline_id);
    5203          884 :         resources
    5204          884 :             .remote_client
    5205          884 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5206              : 
    5207          884 :         let timeline_struct = self
    5208          884 :             .create_timeline_struct(
    5209          884 :                 new_timeline_id,
    5210          884 :                 new_metadata,
    5211          884 :                 None,
    5212          884 :                 ancestor,
    5213          884 :                 resources,
    5214          884 :                 CreateTimelineCause::Load,
    5215          884 :                 create_guard.idempotency.clone(),
    5216          884 :             )
    5217          884 :             .context("Failed to create timeline data structure")?;
    5218              : 
    5219          884 :         timeline_struct.init_empty_layer_map(start_lsn);
    5220              : 
    5221          884 :         if let Err(e) = self
    5222          884 :             .create_timeline_files(&create_guard.timeline_path)
    5223          884 :             .await
    5224              :         {
    5225            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5226            0 :             cleanup_timeline_directory(create_guard);
    5227            0 :             return Err(e);
    5228          884 :         }
    5229          884 : 
    5230          884 :         debug!(
    5231            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5232              :         );
    5233              : 
    5234          884 :         Ok(UninitializedTimeline::new(
    5235          884 :             self,
    5236          884 :             new_timeline_id,
    5237          884 :             Some((timeline_struct, create_guard)),
    5238          884 :         ))
    5239          884 :     }
    5240              : 
    5241          884 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5242          884 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5243              : 
    5244          884 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5245            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5246          884 :         });
    5247              : 
    5248          884 :         Ok(())
    5249          884 :     }
    5250              : 
    5251              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5252              :     /// concurrent attempts to create the same timeline.
    5253              :     ///
    5254              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5255              :     /// offloaded timelines or not.
    5256          896 :     fn create_timeline_create_guard(
    5257          896 :         self: &Arc<Self>,
    5258          896 :         timeline_id: TimelineId,
    5259          896 :         idempotency: CreateTimelineIdempotency,
    5260          896 :         allow_offloaded: bool,
    5261          896 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5262          896 :         let tenant_shard_id = self.tenant_shard_id;
    5263          896 : 
    5264          896 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5265              : 
    5266          896 :         let create_guard = TimelineCreateGuard::new(
    5267          896 :             self,
    5268          896 :             timeline_id,
    5269          896 :             timeline_path.clone(),
    5270          896 :             idempotency,
    5271          896 :             allow_offloaded,
    5272          896 :         )?;
    5273              : 
    5274              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5275              :         // for creation.
    5276              :         // A timeline directory should never exist on disk already:
    5277              :         // - a previous failed creation would have cleaned up after itself
    5278              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5279              :         //
    5280              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5281              :         // this error may indicate a bug in cleanup on failed creations.
    5282          892 :         if timeline_path.exists() {
    5283            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5284            0 :                 "Timeline directory already exists! This is a bug."
    5285            0 :             )));
    5286          892 :         }
    5287          892 : 
    5288          892 :         Ok(create_guard)
    5289          896 :     }
    5290              : 
    5291              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5292              :     ///
    5293              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5294              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5295              :     pub async fn gather_size_inputs(
    5296              :         &self,
    5297              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5298              :         // (only if it is shorter than the real cutoff).
    5299              :         max_retention_period: Option<u64>,
    5300              :         cause: LogicalSizeCalculationCause,
    5301              :         cancel: &CancellationToken,
    5302              :         ctx: &RequestContext,
    5303              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5304              :         let logical_sizes_at_once = self
    5305              :             .conf
    5306              :             .concurrent_tenant_size_logical_size_queries
    5307              :             .inner();
    5308              : 
    5309              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5310              :         //
    5311              :         // But the only case where we need to run multiple of these at once is when we
    5312              :         // request a size for a tenant manually via API, while another background calculation
    5313              :         // is in progress (which is not a common case).
    5314              :         //
    5315              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5316              :         let mut shared_cache = tokio::select! {
    5317              :             locked = self.cached_logical_sizes.lock() => locked,
    5318              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5319              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5320              :         };
    5321              : 
    5322              :         size::gather_inputs(
    5323              :             self,
    5324              :             logical_sizes_at_once,
    5325              :             max_retention_period,
    5326              :             &mut shared_cache,
    5327              :             cause,
    5328              :             cancel,
    5329              :             ctx,
    5330              :         )
    5331              :         .await
    5332              :     }
    5333              : 
    5334              :     /// Calculate synthetic tenant size and cache the result.
    5335              :     /// This is periodically called by background worker.
    5336              :     /// result is cached in tenant struct
    5337              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5338              :     pub async fn calculate_synthetic_size(
    5339              :         &self,
    5340              :         cause: LogicalSizeCalculationCause,
    5341              :         cancel: &CancellationToken,
    5342              :         ctx: &RequestContext,
    5343              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5344              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5345              : 
    5346              :         let size = inputs.calculate();
    5347              : 
    5348              :         self.set_cached_synthetic_size(size);
    5349              : 
    5350              :         Ok(size)
    5351              :     }
    5352              : 
    5353              :     /// Cache given synthetic size and update the metric value
    5354            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5355            0 :         self.cached_synthetic_tenant_size
    5356            0 :             .store(size, Ordering::Relaxed);
    5357            0 : 
    5358            0 :         // Only shard zero should be calculating synthetic sizes
    5359            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5360              : 
    5361            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5362            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5363            0 :             .unwrap()
    5364            0 :             .set(size);
    5365            0 :     }
    5366              : 
    5367            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5368            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5369            0 :     }
    5370              : 
    5371              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5372              :     ///
    5373              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5374              :     /// from an external API handler.
    5375              :     ///
    5376              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5377              :     /// still bounded by tenant/timeline shutdown.
    5378              :     #[tracing::instrument(skip_all)]
    5379              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5380              :         let timelines = self.timelines.lock().unwrap().clone();
    5381              : 
    5382            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5383            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5384            0 :             timeline.freeze_and_flush().await?;
    5385            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5386            0 :             timeline.remote_client.wait_completion().await?;
    5387              : 
    5388            0 :             Ok(())
    5389            0 :         }
    5390              : 
    5391              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5392              :         // aborted when this function's future is cancelled: they should stay alive
    5393              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5394              :         // before Timeline shutdown completes.
    5395              :         let mut results = FuturesUnordered::new();
    5396              : 
    5397              :         for (_timeline_id, timeline) in timelines {
    5398              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5399              :             // means that if this function's future is cancelled, the Timeline shutdown
    5400              :             // will still wait for any I/O in here to complete.
    5401              :             let Ok(gate) = timeline.gate.enter() else {
    5402              :                 continue;
    5403              :             };
    5404            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5405              :             results.push(jh);
    5406              :         }
    5407              : 
    5408              :         while let Some(r) = results.next().await {
    5409              :             if let Err(e) = r {
    5410              :                 if !e.is_cancelled() && !e.is_panic() {
    5411              :                     tracing::error!("unexpected join error: {e:?}");
    5412              :                 }
    5413              :             }
    5414              :         }
    5415              : 
    5416              :         // The flushes we did above were just writes, but the Tenant might have had
    5417              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5418              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5419              :         // because it's typically a no-op.
    5420              :         match self.deletion_queue_client.flush_execute().await {
    5421              :             Ok(_) => {}
    5422              :             Err(DeletionQueueError::ShuttingDown) => {}
    5423              :         }
    5424              : 
    5425              :         Ok(())
    5426              :     }
    5427              : 
    5428            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5429            0 :         self.tenant_conf.load().tenant_conf.clone()
    5430            0 :     }
    5431              : 
    5432              :     /// How much local storage would this tenant like to have?  It can cope with
    5433              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5434              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5435              :     /// by keeping important things on local disk.
    5436              :     ///
    5437              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5438              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5439              :     /// actually use more than they report here.
    5440            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5441            0 :         let timelines = self.timelines.lock().unwrap();
    5442            0 : 
    5443            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5444            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5445            0 :         // of them is used actively enough to occupy space on disk.
    5446            0 :         timelines
    5447            0 :             .values()
    5448            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5449            0 :             .max()
    5450            0 :             .unwrap_or(0)
    5451            0 :     }
    5452              : 
    5453              :     /// Serialize and write the latest TenantManifest to remote storage.
    5454            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5455              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5456              :         // must be loaded while holding this lock. This makes it safe to call this function
    5457              :         // from anywhere without worrying about colliding updates.
    5458            4 :         let mut guard = tokio::select! {
    5459            4 :             g = self.tenant_manifest_upload.lock() => {
    5460            4 :                 g
    5461              :             },
    5462            4 :             _ = self.cancel.cancelled() => {
    5463            0 :                 return Err(TenantManifestError::Cancelled);
    5464              :             }
    5465              :         };
    5466              : 
    5467            4 :         let manifest = self.build_tenant_manifest();
    5468            4 :         if Some(&manifest) == (*guard).as_ref() {
    5469              :             // Optimisation: skip uploads that don't change anything.
    5470            0 :             return Ok(());
    5471            4 :         }
    5472            4 : 
    5473            4 :         // Remote storage does no retries internally, so wrap it
    5474            4 :         match backoff::retry(
    5475            4 :             || async {
    5476            4 :                 upload_tenant_manifest(
    5477            4 :                     &self.remote_storage,
    5478            4 :                     &self.tenant_shard_id,
    5479            4 :                     self.generation,
    5480            4 :                     &manifest,
    5481            4 :                     &self.cancel,
    5482            4 :                 )
    5483            4 :                 .await
    5484            8 :             },
    5485            4 :             |_e| self.cancel.is_cancelled(),
    5486            4 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5487            4 :             FAILED_REMOTE_OP_RETRIES,
    5488            4 :             "uploading tenant manifest",
    5489            4 :             &self.cancel,
    5490            4 :         )
    5491            4 :         .await
    5492              :         {
    5493            0 :             None => Err(TenantManifestError::Cancelled),
    5494            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5495            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5496              :             Some(Ok(_)) => {
    5497              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5498              :                 // re-uploading the same thing.
    5499            4 :                 *guard = Some(manifest);
    5500            4 : 
    5501            4 :                 Ok(())
    5502              :             }
    5503              :         }
    5504            4 :     }
    5505              : }
    5506              : 
    5507              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5508              : /// to get bootstrap data for timeline initialization.
    5509            0 : async fn run_initdb(
    5510            0 :     conf: &'static PageServerConf,
    5511            0 :     initdb_target_dir: &Utf8Path,
    5512            0 :     pg_version: u32,
    5513            0 :     cancel: &CancellationToken,
    5514            0 : ) -> Result<(), InitdbError> {
    5515            0 :     let initdb_bin_path = conf
    5516            0 :         .pg_bin_dir(pg_version)
    5517            0 :         .map_err(InitdbError::Other)?
    5518            0 :         .join("initdb");
    5519            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5520            0 :     info!(
    5521            0 :         "running {} in {}, libdir: {}",
    5522              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5523              :     );
    5524              : 
    5525            0 :     let _permit = {
    5526            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5527            0 :         INIT_DB_SEMAPHORE.acquire().await
    5528              :     };
    5529              : 
    5530            0 :     CONCURRENT_INITDBS.inc();
    5531            0 :     scopeguard::defer! {
    5532            0 :         CONCURRENT_INITDBS.dec();
    5533            0 :     }
    5534            0 : 
    5535            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5536            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5537            0 :         superuser: &conf.superuser,
    5538            0 :         locale: &conf.locale,
    5539            0 :         initdb_bin: &initdb_bin_path,
    5540            0 :         pg_version,
    5541            0 :         library_search_path: &initdb_lib_dir,
    5542            0 :         pgdata: initdb_target_dir,
    5543            0 :     })
    5544            0 :     .await
    5545            0 :     .map_err(InitdbError::Inner);
    5546            0 : 
    5547            0 :     // This isn't true cancellation support, see above. Still return an error to
    5548            0 :     // excercise the cancellation code path.
    5549            0 :     if cancel.is_cancelled() {
    5550            0 :         return Err(InitdbError::Cancelled);
    5551            0 :     }
    5552            0 : 
    5553            0 :     res
    5554            0 : }
    5555              : 
    5556              : /// Dump contents of a layer file to stdout.
    5557            0 : pub async fn dump_layerfile_from_path(
    5558            0 :     path: &Utf8Path,
    5559            0 :     verbose: bool,
    5560            0 :     ctx: &RequestContext,
    5561            0 : ) -> anyhow::Result<()> {
    5562              :     use std::os::unix::fs::FileExt;
    5563              : 
    5564              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5565              :     // file.
    5566            0 :     let file = File::open(path)?;
    5567            0 :     let mut header_buf = [0u8; 2];
    5568            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5569              : 
    5570            0 :     match u16::from_be_bytes(header_buf) {
    5571              :         crate::IMAGE_FILE_MAGIC => {
    5572            0 :             ImageLayer::new_for_path(path, file)?
    5573            0 :                 .dump(verbose, ctx)
    5574            0 :                 .await?
    5575              :         }
    5576              :         crate::DELTA_FILE_MAGIC => {
    5577            0 :             DeltaLayer::new_for_path(path, file)?
    5578            0 :                 .dump(verbose, ctx)
    5579            0 :                 .await?
    5580              :         }
    5581            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5582              :     }
    5583              : 
    5584            0 :     Ok(())
    5585            0 : }
    5586              : 
    5587              : #[cfg(test)]
    5588              : pub(crate) mod harness {
    5589              :     use bytes::{Bytes, BytesMut};
    5590              :     use once_cell::sync::OnceCell;
    5591              :     use pageserver_api::models::ShardParameters;
    5592              :     use pageserver_api::shard::ShardIndex;
    5593              :     use utils::logging;
    5594              : 
    5595              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5596              :     use crate::l0_flush::L0FlushConfig;
    5597              :     use crate::walredo::apply_neon;
    5598              :     use pageserver_api::key::Key;
    5599              :     use pageserver_api::record::NeonWalRecord;
    5600              : 
    5601              :     use super::*;
    5602              :     use hex_literal::hex;
    5603              :     use utils::id::TenantId;
    5604              : 
    5605              :     pub const TIMELINE_ID: TimelineId =
    5606              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5607              :     pub const NEW_TIMELINE_ID: TimelineId =
    5608              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5609              : 
    5610              :     /// Convenience function to create a page image with given string as the only content
    5611     10057571 :     pub fn test_img(s: &str) -> Bytes {
    5612     10057571 :         let mut buf = BytesMut::new();
    5613     10057571 :         buf.extend_from_slice(s.as_bytes());
    5614     10057571 :         buf.resize(64, 0);
    5615     10057571 : 
    5616     10057571 :         buf.freeze()
    5617     10057571 :     }
    5618              : 
    5619              :     impl From<TenantConf> for TenantConfOpt {
    5620          444 :         fn from(tenant_conf: TenantConf) -> Self {
    5621          444 :             Self {
    5622          444 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5623          444 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5624          444 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5625          444 :                 compaction_period: Some(tenant_conf.compaction_period),
    5626          444 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5627          444 :                 compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
    5628          444 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5629          444 :                 compaction_l0_first: Some(tenant_conf.compaction_l0_first),
    5630          444 :                 compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
    5631          444 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5632          444 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5633          444 :                 l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
    5634          444 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5635          444 :                 gc_period: Some(tenant_conf.gc_period),
    5636          444 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5637          444 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5638          444 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5639          444 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5640          444 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5641          444 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5642          444 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5643          444 :                 evictions_low_residence_duration_metric_threshold: Some(
    5644          444 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5645          444 :                 ),
    5646          444 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5647          444 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5648          444 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5649          444 :                 image_layer_creation_check_threshold: Some(
    5650          444 :                     tenant_conf.image_layer_creation_check_threshold,
    5651          444 :                 ),
    5652          444 :                 image_creation_preempt_threshold: Some(
    5653          444 :                     tenant_conf.image_creation_preempt_threshold,
    5654          444 :                 ),
    5655          444 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5656          444 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5657          444 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5658          444 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5659          444 :                 rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
    5660          444 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5661          444 :                 gc_compaction_initial_threshold_kb: Some(
    5662          444 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5663          444 :                 ),
    5664          444 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5665          444 :             }
    5666          444 :         }
    5667              :     }
    5668              : 
    5669              :     pub struct TenantHarness {
    5670              :         pub conf: &'static PageServerConf,
    5671              :         pub tenant_conf: TenantConf,
    5672              :         pub tenant_shard_id: TenantShardId,
    5673              :         pub generation: Generation,
    5674              :         pub shard: ShardIndex,
    5675              :         pub remote_storage: GenericRemoteStorage,
    5676              :         pub remote_fs_dir: Utf8PathBuf,
    5677              :         pub deletion_queue: MockDeletionQueue,
    5678              :     }
    5679              : 
    5680              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5681              : 
    5682          492 :     pub(crate) fn setup_logging() {
    5683          492 :         LOG_HANDLE.get_or_init(|| {
    5684          468 :             logging::init(
    5685          468 :                 logging::LogFormat::Test,
    5686          468 :                 // enable it in case the tests exercise code paths that use
    5687          468 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5688          468 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5689          468 :                 logging::Output::Stdout,
    5690          468 :             )
    5691          468 :             .expect("Failed to init test logging")
    5692          492 :         });
    5693          492 :     }
    5694              : 
    5695              :     impl TenantHarness {
    5696          444 :         pub async fn create_custom(
    5697          444 :             test_name: &'static str,
    5698          444 :             tenant_conf: TenantConf,
    5699          444 :             tenant_id: TenantId,
    5700          444 :             shard_identity: ShardIdentity,
    5701          444 :             generation: Generation,
    5702          444 :         ) -> anyhow::Result<Self> {
    5703          444 :             setup_logging();
    5704          444 : 
    5705          444 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5706          444 :             let _ = fs::remove_dir_all(&repo_dir);
    5707          444 :             fs::create_dir_all(&repo_dir)?;
    5708              : 
    5709          444 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5710          444 :             // Make a static copy of the config. This can never be free'd, but that's
    5711          444 :             // OK in a test.
    5712          444 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5713          444 : 
    5714          444 :             let shard = shard_identity.shard_index();
    5715          444 :             let tenant_shard_id = TenantShardId {
    5716          444 :                 tenant_id,
    5717          444 :                 shard_number: shard.shard_number,
    5718          444 :                 shard_count: shard.shard_count,
    5719          444 :             };
    5720          444 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5721          444 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5722              : 
    5723              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5724          444 :             let remote_fs_dir = conf.workdir.join("localfs");
    5725          444 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5726          444 :             let config = RemoteStorageConfig {
    5727          444 :                 storage: RemoteStorageKind::LocalFs {
    5728          444 :                     local_path: remote_fs_dir.clone(),
    5729          444 :                 },
    5730          444 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5731          444 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5732          444 :             };
    5733          444 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5734          444 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5735          444 : 
    5736          444 :             Ok(Self {
    5737          444 :                 conf,
    5738          444 :                 tenant_conf,
    5739          444 :                 tenant_shard_id,
    5740          444 :                 generation,
    5741          444 :                 shard,
    5742          444 :                 remote_storage,
    5743          444 :                 remote_fs_dir,
    5744          444 :                 deletion_queue,
    5745          444 :             })
    5746          444 :         }
    5747              : 
    5748          420 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5749          420 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5750          420 :             // The tests perform them manually if needed.
    5751          420 :             let tenant_conf = TenantConf {
    5752          420 :                 gc_period: Duration::ZERO,
    5753          420 :                 compaction_period: Duration::ZERO,
    5754          420 :                 ..TenantConf::default()
    5755          420 :             };
    5756          420 :             let tenant_id = TenantId::generate();
    5757          420 :             let shard = ShardIdentity::unsharded();
    5758          420 :             Self::create_custom(
    5759          420 :                 test_name,
    5760          420 :                 tenant_conf,
    5761          420 :                 tenant_id,
    5762          420 :                 shard,
    5763          420 :                 Generation::new(0xdeadbeef),
    5764          420 :             )
    5765          420 :             .await
    5766          420 :         }
    5767              : 
    5768           40 :         pub fn span(&self) -> tracing::Span {
    5769           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5770           40 :         }
    5771              : 
    5772          444 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5773          444 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5774          444 :             (
    5775          444 :                 self.do_try_load(&ctx)
    5776          444 :                     .await
    5777          444 :                     .expect("failed to load test tenant"),
    5778          444 :                 ctx,
    5779          444 :             )
    5780          444 :         }
    5781              : 
    5782              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5783              :         pub(crate) async fn do_try_load(
    5784              :             &self,
    5785              :             ctx: &RequestContext,
    5786              :         ) -> anyhow::Result<Arc<Tenant>> {
    5787              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5788              : 
    5789              :             let tenant = Arc::new(Tenant::new(
    5790              :                 TenantState::Attaching,
    5791              :                 self.conf,
    5792              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5793              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5794              :                     self.generation,
    5795              :                     &ShardParameters::default(),
    5796              :                 ))
    5797              :                 .unwrap(),
    5798              :                 // This is a legacy/test code path: sharding isn't supported here.
    5799              :                 ShardIdentity::unsharded(),
    5800              :                 Some(walredo_mgr),
    5801              :                 self.tenant_shard_id,
    5802              :                 self.remote_storage.clone(),
    5803              :                 self.deletion_queue.new_client(),
    5804              :                 // TODO: ideally we should run all unit tests with both configs
    5805              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5806              :             ));
    5807              : 
    5808              :             let preload = tenant
    5809              :                 .preload(&self.remote_storage, CancellationToken::new())
    5810              :                 .await?;
    5811              :             tenant.attach(Some(preload), ctx).await?;
    5812              : 
    5813              :             tenant.state.send_replace(TenantState::Active);
    5814              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5815              :                 timeline.set_state(TimelineState::Active);
    5816              :             }
    5817              :             Ok(tenant)
    5818              :         }
    5819              : 
    5820            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5821            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5822            4 :         }
    5823              :     }
    5824              : 
    5825              :     // Mock WAL redo manager that doesn't do much
    5826              :     pub(crate) struct TestRedoManager;
    5827              : 
    5828              :     impl TestRedoManager {
    5829              :         /// # Cancel-Safety
    5830              :         ///
    5831              :         /// This method is cancellation-safe.
    5832         1636 :         pub async fn request_redo(
    5833         1636 :             &self,
    5834         1636 :             key: Key,
    5835         1636 :             lsn: Lsn,
    5836         1636 :             base_img: Option<(Lsn, Bytes)>,
    5837         1636 :             records: Vec<(Lsn, NeonWalRecord)>,
    5838         1636 :             _pg_version: u32,
    5839         1636 :         ) -> Result<Bytes, walredo::Error> {
    5840         2392 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5841         1636 :             if records_neon {
    5842              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5843         1636 :                 let mut page = match (base_img, records.first()) {
    5844         1504 :                     (Some((_lsn, img)), _) => {
    5845         1504 :                         let mut page = BytesMut::new();
    5846         1504 :                         page.extend_from_slice(&img);
    5847         1504 :                         page
    5848              :                     }
    5849          132 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5850              :                     _ => {
    5851            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5852              :                     }
    5853              :                 };
    5854              : 
    5855         4028 :                 for (record_lsn, record) in records {
    5856         2392 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5857              :                 }
    5858         1636 :                 Ok(page.freeze())
    5859              :             } else {
    5860              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5861            0 :                 let s = format!(
    5862            0 :                     "redo for {} to get to {}, with {} and {} records",
    5863            0 :                     key,
    5864            0 :                     lsn,
    5865            0 :                     if base_img.is_some() {
    5866            0 :                         "base image"
    5867              :                     } else {
    5868            0 :                         "no base image"
    5869              :                     },
    5870            0 :                     records.len()
    5871            0 :                 );
    5872            0 :                 println!("{s}");
    5873            0 : 
    5874            0 :                 Ok(test_img(&s))
    5875              :             }
    5876         1636 :         }
    5877              :     }
    5878              : }
    5879              : 
    5880              : #[cfg(test)]
    5881              : mod tests {
    5882              :     use std::collections::{BTreeMap, BTreeSet};
    5883              : 
    5884              :     use super::*;
    5885              :     use crate::keyspace::KeySpaceAccum;
    5886              :     use crate::tenant::harness::*;
    5887              :     use crate::tenant::timeline::CompactFlags;
    5888              :     use crate::DEFAULT_PG_VERSION;
    5889              :     use bytes::{Bytes, BytesMut};
    5890              :     use hex_literal::hex;
    5891              :     use itertools::Itertools;
    5892              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5893              :     use pageserver_api::keyspace::KeySpace;
    5894              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5895              :     use pageserver_api::value::Value;
    5896              :     use pageserver_compaction::helpers::overlaps_with;
    5897              :     use rand::{thread_rng, Rng};
    5898              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5899              :     use tests::storage_layer::ValuesReconstructState;
    5900              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5901              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5902              :     use utils::id::TenantId;
    5903              : 
    5904              :     #[cfg(feature = "testing")]
    5905              :     use models::CompactLsnRange;
    5906              :     #[cfg(feature = "testing")]
    5907              :     use pageserver_api::record::NeonWalRecord;
    5908              :     #[cfg(feature = "testing")]
    5909              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5910              :     #[cfg(feature = "testing")]
    5911              :     use timeline::GcInfo;
    5912              : 
    5913              :     static TEST_KEY: Lazy<Key> =
    5914           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5915              : 
    5916              :     #[tokio::test]
    5917            4 :     async fn test_basic() -> anyhow::Result<()> {
    5918            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5919            4 :         let tline = tenant
    5920            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5921            4 :             .await?;
    5922            4 : 
    5923            4 :         let mut writer = tline.writer().await;
    5924            4 :         writer
    5925            4 :             .put(
    5926            4 :                 *TEST_KEY,
    5927            4 :                 Lsn(0x10),
    5928            4 :                 &Value::Image(test_img("foo at 0x10")),
    5929            4 :                 &ctx,
    5930            4 :             )
    5931            4 :             .await?;
    5932            4 :         writer.finish_write(Lsn(0x10));
    5933            4 :         drop(writer);
    5934            4 : 
    5935            4 :         let mut writer = tline.writer().await;
    5936            4 :         writer
    5937            4 :             .put(
    5938            4 :                 *TEST_KEY,
    5939            4 :                 Lsn(0x20),
    5940            4 :                 &Value::Image(test_img("foo at 0x20")),
    5941            4 :                 &ctx,
    5942            4 :             )
    5943            4 :             .await?;
    5944            4 :         writer.finish_write(Lsn(0x20));
    5945            4 :         drop(writer);
    5946            4 : 
    5947            4 :         assert_eq!(
    5948            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5949            4 :             test_img("foo at 0x10")
    5950            4 :         );
    5951            4 :         assert_eq!(
    5952            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5953            4 :             test_img("foo at 0x10")
    5954            4 :         );
    5955            4 :         assert_eq!(
    5956            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5957            4 :             test_img("foo at 0x20")
    5958            4 :         );
    5959            4 : 
    5960            4 :         Ok(())
    5961            4 :     }
    5962              : 
    5963              :     #[tokio::test]
    5964            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5965            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5966            4 :             .await?
    5967            4 :             .load()
    5968            4 :             .await;
    5969            4 :         let _ = tenant
    5970            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5971            4 :             .await?;
    5972            4 : 
    5973            4 :         match tenant
    5974            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5975            4 :             .await
    5976            4 :         {
    5977            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5978            4 :             Err(e) => assert_eq!(
    5979            4 :                 e.to_string(),
    5980            4 :                 "timeline already exists with different parameters".to_string()
    5981            4 :             ),
    5982            4 :         }
    5983            4 : 
    5984            4 :         Ok(())
    5985            4 :     }
    5986              : 
    5987              :     /// Convenience function to create a page image with given string as the only content
    5988           20 :     pub fn test_value(s: &str) -> Value {
    5989           20 :         let mut buf = BytesMut::new();
    5990           20 :         buf.extend_from_slice(s.as_bytes());
    5991           20 :         Value::Image(buf.freeze())
    5992           20 :     }
    5993              : 
    5994              :     ///
    5995              :     /// Test branch creation
    5996              :     ///
    5997              :     #[tokio::test]
    5998            4 :     async fn test_branch() -> anyhow::Result<()> {
    5999            4 :         use std::str::from_utf8;
    6000            4 : 
    6001            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6002            4 :         let tline = tenant
    6003            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6004            4 :             .await?;
    6005            4 :         let mut writer = tline.writer().await;
    6006            4 : 
    6007            4 :         #[allow(non_snake_case)]
    6008            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6009            4 :         #[allow(non_snake_case)]
    6010            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6011            4 : 
    6012            4 :         // Insert a value on the timeline
    6013            4 :         writer
    6014            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6015            4 :             .await?;
    6016            4 :         writer
    6017            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6018            4 :             .await?;
    6019            4 :         writer.finish_write(Lsn(0x20));
    6020            4 : 
    6021            4 :         writer
    6022            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6023            4 :             .await?;
    6024            4 :         writer.finish_write(Lsn(0x30));
    6025            4 :         writer
    6026            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6027            4 :             .await?;
    6028            4 :         writer.finish_write(Lsn(0x40));
    6029            4 : 
    6030            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6031            4 : 
    6032            4 :         // Branch the history, modify relation differently on the new timeline
    6033            4 :         tenant
    6034            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6035            4 :             .await?;
    6036            4 :         let newtline = tenant
    6037            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6038            4 :             .expect("Should have a local timeline");
    6039            4 :         let mut new_writer = newtline.writer().await;
    6040            4 :         new_writer
    6041            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6042            4 :             .await?;
    6043            4 :         new_writer.finish_write(Lsn(0x40));
    6044            4 : 
    6045            4 :         // Check page contents on both branches
    6046            4 :         assert_eq!(
    6047            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6048            4 :             "foo at 0x40"
    6049            4 :         );
    6050            4 :         assert_eq!(
    6051            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6052            4 :             "bar at 0x40"
    6053            4 :         );
    6054            4 :         assert_eq!(
    6055            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6056            4 :             "foobar at 0x20"
    6057            4 :         );
    6058            4 : 
    6059            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6060            4 : 
    6061            4 :         Ok(())
    6062            4 :     }
    6063              : 
    6064           40 :     async fn make_some_layers(
    6065           40 :         tline: &Timeline,
    6066           40 :         start_lsn: Lsn,
    6067           40 :         ctx: &RequestContext,
    6068           40 :     ) -> anyhow::Result<()> {
    6069           40 :         let mut lsn = start_lsn;
    6070              :         {
    6071           40 :             let mut writer = tline.writer().await;
    6072              :             // Create a relation on the timeline
    6073           40 :             writer
    6074           40 :                 .put(
    6075           40 :                     *TEST_KEY,
    6076           40 :                     lsn,
    6077           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6078           40 :                     ctx,
    6079           40 :                 )
    6080           40 :                 .await?;
    6081           40 :             writer.finish_write(lsn);
    6082           40 :             lsn += 0x10;
    6083           40 :             writer
    6084           40 :                 .put(
    6085           40 :                     *TEST_KEY,
    6086           40 :                     lsn,
    6087           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6088           40 :                     ctx,
    6089           40 :                 )
    6090           40 :                 .await?;
    6091           40 :             writer.finish_write(lsn);
    6092           40 :             lsn += 0x10;
    6093           40 :         }
    6094           40 :         tline.freeze_and_flush().await?;
    6095              :         {
    6096           40 :             let mut writer = tline.writer().await;
    6097           40 :             writer
    6098           40 :                 .put(
    6099           40 :                     *TEST_KEY,
    6100           40 :                     lsn,
    6101           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6102           40 :                     ctx,
    6103           40 :                 )
    6104           40 :                 .await?;
    6105           40 :             writer.finish_write(lsn);
    6106           40 :             lsn += 0x10;
    6107           40 :             writer
    6108           40 :                 .put(
    6109           40 :                     *TEST_KEY,
    6110           40 :                     lsn,
    6111           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6112           40 :                     ctx,
    6113           40 :                 )
    6114           40 :                 .await?;
    6115           40 :             writer.finish_write(lsn);
    6116           40 :         }
    6117           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6118           40 :     }
    6119              : 
    6120              :     #[tokio::test(start_paused = true)]
    6121            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6122            4 :         let (tenant, ctx) =
    6123            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6124            4 :                 .await?
    6125            4 :                 .load()
    6126            4 :                 .await;
    6127            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6128            4 :         // initial transition into AttachedSingle.
    6129            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6130            4 :         tokio::time::resume();
    6131            4 :         let tline = tenant
    6132            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6133            4 :             .await?;
    6134            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6135            4 : 
    6136            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6137            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6138            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6139            4 :         // below should fail.
    6140            4 :         tenant
    6141            4 :             .gc_iteration(
    6142            4 :                 Some(TIMELINE_ID),
    6143            4 :                 0x10,
    6144            4 :                 Duration::ZERO,
    6145            4 :                 &CancellationToken::new(),
    6146            4 :                 &ctx,
    6147            4 :             )
    6148            4 :             .await?;
    6149            4 : 
    6150            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6151            4 :         match tenant
    6152            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6153            4 :             .await
    6154            4 :         {
    6155            4 :             Ok(_) => panic!("branching should have failed"),
    6156            4 :             Err(err) => {
    6157            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6158            4 :                     panic!("wrong error type")
    6159            4 :                 };
    6160            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6161            4 :                 assert!(err
    6162            4 :                     .source()
    6163            4 :                     .unwrap()
    6164            4 :                     .to_string()
    6165            4 :                     .contains("we might've already garbage collected needed data"))
    6166            4 :             }
    6167            4 :         }
    6168            4 : 
    6169            4 :         Ok(())
    6170            4 :     }
    6171              : 
    6172              :     #[tokio::test]
    6173            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6174            4 :         let (tenant, ctx) =
    6175            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6176            4 :                 .await?
    6177            4 :                 .load()
    6178            4 :                 .await;
    6179            4 : 
    6180            4 :         let tline = tenant
    6181            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6182            4 :             .await?;
    6183            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6184            4 :         match tenant
    6185            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6186            4 :             .await
    6187            4 :         {
    6188            4 :             Ok(_) => panic!("branching should have failed"),
    6189            4 :             Err(err) => {
    6190            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6191            4 :                     panic!("wrong error type");
    6192            4 :                 };
    6193            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6194            4 :                 assert!(&err
    6195            4 :                     .source()
    6196            4 :                     .unwrap()
    6197            4 :                     .to_string()
    6198            4 :                     .contains("is earlier than latest GC cutoff"));
    6199            4 :             }
    6200            4 :         }
    6201            4 : 
    6202            4 :         Ok(())
    6203            4 :     }
    6204              : 
    6205              :     /*
    6206              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6207              :     // remove the old value, we'd need to work a little harder
    6208              :     #[tokio::test]
    6209              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6210              :         let repo =
    6211              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6212              :             .load();
    6213              : 
    6214              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6215              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6216              : 
    6217              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6218              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6219              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6220              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6221              :             Ok(_) => panic!("request for page should have failed"),
    6222              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6223              :         }
    6224              :         Ok(())
    6225              :     }
    6226              :      */
    6227              : 
    6228              :     #[tokio::test]
    6229            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6230            4 :         let (tenant, ctx) =
    6231            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6232            4 :                 .await?
    6233            4 :                 .load()
    6234            4 :                 .await;
    6235            4 :         let tline = tenant
    6236            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6237            4 :             .await?;
    6238            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6239            4 : 
    6240            4 :         tenant
    6241            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6242            4 :             .await?;
    6243            4 :         let newtline = tenant
    6244            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6245            4 :             .expect("Should have a local timeline");
    6246            4 : 
    6247            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6248            4 : 
    6249            4 :         tline.set_broken("test".to_owned());
    6250            4 : 
    6251            4 :         tenant
    6252            4 :             .gc_iteration(
    6253            4 :                 Some(TIMELINE_ID),
    6254            4 :                 0x10,
    6255            4 :                 Duration::ZERO,
    6256            4 :                 &CancellationToken::new(),
    6257            4 :                 &ctx,
    6258            4 :             )
    6259            4 :             .await?;
    6260            4 : 
    6261            4 :         // The branchpoints should contain all timelines, even ones marked
    6262            4 :         // as Broken.
    6263            4 :         {
    6264            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6265            4 :             assert_eq!(branchpoints.len(), 1);
    6266            4 :             assert_eq!(
    6267            4 :                 branchpoints[0],
    6268            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6269            4 :             );
    6270            4 :         }
    6271            4 : 
    6272            4 :         // You can read the key from the child branch even though the parent is
    6273            4 :         // Broken, as long as you don't need to access data from the parent.
    6274            4 :         assert_eq!(
    6275            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6276            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6277            4 :         );
    6278            4 : 
    6279            4 :         // This needs to traverse to the parent, and fails.
    6280            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6281            4 :         assert!(
    6282            4 :             err.to_string().starts_with(&format!(
    6283            4 :                 "bad state on timeline {}: Broken",
    6284            4 :                 tline.timeline_id
    6285            4 :             )),
    6286            4 :             "{err}"
    6287            4 :         );
    6288            4 : 
    6289            4 :         Ok(())
    6290            4 :     }
    6291              : 
    6292              :     #[tokio::test]
    6293            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6294            4 :         let (tenant, ctx) =
    6295            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6296            4 :                 .await?
    6297            4 :                 .load()
    6298            4 :                 .await;
    6299            4 :         let tline = tenant
    6300            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6301            4 :             .await?;
    6302            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6303            4 : 
    6304            4 :         tenant
    6305            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6306            4 :             .await?;
    6307            4 :         let newtline = tenant
    6308            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6309            4 :             .expect("Should have a local timeline");
    6310            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6311            4 :         tenant
    6312            4 :             .gc_iteration(
    6313            4 :                 Some(TIMELINE_ID),
    6314            4 :                 0x10,
    6315            4 :                 Duration::ZERO,
    6316            4 :                 &CancellationToken::new(),
    6317            4 :                 &ctx,
    6318            4 :             )
    6319            4 :             .await?;
    6320            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6321            4 : 
    6322            4 :         Ok(())
    6323            4 :     }
    6324              :     #[tokio::test]
    6325            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6326            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6327            4 :             .await?
    6328            4 :             .load()
    6329            4 :             .await;
    6330            4 :         let tline = tenant
    6331            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6332            4 :             .await?;
    6333            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6334            4 : 
    6335            4 :         tenant
    6336            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6337            4 :             .await?;
    6338            4 :         let newtline = tenant
    6339            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6340            4 :             .expect("Should have a local timeline");
    6341            4 : 
    6342            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6343            4 : 
    6344            4 :         // run gc on parent
    6345            4 :         tenant
    6346            4 :             .gc_iteration(
    6347            4 :                 Some(TIMELINE_ID),
    6348            4 :                 0x10,
    6349            4 :                 Duration::ZERO,
    6350            4 :                 &CancellationToken::new(),
    6351            4 :                 &ctx,
    6352            4 :             )
    6353            4 :             .await?;
    6354            4 : 
    6355            4 :         // Check that the data is still accessible on the branch.
    6356            4 :         assert_eq!(
    6357            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6358            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6359            4 :         );
    6360            4 : 
    6361            4 :         Ok(())
    6362            4 :     }
    6363              : 
    6364              :     #[tokio::test]
    6365            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6366            4 :         const TEST_NAME: &str = "timeline_load";
    6367            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6368            4 :         {
    6369            4 :             let (tenant, ctx) = harness.load().await;
    6370            4 :             let tline = tenant
    6371            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6372            4 :                 .await?;
    6373            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6374            4 :             // so that all uploads finish & we can call harness.load() below again
    6375            4 :             tenant
    6376            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6377            4 :                 .instrument(harness.span())
    6378            4 :                 .await
    6379            4 :                 .ok()
    6380            4 :                 .unwrap();
    6381            4 :         }
    6382            4 : 
    6383            4 :         let (tenant, _ctx) = harness.load().await;
    6384            4 :         tenant
    6385            4 :             .get_timeline(TIMELINE_ID, true)
    6386            4 :             .expect("cannot load timeline");
    6387            4 : 
    6388            4 :         Ok(())
    6389            4 :     }
    6390              : 
    6391              :     #[tokio::test]
    6392            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6393            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6394            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6395            4 :         // create two timelines
    6396            4 :         {
    6397            4 :             let (tenant, ctx) = harness.load().await;
    6398            4 :             let tline = tenant
    6399            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6400            4 :                 .await?;
    6401            4 : 
    6402            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6403            4 : 
    6404            4 :             let child_tline = tenant
    6405            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6406            4 :                 .await?;
    6407            4 :             child_tline.set_state(TimelineState::Active);
    6408            4 : 
    6409            4 :             let newtline = tenant
    6410            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6411            4 :                 .expect("Should have a local timeline");
    6412            4 : 
    6413            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6414            4 : 
    6415            4 :             // so that all uploads finish & we can call harness.load() below again
    6416            4 :             tenant
    6417            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6418            4 :                 .instrument(harness.span())
    6419            4 :                 .await
    6420            4 :                 .ok()
    6421            4 :                 .unwrap();
    6422            4 :         }
    6423            4 : 
    6424            4 :         // check that both of them are initially unloaded
    6425            4 :         let (tenant, _ctx) = harness.load().await;
    6426            4 : 
    6427            4 :         // check that both, child and ancestor are loaded
    6428            4 :         let _child_tline = tenant
    6429            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6430            4 :             .expect("cannot get child timeline loaded");
    6431            4 : 
    6432            4 :         let _ancestor_tline = tenant
    6433            4 :             .get_timeline(TIMELINE_ID, true)
    6434            4 :             .expect("cannot get ancestor timeline loaded");
    6435            4 : 
    6436            4 :         Ok(())
    6437            4 :     }
    6438              : 
    6439              :     #[tokio::test]
    6440            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6441            4 :         use storage_layer::AsLayerDesc;
    6442            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6443            4 :             .await?
    6444            4 :             .load()
    6445            4 :             .await;
    6446            4 :         let tline = tenant
    6447            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6448            4 :             .await?;
    6449            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6450            4 : 
    6451            4 :         let layer_map = tline.layers.read().await;
    6452            4 :         let level0_deltas = layer_map
    6453            4 :             .layer_map()?
    6454            4 :             .level0_deltas()
    6455            4 :             .iter()
    6456            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6457            4 :             .collect::<Vec<_>>();
    6458            4 : 
    6459            4 :         assert!(!level0_deltas.is_empty());
    6460            4 : 
    6461           12 :         for delta in level0_deltas {
    6462            4 :             // Ensure we are dumping a delta layer here
    6463            8 :             assert!(delta.layer_desc().is_delta);
    6464            8 :             delta.dump(true, &ctx).await.unwrap();
    6465            4 :         }
    6466            4 : 
    6467            4 :         Ok(())
    6468            4 :     }
    6469              : 
    6470              :     #[tokio::test]
    6471            4 :     async fn test_images() -> anyhow::Result<()> {
    6472            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6473            4 :         let tline = tenant
    6474            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6475            4 :             .await?;
    6476            4 : 
    6477            4 :         let mut writer = tline.writer().await;
    6478            4 :         writer
    6479            4 :             .put(
    6480            4 :                 *TEST_KEY,
    6481            4 :                 Lsn(0x10),
    6482            4 :                 &Value::Image(test_img("foo at 0x10")),
    6483            4 :                 &ctx,
    6484            4 :             )
    6485            4 :             .await?;
    6486            4 :         writer.finish_write(Lsn(0x10));
    6487            4 :         drop(writer);
    6488            4 : 
    6489            4 :         tline.freeze_and_flush().await?;
    6490            4 :         tline
    6491            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6492            4 :             .await?;
    6493            4 : 
    6494            4 :         let mut writer = tline.writer().await;
    6495            4 :         writer
    6496            4 :             .put(
    6497            4 :                 *TEST_KEY,
    6498            4 :                 Lsn(0x20),
    6499            4 :                 &Value::Image(test_img("foo at 0x20")),
    6500            4 :                 &ctx,
    6501            4 :             )
    6502            4 :             .await?;
    6503            4 :         writer.finish_write(Lsn(0x20));
    6504            4 :         drop(writer);
    6505            4 : 
    6506            4 :         tline.freeze_and_flush().await?;
    6507            4 :         tline
    6508            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6509            4 :             .await?;
    6510            4 : 
    6511            4 :         let mut writer = tline.writer().await;
    6512            4 :         writer
    6513            4 :             .put(
    6514            4 :                 *TEST_KEY,
    6515            4 :                 Lsn(0x30),
    6516            4 :                 &Value::Image(test_img("foo at 0x30")),
    6517            4 :                 &ctx,
    6518            4 :             )
    6519            4 :             .await?;
    6520            4 :         writer.finish_write(Lsn(0x30));
    6521            4 :         drop(writer);
    6522            4 : 
    6523            4 :         tline.freeze_and_flush().await?;
    6524            4 :         tline
    6525            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6526            4 :             .await?;
    6527            4 : 
    6528            4 :         let mut writer = tline.writer().await;
    6529            4 :         writer
    6530            4 :             .put(
    6531            4 :                 *TEST_KEY,
    6532            4 :                 Lsn(0x40),
    6533            4 :                 &Value::Image(test_img("foo at 0x40")),
    6534            4 :                 &ctx,
    6535            4 :             )
    6536            4 :             .await?;
    6537            4 :         writer.finish_write(Lsn(0x40));
    6538            4 :         drop(writer);
    6539            4 : 
    6540            4 :         tline.freeze_and_flush().await?;
    6541            4 :         tline
    6542            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6543            4 :             .await?;
    6544            4 : 
    6545            4 :         assert_eq!(
    6546            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6547            4 :             test_img("foo at 0x10")
    6548            4 :         );
    6549            4 :         assert_eq!(
    6550            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6551            4 :             test_img("foo at 0x10")
    6552            4 :         );
    6553            4 :         assert_eq!(
    6554            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6555            4 :             test_img("foo at 0x20")
    6556            4 :         );
    6557            4 :         assert_eq!(
    6558            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6559            4 :             test_img("foo at 0x30")
    6560            4 :         );
    6561            4 :         assert_eq!(
    6562            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6563            4 :             test_img("foo at 0x40")
    6564            4 :         );
    6565            4 : 
    6566            4 :         Ok(())
    6567            4 :     }
    6568              : 
    6569            8 :     async fn bulk_insert_compact_gc(
    6570            8 :         tenant: &Tenant,
    6571            8 :         timeline: &Arc<Timeline>,
    6572            8 :         ctx: &RequestContext,
    6573            8 :         lsn: Lsn,
    6574            8 :         repeat: usize,
    6575            8 :         key_count: usize,
    6576            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6577            8 :         let compact = true;
    6578            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6579            8 :     }
    6580              : 
    6581           16 :     async fn bulk_insert_maybe_compact_gc(
    6582           16 :         tenant: &Tenant,
    6583           16 :         timeline: &Arc<Timeline>,
    6584           16 :         ctx: &RequestContext,
    6585           16 :         mut lsn: Lsn,
    6586           16 :         repeat: usize,
    6587           16 :         key_count: usize,
    6588           16 :         compact: bool,
    6589           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6590           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6591           16 : 
    6592           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6593           16 :         let mut blknum = 0;
    6594           16 : 
    6595           16 :         // Enforce that key range is monotonously increasing
    6596           16 :         let mut keyspace = KeySpaceAccum::new();
    6597           16 : 
    6598           16 :         let cancel = CancellationToken::new();
    6599           16 : 
    6600           16 :         for _ in 0..repeat {
    6601          800 :             for _ in 0..key_count {
    6602      8000000 :                 test_key.field6 = blknum;
    6603      8000000 :                 let mut writer = timeline.writer().await;
    6604      8000000 :                 writer
    6605      8000000 :                     .put(
    6606      8000000 :                         test_key,
    6607      8000000 :                         lsn,
    6608      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6609      8000000 :                         ctx,
    6610      8000000 :                     )
    6611      8000000 :                     .await?;
    6612      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6613      8000000 :                 writer.finish_write(lsn);
    6614      8000000 :                 drop(writer);
    6615      8000000 : 
    6616      8000000 :                 keyspace.add_key(test_key);
    6617      8000000 : 
    6618      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6619      8000000 :                 blknum += 1;
    6620              :             }
    6621              : 
    6622          800 :             timeline.freeze_and_flush().await?;
    6623          800 :             if compact {
    6624              :                 // this requires timeline to be &Arc<Timeline>
    6625          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6626          400 :             }
    6627              : 
    6628              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6629              :             // originally was.
    6630          800 :             let res = tenant
    6631          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6632          800 :                 .await?;
    6633              : 
    6634          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6635              :         }
    6636              : 
    6637           16 :         Ok(inserted)
    6638           16 :     }
    6639              : 
    6640              :     //
    6641              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6642              :     // Repeat 50 times.
    6643              :     //
    6644              :     #[tokio::test]
    6645            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6646            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6647            4 :         let (tenant, ctx) = harness.load().await;
    6648            4 :         let tline = tenant
    6649            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6650            4 :             .await?;
    6651            4 : 
    6652            4 :         let lsn = Lsn(0x10);
    6653            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6654            4 : 
    6655            4 :         Ok(())
    6656            4 :     }
    6657              : 
    6658              :     // Test the vectored get real implementation against a simple sequential implementation.
    6659              :     //
    6660              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6661              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6662              :     // grow to the right on the X axis.
    6663              :     //                       [Delta]
    6664              :     //                 [Delta]
    6665              :     //           [Delta]
    6666              :     //    [Delta]
    6667              :     // ------------ Image ---------------
    6668              :     //
    6669              :     // After layer generation we pick the ranges to query as follows:
    6670              :     // 1. The beginning of each delta layer
    6671              :     // 2. At the seam between two adjacent delta layers
    6672              :     //
    6673              :     // There's one major downside to this test: delta layers only contains images,
    6674              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6675              :     #[tokio::test]
    6676            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6677            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6678            4 :         let (tenant, ctx) = harness.load().await;
    6679            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6680            4 :         let tline = tenant
    6681            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6682            4 :             .await?;
    6683            4 : 
    6684            4 :         let lsn = Lsn(0x10);
    6685            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6686            4 : 
    6687            4 :         let guard = tline.layers.read().await;
    6688            4 :         let lm = guard.layer_map()?;
    6689            4 : 
    6690            4 :         lm.dump(true, &ctx).await?;
    6691            4 : 
    6692            4 :         let mut reads = Vec::new();
    6693            4 :         let mut prev = None;
    6694           24 :         lm.iter_historic_layers().for_each(|desc| {
    6695           24 :             if !desc.is_delta() {
    6696            4 :                 prev = Some(desc.clone());
    6697            4 :                 return;
    6698           20 :             }
    6699           20 : 
    6700           20 :             let start = desc.key_range.start;
    6701           20 :             let end = desc
    6702           20 :                 .key_range
    6703           20 :                 .start
    6704           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6705           20 :             reads.push(KeySpace {
    6706           20 :                 ranges: vec![start..end],
    6707           20 :             });
    6708            4 : 
    6709           20 :             if let Some(prev) = &prev {
    6710           20 :                 if !prev.is_delta() {
    6711           20 :                     return;
    6712            4 :                 }
    6713            0 : 
    6714            0 :                 let first_range = Key {
    6715            0 :                     field6: prev.key_range.end.field6 - 4,
    6716            0 :                     ..prev.key_range.end
    6717            0 :                 }..prev.key_range.end;
    6718            0 : 
    6719            0 :                 let second_range = desc.key_range.start..Key {
    6720            0 :                     field6: desc.key_range.start.field6 + 4,
    6721            0 :                     ..desc.key_range.start
    6722            0 :                 };
    6723            0 : 
    6724            0 :                 reads.push(KeySpace {
    6725            0 :                     ranges: vec![first_range, second_range],
    6726            0 :                 });
    6727            4 :             };
    6728            4 : 
    6729            4 :             prev = Some(desc.clone());
    6730           24 :         });
    6731            4 : 
    6732            4 :         drop(guard);
    6733            4 : 
    6734            4 :         // Pick a big LSN such that we query over all the changes.
    6735            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6736            4 : 
    6737           24 :         for read in reads {
    6738           20 :             info!("Doing vectored read on {:?}", read);
    6739            4 : 
    6740           20 :             let vectored_res = tline
    6741           20 :                 .get_vectored_impl(
    6742           20 :                     read.clone(),
    6743           20 :                     reads_lsn,
    6744           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6745           20 :                     &ctx,
    6746           20 :                 )
    6747           20 :                 .await;
    6748            4 : 
    6749           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6750           20 :             let mut expect_missing = false;
    6751           20 :             let mut key = read.start().unwrap();
    6752          660 :             while key != read.end().unwrap() {
    6753          640 :                 if let Some(lsns) = inserted.get(&key) {
    6754          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6755          640 :                     match expected_lsn {
    6756          640 :                         Some(lsn) => {
    6757          640 :                             expected_lsns.insert(key, *lsn);
    6758          640 :                         }
    6759            4 :                         None => {
    6760            4 :                             expect_missing = true;
    6761            0 :                             break;
    6762            4 :                         }
    6763            4 :                     }
    6764            4 :                 } else {
    6765            4 :                     expect_missing = true;
    6766            0 :                     break;
    6767            4 :                 }
    6768            4 : 
    6769          640 :                 key = key.next();
    6770            4 :             }
    6771            4 : 
    6772           20 :             if expect_missing {
    6773            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6774            4 :             } else {
    6775          640 :                 for (key, image) in vectored_res? {
    6776          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6777          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6778          640 :                     assert_eq!(image?, expected_image);
    6779            4 :                 }
    6780            4 :             }
    6781            4 :         }
    6782            4 : 
    6783            4 :         Ok(())
    6784            4 :     }
    6785              : 
    6786              :     #[tokio::test]
    6787            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6788            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6789            4 : 
    6790            4 :         let (tenant, ctx) = harness.load().await;
    6791            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6792            4 :         let tline = tenant
    6793            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6794            4 :             .await?;
    6795            4 :         let tline = tline.raw_timeline().unwrap();
    6796            4 : 
    6797            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6798            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6799            4 :         modification.set_lsn(Lsn(0x1008))?;
    6800            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6801            4 :         modification.commit(&ctx).await?;
    6802            4 : 
    6803            4 :         let child_timeline_id = TimelineId::generate();
    6804            4 :         tenant
    6805            4 :             .branch_timeline_test(
    6806            4 :                 tline,
    6807            4 :                 child_timeline_id,
    6808            4 :                 Some(tline.get_last_record_lsn()),
    6809            4 :                 &ctx,
    6810            4 :             )
    6811            4 :             .await?;
    6812            4 : 
    6813            4 :         let child_timeline = tenant
    6814            4 :             .get_timeline(child_timeline_id, true)
    6815            4 :             .expect("Should have the branched timeline");
    6816            4 : 
    6817            4 :         let aux_keyspace = KeySpace {
    6818            4 :             ranges: vec![NON_INHERITED_RANGE],
    6819            4 :         };
    6820            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6821            4 : 
    6822            4 :         let vectored_res = child_timeline
    6823            4 :             .get_vectored_impl(
    6824            4 :                 aux_keyspace.clone(),
    6825            4 :                 read_lsn,
    6826            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6827            4 :                 &ctx,
    6828            4 :             )
    6829            4 :             .await;
    6830            4 : 
    6831            4 :         let images = vectored_res?;
    6832            4 :         assert!(images.is_empty());
    6833            4 :         Ok(())
    6834            4 :     }
    6835              : 
    6836              :     // Test that vectored get handles layer gaps correctly
    6837              :     // by advancing into the next ancestor timeline if required.
    6838              :     //
    6839              :     // The test generates timelines that look like the diagram below.
    6840              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6841              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6842              :     //
    6843              :     // ```
    6844              :     //-------------------------------+
    6845              :     //                          ...  |
    6846              :     //               [   L1   ]      |
    6847              :     //     [ / L1   ]                | Child Timeline
    6848              :     // ...                           |
    6849              :     // ------------------------------+
    6850              :     //     [ X L1   ]                | Parent Timeline
    6851              :     // ------------------------------+
    6852              :     // ```
    6853              :     #[tokio::test]
    6854            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6855            4 :         let tenant_conf = TenantConf {
    6856            4 :             // Make compaction deterministic
    6857            4 :             gc_period: Duration::ZERO,
    6858            4 :             compaction_period: Duration::ZERO,
    6859            4 :             // Encourage creation of L1 layers
    6860            4 :             checkpoint_distance: 16 * 1024,
    6861            4 :             compaction_target_size: 8 * 1024,
    6862            4 :             ..TenantConf::default()
    6863            4 :         };
    6864            4 : 
    6865            4 :         let harness = TenantHarness::create_custom(
    6866            4 :             "test_get_vectored_key_gap",
    6867            4 :             tenant_conf,
    6868            4 :             TenantId::generate(),
    6869            4 :             ShardIdentity::unsharded(),
    6870            4 :             Generation::new(0xdeadbeef),
    6871            4 :         )
    6872            4 :         .await?;
    6873            4 :         let (tenant, ctx) = harness.load().await;
    6874            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6875            4 : 
    6876            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6877            4 :         let gap_at_key = current_key.add(100);
    6878            4 :         let mut current_lsn = Lsn(0x10);
    6879            4 : 
    6880            4 :         const KEY_COUNT: usize = 10_000;
    6881            4 : 
    6882            4 :         let timeline_id = TimelineId::generate();
    6883            4 :         let current_timeline = tenant
    6884            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6885            4 :             .await?;
    6886            4 : 
    6887            4 :         current_lsn += 0x100;
    6888            4 : 
    6889            4 :         let mut writer = current_timeline.writer().await;
    6890            4 :         writer
    6891            4 :             .put(
    6892            4 :                 gap_at_key,
    6893            4 :                 current_lsn,
    6894            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6895            4 :                 &ctx,
    6896            4 :             )
    6897            4 :             .await?;
    6898            4 :         writer.finish_write(current_lsn);
    6899            4 :         drop(writer);
    6900            4 : 
    6901            4 :         let mut latest_lsns = HashMap::new();
    6902            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6903            4 : 
    6904            4 :         current_timeline.freeze_and_flush().await?;
    6905            4 : 
    6906            4 :         let child_timeline_id = TimelineId::generate();
    6907            4 : 
    6908            4 :         tenant
    6909            4 :             .branch_timeline_test(
    6910            4 :                 &current_timeline,
    6911            4 :                 child_timeline_id,
    6912            4 :                 Some(current_lsn),
    6913            4 :                 &ctx,
    6914            4 :             )
    6915            4 :             .await?;
    6916            4 :         let child_timeline = tenant
    6917            4 :             .get_timeline(child_timeline_id, true)
    6918            4 :             .expect("Should have the branched timeline");
    6919            4 : 
    6920        40004 :         for i in 0..KEY_COUNT {
    6921        40000 :             if current_key == gap_at_key {
    6922            4 :                 current_key = current_key.next();
    6923            4 :                 continue;
    6924        39996 :             }
    6925        39996 : 
    6926        39996 :             current_lsn += 0x10;
    6927            4 : 
    6928        39996 :             let mut writer = child_timeline.writer().await;
    6929        39996 :             writer
    6930        39996 :                 .put(
    6931        39996 :                     current_key,
    6932        39996 :                     current_lsn,
    6933        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6934        39996 :                     &ctx,
    6935        39996 :                 )
    6936        39996 :                 .await?;
    6937        39996 :             writer.finish_write(current_lsn);
    6938        39996 :             drop(writer);
    6939        39996 : 
    6940        39996 :             latest_lsns.insert(current_key, current_lsn);
    6941        39996 :             current_key = current_key.next();
    6942        39996 : 
    6943        39996 :             // Flush every now and then to encourage layer file creation.
    6944        39996 :             if i % 500 == 0 {
    6945           80 :                 child_timeline.freeze_and_flush().await?;
    6946        39916 :             }
    6947            4 :         }
    6948            4 : 
    6949            4 :         child_timeline.freeze_and_flush().await?;
    6950            4 :         let mut flags = EnumSet::new();
    6951            4 :         flags.insert(CompactFlags::ForceRepartition);
    6952            4 :         child_timeline
    6953            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    6954            4 :             .await?;
    6955            4 : 
    6956            4 :         let key_near_end = {
    6957            4 :             let mut tmp = current_key;
    6958            4 :             tmp.field6 -= 10;
    6959            4 :             tmp
    6960            4 :         };
    6961            4 : 
    6962            4 :         let key_near_gap = {
    6963            4 :             let mut tmp = gap_at_key;
    6964            4 :             tmp.field6 -= 10;
    6965            4 :             tmp
    6966            4 :         };
    6967            4 : 
    6968            4 :         let read = KeySpace {
    6969            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6970            4 :         };
    6971            4 :         let results = child_timeline
    6972            4 :             .get_vectored_impl(
    6973            4 :                 read.clone(),
    6974            4 :                 current_lsn,
    6975            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6976            4 :                 &ctx,
    6977            4 :             )
    6978            4 :             .await?;
    6979            4 : 
    6980           88 :         for (key, img_res) in results {
    6981           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6982           84 :             assert_eq!(img_res?, expected);
    6983            4 :         }
    6984            4 : 
    6985            4 :         Ok(())
    6986            4 :     }
    6987              : 
    6988              :     // Test that vectored get descends into ancestor timelines correctly and
    6989              :     // does not return an image that's newer than requested.
    6990              :     //
    6991              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6992              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6993              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6994              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6995              :     // order to avoid returning an image that's too new. The test below constructs such
    6996              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6997              :     // ```
    6998              :     //    LSN
    6999              :     //     ^
    7000              :     //     |
    7001              :     //     |
    7002              :     // 500 | --------------------------------------> branch point
    7003              :     // 400 |        X
    7004              :     // 300 |        X
    7005              :     // 200 | --------------------------------------> requested lsn
    7006              :     // 100 |        X
    7007              :     //     |---------------------------------------> Key
    7008              :     //              |
    7009              :     //              ------> requested key
    7010              :     //
    7011              :     // Legend:
    7012              :     // * X - page images
    7013              :     // ```
    7014              :     #[tokio::test]
    7015            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7016            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7017            4 :         let (tenant, ctx) = harness.load().await;
    7018            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7019            4 : 
    7020            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7021            4 :         let end_key = start_key.add(1000);
    7022            4 :         let child_gap_at_key = start_key.add(500);
    7023            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7024            4 : 
    7025            4 :         let mut current_lsn = Lsn(0x10);
    7026            4 : 
    7027            4 :         let timeline_id = TimelineId::generate();
    7028            4 :         let parent_timeline = tenant
    7029            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7030            4 :             .await?;
    7031            4 : 
    7032            4 :         current_lsn += 0x100;
    7033            4 : 
    7034           16 :         for _ in 0..3 {
    7035           12 :             let mut key = start_key;
    7036        12012 :             while key < end_key {
    7037        12000 :                 current_lsn += 0x10;
    7038        12000 : 
    7039        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7040            4 : 
    7041        12000 :                 let mut writer = parent_timeline.writer().await;
    7042        12000 :                 writer
    7043        12000 :                     .put(
    7044        12000 :                         key,
    7045        12000 :                         current_lsn,
    7046        12000 :                         &Value::Image(test_img(&image_value)),
    7047        12000 :                         &ctx,
    7048        12000 :                     )
    7049        12000 :                     .await?;
    7050        12000 :                 writer.finish_write(current_lsn);
    7051        12000 : 
    7052        12000 :                 if key == child_gap_at_key {
    7053           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7054        11988 :                 }
    7055            4 : 
    7056        12000 :                 key = key.next();
    7057            4 :             }
    7058            4 : 
    7059           12 :             parent_timeline.freeze_and_flush().await?;
    7060            4 :         }
    7061            4 : 
    7062            4 :         let child_timeline_id = TimelineId::generate();
    7063            4 : 
    7064            4 :         let child_timeline = tenant
    7065            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7066            4 :             .await?;
    7067            4 : 
    7068            4 :         let mut key = start_key;
    7069         4004 :         while key < end_key {
    7070         4000 :             if key == child_gap_at_key {
    7071            4 :                 key = key.next();
    7072            4 :                 continue;
    7073         3996 :             }
    7074         3996 : 
    7075         3996 :             current_lsn += 0x10;
    7076            4 : 
    7077         3996 :             let mut writer = child_timeline.writer().await;
    7078         3996 :             writer
    7079         3996 :                 .put(
    7080         3996 :                     key,
    7081         3996 :                     current_lsn,
    7082         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7083         3996 :                     &ctx,
    7084         3996 :                 )
    7085         3996 :                 .await?;
    7086         3996 :             writer.finish_write(current_lsn);
    7087         3996 : 
    7088         3996 :             key = key.next();
    7089            4 :         }
    7090            4 : 
    7091            4 :         child_timeline.freeze_and_flush().await?;
    7092            4 : 
    7093            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7094            4 :         let mut query_lsns = Vec::new();
    7095           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7096           72 :             for offset in lsn_offsets {
    7097           60 :                 query_lsns.push(Lsn(image_lsn
    7098           60 :                     .0
    7099           60 :                     .checked_add_signed(offset)
    7100           60 :                     .expect("Shouldn't overflow")));
    7101           60 :             }
    7102            4 :         }
    7103            4 : 
    7104           64 :         for query_lsn in query_lsns {
    7105           60 :             let results = child_timeline
    7106           60 :                 .get_vectored_impl(
    7107           60 :                     KeySpace {
    7108           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7109           60 :                     },
    7110           60 :                     query_lsn,
    7111           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7112           60 :                     &ctx,
    7113           60 :                 )
    7114           60 :                 .await;
    7115            4 : 
    7116           60 :             let expected_item = parent_gap_lsns
    7117           60 :                 .iter()
    7118           60 :                 .rev()
    7119          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7120           60 : 
    7121           60 :             info!(
    7122            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7123            4 :                 query_lsn, expected_item
    7124            4 :             );
    7125            4 : 
    7126           60 :             match expected_item {
    7127           52 :                 Some((_, img_value)) => {
    7128           52 :                     let key_results = results.expect("No vectored get error expected");
    7129           52 :                     let key_result = &key_results[&child_gap_at_key];
    7130           52 :                     let returned_img = key_result
    7131           52 :                         .as_ref()
    7132           52 :                         .expect("No page reconstruct error expected");
    7133           52 : 
    7134           52 :                     info!(
    7135            4 :                         "Vectored read at LSN {} returned image {}",
    7136            0 :                         query_lsn,
    7137            0 :                         std::str::from_utf8(returned_img)?
    7138            4 :                     );
    7139           52 :                     assert_eq!(*returned_img, test_img(img_value));
    7140            4 :                 }
    7141            4 :                 None => {
    7142            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7143            4 :                 }
    7144            4 :             }
    7145            4 :         }
    7146            4 : 
    7147            4 :         Ok(())
    7148            4 :     }
    7149              : 
    7150              :     #[tokio::test]
    7151            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    7152            4 :         let names_algorithms = [
    7153            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7154            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7155            4 :         ];
    7156           12 :         for (name, algorithm) in names_algorithms {
    7157            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7158            4 :         }
    7159            4 :         Ok(())
    7160            4 :     }
    7161              : 
    7162            8 :     async fn test_random_updates_algorithm(
    7163            8 :         name: &'static str,
    7164            8 :         compaction_algorithm: CompactionAlgorithm,
    7165            8 :     ) -> anyhow::Result<()> {
    7166            8 :         let mut harness = TenantHarness::create(name).await?;
    7167            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7168            8 :             kind: compaction_algorithm,
    7169            8 :         };
    7170            8 :         let (tenant, ctx) = harness.load().await;
    7171            8 :         let tline = tenant
    7172            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7173            8 :             .await?;
    7174              : 
    7175              :         const NUM_KEYS: usize = 1000;
    7176            8 :         let cancel = CancellationToken::new();
    7177            8 : 
    7178            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7179            8 :         let mut test_key_end = test_key;
    7180            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7181            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7182            8 : 
    7183            8 :         let mut keyspace = KeySpaceAccum::new();
    7184            8 : 
    7185            8 :         // Track when each page was last modified. Used to assert that
    7186            8 :         // a read sees the latest page version.
    7187            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7188            8 : 
    7189            8 :         let mut lsn = Lsn(0x10);
    7190              :         #[allow(clippy::needless_range_loop)]
    7191         8008 :         for blknum in 0..NUM_KEYS {
    7192         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7193         8000 :             test_key.field6 = blknum as u32;
    7194         8000 :             let mut writer = tline.writer().await;
    7195         8000 :             writer
    7196         8000 :                 .put(
    7197         8000 :                     test_key,
    7198         8000 :                     lsn,
    7199         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7200         8000 :                     &ctx,
    7201         8000 :                 )
    7202         8000 :                 .await?;
    7203         8000 :             writer.finish_write(lsn);
    7204         8000 :             updated[blknum] = lsn;
    7205         8000 :             drop(writer);
    7206         8000 : 
    7207         8000 :             keyspace.add_key(test_key);
    7208              :         }
    7209              : 
    7210          408 :         for _ in 0..50 {
    7211       400400 :             for _ in 0..NUM_KEYS {
    7212       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7213       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7214       400000 :                 test_key.field6 = blknum as u32;
    7215       400000 :                 let mut writer = tline.writer().await;
    7216       400000 :                 writer
    7217       400000 :                     .put(
    7218       400000 :                         test_key,
    7219       400000 :                         lsn,
    7220       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7221       400000 :                         &ctx,
    7222       400000 :                     )
    7223       400000 :                     .await?;
    7224       400000 :                 writer.finish_write(lsn);
    7225       400000 :                 drop(writer);
    7226       400000 :                 updated[blknum] = lsn;
    7227              :             }
    7228              : 
    7229              :             // Read all the blocks
    7230       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7231       400000 :                 test_key.field6 = blknum as u32;
    7232       400000 :                 assert_eq!(
    7233       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7234       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7235              :                 );
    7236              :             }
    7237              : 
    7238              :             // Perform a cycle of flush, and GC
    7239          400 :             tline.freeze_and_flush().await?;
    7240          400 :             tenant
    7241          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7242          400 :                 .await?;
    7243              :         }
    7244              : 
    7245            8 :         Ok(())
    7246            8 :     }
    7247              : 
    7248              :     #[tokio::test]
    7249            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7250            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7251            4 :             .await?
    7252            4 :             .load()
    7253            4 :             .await;
    7254            4 :         let mut tline = tenant
    7255            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7256            4 :             .await?;
    7257            4 : 
    7258            4 :         const NUM_KEYS: usize = 1000;
    7259            4 : 
    7260            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7261            4 : 
    7262            4 :         let mut keyspace = KeySpaceAccum::new();
    7263            4 : 
    7264            4 :         let cancel = CancellationToken::new();
    7265            4 : 
    7266            4 :         // Track when each page was last modified. Used to assert that
    7267            4 :         // a read sees the latest page version.
    7268            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7269            4 : 
    7270            4 :         let mut lsn = Lsn(0x10);
    7271            4 :         #[allow(clippy::needless_range_loop)]
    7272         4004 :         for blknum in 0..NUM_KEYS {
    7273         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7274         4000 :             test_key.field6 = blknum as u32;
    7275         4000 :             let mut writer = tline.writer().await;
    7276         4000 :             writer
    7277         4000 :                 .put(
    7278         4000 :                     test_key,
    7279         4000 :                     lsn,
    7280         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7281         4000 :                     &ctx,
    7282         4000 :                 )
    7283         4000 :                 .await?;
    7284         4000 :             writer.finish_write(lsn);
    7285         4000 :             updated[blknum] = lsn;
    7286         4000 :             drop(writer);
    7287         4000 : 
    7288         4000 :             keyspace.add_key(test_key);
    7289            4 :         }
    7290            4 : 
    7291          204 :         for _ in 0..50 {
    7292          200 :             let new_tline_id = TimelineId::generate();
    7293          200 :             tenant
    7294          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7295          200 :                 .await?;
    7296          200 :             tline = tenant
    7297          200 :                 .get_timeline(new_tline_id, true)
    7298          200 :                 .expect("Should have the branched timeline");
    7299            4 : 
    7300       200200 :             for _ in 0..NUM_KEYS {
    7301       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7302       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7303       200000 :                 test_key.field6 = blknum as u32;
    7304       200000 :                 let mut writer = tline.writer().await;
    7305       200000 :                 writer
    7306       200000 :                     .put(
    7307       200000 :                         test_key,
    7308       200000 :                         lsn,
    7309       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7310       200000 :                         &ctx,
    7311       200000 :                     )
    7312       200000 :                     .await?;
    7313       200000 :                 println!("updating {} at {}", blknum, lsn);
    7314       200000 :                 writer.finish_write(lsn);
    7315       200000 :                 drop(writer);
    7316       200000 :                 updated[blknum] = lsn;
    7317            4 :             }
    7318            4 : 
    7319            4 :             // Read all the blocks
    7320       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7321       200000 :                 test_key.field6 = blknum as u32;
    7322       200000 :                 assert_eq!(
    7323       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7324       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7325            4 :                 );
    7326            4 :             }
    7327            4 : 
    7328            4 :             // Perform a cycle of flush, compact, and GC
    7329          200 :             tline.freeze_and_flush().await?;
    7330          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7331          200 :             tenant
    7332          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7333          200 :                 .await?;
    7334            4 :         }
    7335            4 : 
    7336            4 :         Ok(())
    7337            4 :     }
    7338              : 
    7339              :     #[tokio::test]
    7340            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7341            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7342            4 :             .await?
    7343            4 :             .load()
    7344            4 :             .await;
    7345            4 :         let mut tline = tenant
    7346            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7347            4 :             .await?;
    7348            4 : 
    7349            4 :         const NUM_KEYS: usize = 100;
    7350            4 :         const NUM_TLINES: usize = 50;
    7351            4 : 
    7352            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7353            4 :         // Track page mutation lsns across different timelines.
    7354            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7355            4 : 
    7356            4 :         let mut lsn = Lsn(0x10);
    7357            4 : 
    7358            4 :         #[allow(clippy::needless_range_loop)]
    7359          204 :         for idx in 0..NUM_TLINES {
    7360          200 :             let new_tline_id = TimelineId::generate();
    7361          200 :             tenant
    7362          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7363          200 :                 .await?;
    7364          200 :             tline = tenant
    7365          200 :                 .get_timeline(new_tline_id, true)
    7366          200 :                 .expect("Should have the branched timeline");
    7367            4 : 
    7368        20200 :             for _ in 0..NUM_KEYS {
    7369        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7370        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7371        20000 :                 test_key.field6 = blknum as u32;
    7372        20000 :                 let mut writer = tline.writer().await;
    7373        20000 :                 writer
    7374        20000 :                     .put(
    7375        20000 :                         test_key,
    7376        20000 :                         lsn,
    7377        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7378        20000 :                         &ctx,
    7379        20000 :                     )
    7380        20000 :                     .await?;
    7381        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7382        20000 :                 writer.finish_write(lsn);
    7383        20000 :                 drop(writer);
    7384        20000 :                 updated[idx][blknum] = lsn;
    7385            4 :             }
    7386            4 :         }
    7387            4 : 
    7388            4 :         // Read pages from leaf timeline across all ancestors.
    7389          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7390        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7391            4 :                 // Skip empty mutations.
    7392        20000 :                 if lsn.0 == 0 {
    7393         7317 :                     continue;
    7394        12683 :                 }
    7395        12683 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7396        12683 :                 test_key.field6 = blknum as u32;
    7397        12683 :                 assert_eq!(
    7398        12683 :                     tline.get(test_key, *lsn, &ctx).await?,
    7399        12683 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7400            4 :                 );
    7401            4 :             }
    7402            4 :         }
    7403            4 :         Ok(())
    7404            4 :     }
    7405              : 
    7406              :     #[tokio::test]
    7407            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7408            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7409            4 :             .await?
    7410            4 :             .load()
    7411            4 :             .await;
    7412            4 : 
    7413            4 :         let initdb_lsn = Lsn(0x20);
    7414            4 :         let utline = tenant
    7415            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7416            4 :             .await?;
    7417            4 :         let tline = utline.raw_timeline().unwrap();
    7418            4 : 
    7419            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7420            4 :         tline.maybe_spawn_flush_loop();
    7421            4 : 
    7422            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7423            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7424            4 :         // Except if you `put` at `initdb_lsn`.
    7425            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7426            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7427            4 :         // Let's make sure the test timeline can handle that case.
    7428            4 :         {
    7429            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7430            4 :             assert_eq!(
    7431            4 :                 timeline::FlushLoopState::Running {
    7432            4 :                     expect_initdb_optimization: false,
    7433            4 :                     initdb_optimization_count: 0,
    7434            4 :                 },
    7435            4 :                 *state
    7436            4 :             );
    7437            4 :             *state = timeline::FlushLoopState::Running {
    7438            4 :                 expect_initdb_optimization: true,
    7439            4 :                 initdb_optimization_count: 0,
    7440            4 :             };
    7441            4 :         }
    7442            4 : 
    7443            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7444            4 :         // As explained above, the optimization requires some keys to be present.
    7445            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7446            4 :         // This is what `create_test_timeline` does, by the way.
    7447            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7448            4 :         modification
    7449            4 :             .init_empty_test_timeline()
    7450            4 :             .context("init_empty_test_timeline")?;
    7451            4 :         modification
    7452            4 :             .commit(&ctx)
    7453            4 :             .await
    7454            4 :             .context("commit init_empty_test_timeline modification")?;
    7455            4 : 
    7456            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7457            4 :         tline.freeze_and_flush().await?;
    7458            4 : 
    7459            4 :         // assert freeze_and_flush exercised the initdb optimization
    7460            4 :         {
    7461            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7462            4 :             let timeline::FlushLoopState::Running {
    7463            4 :                 expect_initdb_optimization,
    7464            4 :                 initdb_optimization_count,
    7465            4 :             } = *state
    7466            4 :             else {
    7467            4 :                 panic!("unexpected state: {:?}", *state);
    7468            4 :             };
    7469            4 :             assert!(expect_initdb_optimization);
    7470            4 :             assert!(initdb_optimization_count > 0);
    7471            4 :         }
    7472            4 :         Ok(())
    7473            4 :     }
    7474              : 
    7475              :     #[tokio::test]
    7476            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7477            4 :         let name = "test_create_guard_crash";
    7478            4 :         let harness = TenantHarness::create(name).await?;
    7479            4 :         {
    7480            4 :             let (tenant, ctx) = harness.load().await;
    7481            4 :             let tline = tenant
    7482            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7483            4 :                 .await?;
    7484            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7485            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7486            4 :             raw_tline
    7487            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7488            4 :                 .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))
    7489            4 :                 .await;
    7490            4 :             std::mem::forget(tline);
    7491            4 :         }
    7492            4 : 
    7493            4 :         let (tenant, _) = harness.load().await;
    7494            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7495            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7496            4 :             Err(e) => {
    7497            4 :                 assert_eq!(
    7498            4 :                     e,
    7499            4 :                     GetTimelineError::NotFound {
    7500            4 :                         tenant_id: tenant.tenant_shard_id,
    7501            4 :                         timeline_id: TIMELINE_ID,
    7502            4 :                     }
    7503            4 :                 )
    7504            4 :             }
    7505            4 :         }
    7506            4 : 
    7507            4 :         assert!(!harness
    7508            4 :             .conf
    7509            4 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7510            4 :             .exists());
    7511            4 : 
    7512            4 :         Ok(())
    7513            4 :     }
    7514              : 
    7515              :     #[tokio::test]
    7516            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7517            4 :         let names_algorithms = [
    7518            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7519            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7520            4 :         ];
    7521           12 :         for (name, algorithm) in names_algorithms {
    7522            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7523            4 :         }
    7524            4 :         Ok(())
    7525            4 :     }
    7526              : 
    7527            8 :     async fn test_read_at_max_lsn_algorithm(
    7528            8 :         name: &'static str,
    7529            8 :         compaction_algorithm: CompactionAlgorithm,
    7530            8 :     ) -> anyhow::Result<()> {
    7531            8 :         let mut harness = TenantHarness::create(name).await?;
    7532            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7533            8 :             kind: compaction_algorithm,
    7534            8 :         };
    7535            8 :         let (tenant, ctx) = harness.load().await;
    7536            8 :         let tline = tenant
    7537            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7538            8 :             .await?;
    7539              : 
    7540            8 :         let lsn = Lsn(0x10);
    7541            8 :         let compact = false;
    7542            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7543              : 
    7544            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7545            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7546              : 
    7547            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7548            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7549              : 
    7550            8 :         Ok(())
    7551            8 :     }
    7552              : 
    7553              :     #[tokio::test]
    7554            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7555            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7556            4 :         let (tenant, ctx) = harness.load().await;
    7557            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7558            4 :         let tline = tenant
    7559            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7560            4 :             .await?;
    7561            4 : 
    7562            4 :         const NUM_KEYS: usize = 1000;
    7563            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7564            4 : 
    7565            4 :         let cancel = CancellationToken::new();
    7566            4 : 
    7567            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7568            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7569            4 :         let mut test_key = base_key;
    7570            4 : 
    7571            4 :         // Track when each page was last modified. Used to assert that
    7572            4 :         // a read sees the latest page version.
    7573            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7574            4 : 
    7575            4 :         let mut lsn = Lsn(0x10);
    7576            4 :         #[allow(clippy::needless_range_loop)]
    7577         4004 :         for blknum in 0..NUM_KEYS {
    7578         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7579         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7580         4000 :             let mut writer = tline.writer().await;
    7581         4000 :             writer
    7582         4000 :                 .put(
    7583         4000 :                     test_key,
    7584         4000 :                     lsn,
    7585         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7586         4000 :                     &ctx,
    7587         4000 :                 )
    7588         4000 :                 .await?;
    7589         4000 :             writer.finish_write(lsn);
    7590         4000 :             updated[blknum] = lsn;
    7591         4000 :             drop(writer);
    7592            4 :         }
    7593            4 : 
    7594            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7595            4 : 
    7596           48 :         for iter in 0..=10 {
    7597            4 :             // Read all the blocks
    7598        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7599        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7600        44000 :                 assert_eq!(
    7601        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7602        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7603            4 :                 );
    7604            4 :             }
    7605            4 : 
    7606           44 :             let mut cnt = 0;
    7607        44000 :             for (key, value) in tline
    7608           44 :                 .get_vectored_impl(
    7609           44 :                     keyspace.clone(),
    7610           44 :                     lsn,
    7611           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7612           44 :                     &ctx,
    7613           44 :                 )
    7614           44 :                 .await?
    7615            4 :             {
    7616        44000 :                 let blknum = key.field6 as usize;
    7617        44000 :                 let value = value?;
    7618        44000 :                 assert!(blknum % STEP == 0);
    7619        44000 :                 let blknum = blknum / STEP;
    7620        44000 :                 assert_eq!(
    7621        44000 :                     value,
    7622        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7623        44000 :                 );
    7624        44000 :                 cnt += 1;
    7625            4 :             }
    7626            4 : 
    7627           44 :             assert_eq!(cnt, NUM_KEYS);
    7628            4 : 
    7629        44044 :             for _ in 0..NUM_KEYS {
    7630        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7631        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7632        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7633        44000 :                 let mut writer = tline.writer().await;
    7634        44000 :                 writer
    7635        44000 :                     .put(
    7636        44000 :                         test_key,
    7637        44000 :                         lsn,
    7638        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7639        44000 :                         &ctx,
    7640        44000 :                     )
    7641        44000 :                     .await?;
    7642        44000 :                 writer.finish_write(lsn);
    7643        44000 :                 drop(writer);
    7644        44000 :                 updated[blknum] = lsn;
    7645            4 :             }
    7646            4 : 
    7647            4 :             // Perform two cycles of flush, compact, and GC
    7648          132 :             for round in 0..2 {
    7649           88 :                 tline.freeze_and_flush().await?;
    7650           88 :                 tline
    7651           88 :                     .compact(
    7652           88 :                         &cancel,
    7653           88 :                         if iter % 5 == 0 && round == 0 {
    7654           12 :                             let mut flags = EnumSet::new();
    7655           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7656           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7657           12 :                             flags
    7658            4 :                         } else {
    7659           76 :                             EnumSet::empty()
    7660            4 :                         },
    7661           88 :                         &ctx,
    7662           88 :                     )
    7663           88 :                     .await?;
    7664           88 :                 tenant
    7665           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7666           88 :                     .await?;
    7667            4 :             }
    7668            4 :         }
    7669            4 : 
    7670            4 :         Ok(())
    7671            4 :     }
    7672              : 
    7673              :     #[tokio::test]
    7674            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7675            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7676            4 :         let (tenant, ctx) = harness.load().await;
    7677            4 :         let tline = tenant
    7678            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7679            4 :             .await?;
    7680            4 : 
    7681            4 :         let cancel = CancellationToken::new();
    7682            4 : 
    7683            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7684            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7685            4 :         let test_key = base_key;
    7686            4 :         let mut lsn = Lsn(0x10);
    7687            4 : 
    7688           84 :         for _ in 0..20 {
    7689           80 :             lsn = Lsn(lsn.0 + 0x10);
    7690           80 :             let mut writer = tline.writer().await;
    7691           80 :             writer
    7692           80 :                 .put(
    7693           80 :                     test_key,
    7694           80 :                     lsn,
    7695           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7696           80 :                     &ctx,
    7697           80 :                 )
    7698           80 :                 .await?;
    7699           80 :             writer.finish_write(lsn);
    7700           80 :             drop(writer);
    7701           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7702            4 :         }
    7703            4 : 
    7704            4 :         let before_num_l0_delta_files =
    7705            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7706            4 : 
    7707            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7708            4 : 
    7709            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7710            4 : 
    7711            4 :         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}");
    7712            4 : 
    7713            4 :         assert_eq!(
    7714            4 :             tline.get(test_key, lsn, &ctx).await?,
    7715            4 :             test_img(&format!("{} at {}", 0, lsn))
    7716            4 :         );
    7717            4 : 
    7718            4 :         Ok(())
    7719            4 :     }
    7720              : 
    7721              :     #[tokio::test]
    7722            4 :     async fn test_aux_file_e2e() {
    7723            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7724            4 : 
    7725            4 :         let (tenant, ctx) = harness.load().await;
    7726            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7727            4 : 
    7728            4 :         let mut lsn = Lsn(0x08);
    7729            4 : 
    7730            4 :         let tline: Arc<Timeline> = tenant
    7731            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7732            4 :             .await
    7733            4 :             .unwrap();
    7734            4 : 
    7735            4 :         {
    7736            4 :             lsn += 8;
    7737            4 :             let mut modification = tline.begin_modification(lsn);
    7738            4 :             modification
    7739            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7740            4 :                 .await
    7741            4 :                 .unwrap();
    7742            4 :             modification.commit(&ctx).await.unwrap();
    7743            4 :         }
    7744            4 : 
    7745            4 :         // we can read everything from the storage
    7746            4 :         let files = tline
    7747            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7748            4 :             .await
    7749            4 :             .unwrap();
    7750            4 :         assert_eq!(
    7751            4 :             files.get("pg_logical/mappings/test1"),
    7752            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7753            4 :         );
    7754            4 : 
    7755            4 :         {
    7756            4 :             lsn += 8;
    7757            4 :             let mut modification = tline.begin_modification(lsn);
    7758            4 :             modification
    7759            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7760            4 :                 .await
    7761            4 :                 .unwrap();
    7762            4 :             modification.commit(&ctx).await.unwrap();
    7763            4 :         }
    7764            4 : 
    7765            4 :         let files = tline
    7766            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7767            4 :             .await
    7768            4 :             .unwrap();
    7769            4 :         assert_eq!(
    7770            4 :             files.get("pg_logical/mappings/test2"),
    7771            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7772            4 :         );
    7773            4 : 
    7774            4 :         let child = tenant
    7775            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7776            4 :             .await
    7777            4 :             .unwrap();
    7778            4 : 
    7779            4 :         let files = child
    7780            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7781            4 :             .await
    7782            4 :             .unwrap();
    7783            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7784            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7785            4 :     }
    7786              : 
    7787              :     #[tokio::test]
    7788            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7789            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7790            4 :         let (tenant, ctx) = harness.load().await;
    7791            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7792            4 :         let tline = tenant
    7793            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7794            4 :             .await?;
    7795            4 : 
    7796            4 :         const NUM_KEYS: usize = 1000;
    7797            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7798            4 : 
    7799            4 :         let cancel = CancellationToken::new();
    7800            4 : 
    7801            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7802            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7803            4 :         let mut test_key = base_key;
    7804            4 :         let mut lsn = Lsn(0x10);
    7805            4 : 
    7806           16 :         async fn scan_with_statistics(
    7807           16 :             tline: &Timeline,
    7808           16 :             keyspace: &KeySpace,
    7809           16 :             lsn: Lsn,
    7810           16 :             ctx: &RequestContext,
    7811           16 :             io_concurrency: IoConcurrency,
    7812           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7813           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7814           16 :             let res = tline
    7815           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7816           16 :                 .await?;
    7817           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7818           16 :         }
    7819            4 : 
    7820            4 :         #[allow(clippy::needless_range_loop)]
    7821         4004 :         for blknum in 0..NUM_KEYS {
    7822         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7823         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7824         4000 :             let mut writer = tline.writer().await;
    7825         4000 :             writer
    7826         4000 :                 .put(
    7827         4000 :                     test_key,
    7828         4000 :                     lsn,
    7829         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7830         4000 :                     &ctx,
    7831         4000 :                 )
    7832         4000 :                 .await?;
    7833         4000 :             writer.finish_write(lsn);
    7834         4000 :             drop(writer);
    7835            4 :         }
    7836            4 : 
    7837            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7838            4 : 
    7839           44 :         for iter in 1..=10 {
    7840        40040 :             for _ in 0..NUM_KEYS {
    7841        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7842        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7843        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7844        40000 :                 let mut writer = tline.writer().await;
    7845        40000 :                 writer
    7846        40000 :                     .put(
    7847        40000 :                         test_key,
    7848        40000 :                         lsn,
    7849        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7850        40000 :                         &ctx,
    7851        40000 :                     )
    7852        40000 :                     .await?;
    7853        40000 :                 writer.finish_write(lsn);
    7854        40000 :                 drop(writer);
    7855            4 :             }
    7856            4 : 
    7857           40 :             tline.freeze_and_flush().await?;
    7858            4 : 
    7859           40 :             if iter % 5 == 0 {
    7860            8 :                 let (_, before_delta_file_accessed) =
    7861            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7862            8 :                         .await?;
    7863            8 :                 tline
    7864            8 :                     .compact(
    7865            8 :                         &cancel,
    7866            8 :                         {
    7867            8 :                             let mut flags = EnumSet::new();
    7868            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7869            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7870            8 :                             flags
    7871            8 :                         },
    7872            8 :                         &ctx,
    7873            8 :                     )
    7874            8 :                     .await?;
    7875            8 :                 let (_, after_delta_file_accessed) =
    7876            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7877            8 :                         .await?;
    7878            8 :                 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}");
    7879            4 :                 // 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.
    7880            8 :                 assert!(
    7881            8 :                     after_delta_file_accessed <= 2,
    7882            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7883            4 :                 );
    7884           32 :             }
    7885            4 :         }
    7886            4 : 
    7887            4 :         Ok(())
    7888            4 :     }
    7889              : 
    7890              :     #[tokio::test]
    7891            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7892            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7893            4 :         let (tenant, ctx) = harness.load().await;
    7894            4 : 
    7895            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7896            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7897            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7898            4 : 
    7899            4 :         let tline = tenant
    7900            4 :             .create_test_timeline_with_layers(
    7901            4 :                 TIMELINE_ID,
    7902            4 :                 Lsn(0x10),
    7903            4 :                 DEFAULT_PG_VERSION,
    7904            4 :                 &ctx,
    7905            4 :                 Vec::new(), // delta layers
    7906            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7907            4 :                 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
    7908            4 :             )
    7909            4 :             .await?;
    7910            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7911            4 : 
    7912            4 :         let child = tenant
    7913            4 :             .branch_timeline_test_with_layers(
    7914            4 :                 &tline,
    7915            4 :                 NEW_TIMELINE_ID,
    7916            4 :                 Some(Lsn(0x20)),
    7917            4 :                 &ctx,
    7918            4 :                 Vec::new(), // delta layers
    7919            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7920            4 :                 Lsn(0x30),
    7921            4 :             )
    7922            4 :             .await
    7923            4 :             .unwrap();
    7924            4 : 
    7925            4 :         let lsn = Lsn(0x30);
    7926            4 : 
    7927            4 :         // test vectored get on parent timeline
    7928            4 :         assert_eq!(
    7929            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7930            4 :             Some(test_img("data key 1"))
    7931            4 :         );
    7932            4 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7933            4 :             .await
    7934            4 :             .unwrap_err()
    7935            4 :             .is_missing_key_error());
    7936            4 :         assert!(
    7937            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7938            4 :                 .await
    7939            4 :                 .unwrap_err()
    7940            4 :                 .is_missing_key_error()
    7941            4 :         );
    7942            4 : 
    7943            4 :         // test vectored get on child timeline
    7944            4 :         assert_eq!(
    7945            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7946            4 :             Some(test_img("data key 1"))
    7947            4 :         );
    7948            4 :         assert_eq!(
    7949            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7950            4 :             Some(test_img("data key 2"))
    7951            4 :         );
    7952            4 :         assert!(
    7953            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7954            4 :                 .await
    7955            4 :                 .unwrap_err()
    7956            4 :                 .is_missing_key_error()
    7957            4 :         );
    7958            4 : 
    7959            4 :         Ok(())
    7960            4 :     }
    7961              : 
    7962              :     #[tokio::test]
    7963            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7964            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7965            4 :         let (tenant, ctx) = harness.load().await;
    7966            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7967            4 : 
    7968            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7969            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7970            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7971            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7972            4 : 
    7973            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    7974            4 :         let base_inherited_key_child =
    7975            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    7976            4 :         let base_inherited_key_nonexist =
    7977            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    7978            4 :         let base_inherited_key_overwrite =
    7979            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    7980            4 : 
    7981            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7982            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    7983            4 : 
    7984            4 :         let tline = tenant
    7985            4 :             .create_test_timeline_with_layers(
    7986            4 :                 TIMELINE_ID,
    7987            4 :                 Lsn(0x10),
    7988            4 :                 DEFAULT_PG_VERSION,
    7989            4 :                 &ctx,
    7990            4 :                 Vec::new(), // delta layers
    7991            4 :                 vec![(
    7992            4 :                     Lsn(0x20),
    7993            4 :                     vec![
    7994            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    7995            4 :                         (
    7996            4 :                             base_inherited_key_overwrite,
    7997            4 :                             test_img("metadata key overwrite 1a"),
    7998            4 :                         ),
    7999            4 :                         (base_key, test_img("metadata key 1")),
    8000            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8001            4 :                     ],
    8002            4 :                 )], // image layers
    8003            4 :                 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
    8004            4 :             )
    8005            4 :             .await?;
    8006            4 : 
    8007            4 :         let child = tenant
    8008            4 :             .branch_timeline_test_with_layers(
    8009            4 :                 &tline,
    8010            4 :                 NEW_TIMELINE_ID,
    8011            4 :                 Some(Lsn(0x20)),
    8012            4 :                 &ctx,
    8013            4 :                 Vec::new(), // delta layers
    8014            4 :                 vec![(
    8015            4 :                     Lsn(0x30),
    8016            4 :                     vec![
    8017            4 :                         (
    8018            4 :                             base_inherited_key_child,
    8019            4 :                             test_img("metadata inherited key 2"),
    8020            4 :                         ),
    8021            4 :                         (
    8022            4 :                             base_inherited_key_overwrite,
    8023            4 :                             test_img("metadata key overwrite 2a"),
    8024            4 :                         ),
    8025            4 :                         (base_key_child, test_img("metadata key 2")),
    8026            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8027            4 :                     ],
    8028            4 :                 )], // image layers
    8029            4 :                 Lsn(0x30),
    8030            4 :             )
    8031            4 :             .await
    8032            4 :             .unwrap();
    8033            4 : 
    8034            4 :         let lsn = Lsn(0x30);
    8035            4 : 
    8036            4 :         // test vectored get on parent timeline
    8037            4 :         assert_eq!(
    8038            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8039            4 :             Some(test_img("metadata key 1"))
    8040            4 :         );
    8041            4 :         assert_eq!(
    8042            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8043            4 :             None
    8044            4 :         );
    8045            4 :         assert_eq!(
    8046            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8047            4 :             None
    8048            4 :         );
    8049            4 :         assert_eq!(
    8050            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8051            4 :             Some(test_img("metadata key overwrite 1b"))
    8052            4 :         );
    8053            4 :         assert_eq!(
    8054            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8055            4 :             Some(test_img("metadata inherited key 1"))
    8056            4 :         );
    8057            4 :         assert_eq!(
    8058            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8059            4 :             None
    8060            4 :         );
    8061            4 :         assert_eq!(
    8062            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8063            4 :             None
    8064            4 :         );
    8065            4 :         assert_eq!(
    8066            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8067            4 :             Some(test_img("metadata key overwrite 1a"))
    8068            4 :         );
    8069            4 : 
    8070            4 :         // test vectored get on child timeline
    8071            4 :         assert_eq!(
    8072            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8073            4 :             None
    8074            4 :         );
    8075            4 :         assert_eq!(
    8076            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8077            4 :             Some(test_img("metadata key 2"))
    8078            4 :         );
    8079            4 :         assert_eq!(
    8080            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8081            4 :             None
    8082            4 :         );
    8083            4 :         assert_eq!(
    8084            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8085            4 :             Some(test_img("metadata inherited key 1"))
    8086            4 :         );
    8087            4 :         assert_eq!(
    8088            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8089            4 :             Some(test_img("metadata inherited key 2"))
    8090            4 :         );
    8091            4 :         assert_eq!(
    8092            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8093            4 :             None
    8094            4 :         );
    8095            4 :         assert_eq!(
    8096            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8097            4 :             Some(test_img("metadata key overwrite 2b"))
    8098            4 :         );
    8099            4 :         assert_eq!(
    8100            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8101            4 :             Some(test_img("metadata key overwrite 2a"))
    8102            4 :         );
    8103            4 : 
    8104            4 :         // test vectored scan on parent timeline
    8105            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8106            4 :         let res = tline
    8107            4 :             .get_vectored_impl(
    8108            4 :                 KeySpace::single(Key::metadata_key_range()),
    8109            4 :                 lsn,
    8110            4 :                 &mut reconstruct_state,
    8111            4 :                 &ctx,
    8112            4 :             )
    8113            4 :             .await?;
    8114            4 : 
    8115            4 :         assert_eq!(
    8116            4 :             res.into_iter()
    8117           16 :                 .map(|(k, v)| (k, v.unwrap()))
    8118            4 :                 .collect::<Vec<_>>(),
    8119            4 :             vec![
    8120            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8121            4 :                 (
    8122            4 :                     base_inherited_key_overwrite,
    8123            4 :                     test_img("metadata key overwrite 1a")
    8124            4 :                 ),
    8125            4 :                 (base_key, test_img("metadata key 1")),
    8126            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8127            4 :             ]
    8128            4 :         );
    8129            4 : 
    8130            4 :         // test vectored scan on child timeline
    8131            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8132            4 :         let res = child
    8133            4 :             .get_vectored_impl(
    8134            4 :                 KeySpace::single(Key::metadata_key_range()),
    8135            4 :                 lsn,
    8136            4 :                 &mut reconstruct_state,
    8137            4 :                 &ctx,
    8138            4 :             )
    8139            4 :             .await?;
    8140            4 : 
    8141            4 :         assert_eq!(
    8142            4 :             res.into_iter()
    8143           20 :                 .map(|(k, v)| (k, v.unwrap()))
    8144            4 :                 .collect::<Vec<_>>(),
    8145            4 :             vec![
    8146            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8147            4 :                 (
    8148            4 :                     base_inherited_key_child,
    8149            4 :                     test_img("metadata inherited key 2")
    8150            4 :                 ),
    8151            4 :                 (
    8152            4 :                     base_inherited_key_overwrite,
    8153            4 :                     test_img("metadata key overwrite 2a")
    8154            4 :                 ),
    8155            4 :                 (base_key_child, test_img("metadata key 2")),
    8156            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8157            4 :             ]
    8158            4 :         );
    8159            4 : 
    8160            4 :         Ok(())
    8161            4 :     }
    8162              : 
    8163          112 :     async fn get_vectored_impl_wrapper(
    8164          112 :         tline: &Arc<Timeline>,
    8165          112 :         key: Key,
    8166          112 :         lsn: Lsn,
    8167          112 :         ctx: &RequestContext,
    8168          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8169          112 :         let io_concurrency =
    8170          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8171          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8172          112 :         let mut res = tline
    8173          112 :             .get_vectored_impl(
    8174          112 :                 KeySpace::single(key..key.next()),
    8175          112 :                 lsn,
    8176          112 :                 &mut reconstruct_state,
    8177          112 :                 ctx,
    8178          112 :             )
    8179          112 :             .await?;
    8180          100 :         Ok(res.pop_last().map(|(k, v)| {
    8181           64 :             assert_eq!(k, key);
    8182           64 :             v.unwrap()
    8183          100 :         }))
    8184          112 :     }
    8185              : 
    8186              :     #[tokio::test]
    8187            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8188            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8189            4 :         let (tenant, ctx) = harness.load().await;
    8190            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8191            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8192            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8193            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8194            4 : 
    8195            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8196            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8197            4 :         // Lsn 0x20 key1+key2 tomestones
    8198            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8199            4 :         let tline = tenant
    8200            4 :             .create_test_timeline_with_layers(
    8201            4 :                 TIMELINE_ID,
    8202            4 :                 Lsn(0x10),
    8203            4 :                 DEFAULT_PG_VERSION,
    8204            4 :                 &ctx,
    8205            4 :                 // delta layers
    8206            4 :                 vec![
    8207            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8208            4 :                         Lsn(0x10)..Lsn(0x20),
    8209            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8210            4 :                     ),
    8211            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8212            4 :                         Lsn(0x20)..Lsn(0x30),
    8213            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8214            4 :                     ),
    8215            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8216            4 :                         Lsn(0x20)..Lsn(0x30),
    8217            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8218            4 :                     ),
    8219            4 :                 ],
    8220            4 :                 // image layers
    8221            4 :                 vec![
    8222            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8223            4 :                     (
    8224            4 :                         Lsn(0x30),
    8225            4 :                         vec![
    8226            4 :                             (key0, test_img("metadata key 0")),
    8227            4 :                             (key3, test_img("metadata key 3")),
    8228            4 :                         ],
    8229            4 :                     ),
    8230            4 :                 ],
    8231            4 :                 Lsn(0x30),
    8232            4 :             )
    8233            4 :             .await?;
    8234            4 : 
    8235            4 :         let lsn = Lsn(0x30);
    8236            4 :         let old_lsn = Lsn(0x20);
    8237            4 : 
    8238            4 :         assert_eq!(
    8239            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8240            4 :             Some(test_img("metadata key 0"))
    8241            4 :         );
    8242            4 :         assert_eq!(
    8243            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8244            4 :             None,
    8245            4 :         );
    8246            4 :         assert_eq!(
    8247            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8248            4 :             None,
    8249            4 :         );
    8250            4 :         assert_eq!(
    8251            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8252            4 :             Some(Bytes::new()),
    8253            4 :         );
    8254            4 :         assert_eq!(
    8255            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8256            4 :             Some(Bytes::new()),
    8257            4 :         );
    8258            4 :         assert_eq!(
    8259            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8260            4 :             Some(test_img("metadata key 3"))
    8261            4 :         );
    8262            4 : 
    8263            4 :         Ok(())
    8264            4 :     }
    8265              : 
    8266              :     #[tokio::test]
    8267            4 :     async fn test_metadata_tombstone_image_creation() {
    8268            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8269            4 :             .await
    8270            4 :             .unwrap();
    8271            4 :         let (tenant, ctx) = harness.load().await;
    8272            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8273            4 : 
    8274            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8275            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8276            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8277            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8278            4 : 
    8279            4 :         let tline = tenant
    8280            4 :             .create_test_timeline_with_layers(
    8281            4 :                 TIMELINE_ID,
    8282            4 :                 Lsn(0x10),
    8283            4 :                 DEFAULT_PG_VERSION,
    8284            4 :                 &ctx,
    8285            4 :                 // delta layers
    8286            4 :                 vec![
    8287            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8288            4 :                         Lsn(0x10)..Lsn(0x20),
    8289            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8290            4 :                     ),
    8291            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8292            4 :                         Lsn(0x20)..Lsn(0x30),
    8293            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8294            4 :                     ),
    8295            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8296            4 :                         Lsn(0x20)..Lsn(0x30),
    8297            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8298            4 :                     ),
    8299            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8300            4 :                         Lsn(0x30)..Lsn(0x40),
    8301            4 :                         vec![
    8302            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8303            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8304            4 :                         ],
    8305            4 :                     ),
    8306            4 :                 ],
    8307            4 :                 // image layers
    8308            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8309            4 :                 Lsn(0x40),
    8310            4 :             )
    8311            4 :             .await
    8312            4 :             .unwrap();
    8313            4 : 
    8314            4 :         let cancel = CancellationToken::new();
    8315            4 : 
    8316            4 :         tline
    8317            4 :             .compact(
    8318            4 :                 &cancel,
    8319            4 :                 {
    8320            4 :                     let mut flags = EnumSet::new();
    8321            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8322            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8323            4 :                     flags
    8324            4 :                 },
    8325            4 :                 &ctx,
    8326            4 :             )
    8327            4 :             .await
    8328            4 :             .unwrap();
    8329            4 : 
    8330            4 :         // Image layers are created at last_record_lsn
    8331            4 :         let images = tline
    8332            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8333            4 :             .await
    8334            4 :             .unwrap()
    8335            4 :             .into_iter()
    8336           36 :             .filter(|(k, _)| k.is_metadata_key())
    8337            4 :             .collect::<Vec<_>>();
    8338            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8339            4 :     }
    8340              : 
    8341              :     #[tokio::test]
    8342            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8343            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8344            4 :             .await
    8345            4 :             .unwrap();
    8346            4 :         let (tenant, ctx) = harness.load().await;
    8347            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8348            4 : 
    8349            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8350            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8351            4 : 
    8352            4 :         let tline = tenant
    8353            4 :             .create_test_timeline_with_layers(
    8354            4 :                 TIMELINE_ID,
    8355            4 :                 Lsn(0x10),
    8356            4 :                 DEFAULT_PG_VERSION,
    8357            4 :                 &ctx,
    8358            4 :                 // delta layers
    8359            4 :                 vec![
    8360            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8361            4 :                         Lsn(0x10)..Lsn(0x20),
    8362            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8363            4 :                     ),
    8364            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8365            4 :                         Lsn(0x20)..Lsn(0x30),
    8366            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8367            4 :                     ),
    8368            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8369            4 :                         Lsn(0x20)..Lsn(0x30),
    8370            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8371            4 :                     ),
    8372            4 :                 ],
    8373            4 :                 // image layers
    8374            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8375            4 :                 Lsn(0x30),
    8376            4 :             )
    8377            4 :             .await
    8378            4 :             .unwrap();
    8379            4 : 
    8380            4 :         let cancel = CancellationToken::new();
    8381            4 : 
    8382            4 :         tline
    8383            4 :             .compact(
    8384            4 :                 &cancel,
    8385            4 :                 {
    8386            4 :                     let mut flags = EnumSet::new();
    8387            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8388            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8389            4 :                     flags
    8390            4 :                 },
    8391            4 :                 &ctx,
    8392            4 :             )
    8393            4 :             .await
    8394            4 :             .unwrap();
    8395            4 : 
    8396            4 :         // Image layers are created at last_record_lsn
    8397            4 :         let images = tline
    8398            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8399            4 :             .await
    8400            4 :             .unwrap()
    8401            4 :             .into_iter()
    8402           28 :             .filter(|(k, _)| k.is_metadata_key())
    8403            4 :             .collect::<Vec<_>>();
    8404            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8405            4 :     }
    8406              : 
    8407              :     #[tokio::test]
    8408            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8409            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8410            4 :         let (tenant, ctx) = harness.load().await;
    8411            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8412            4 : 
    8413          204 :         fn get_key(id: u32) -> Key {
    8414          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8415          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8416          204 :             key.field6 = id;
    8417          204 :             key
    8418          204 :         }
    8419            4 : 
    8420            4 :         // We create
    8421            4 :         // - one bottom-most image layer,
    8422            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8423            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8424            4 :         // - a delta layer D3 above the horizon.
    8425            4 :         //
    8426            4 :         //                             | D3 |
    8427            4 :         //  | D1 |
    8428            4 :         // -|    |-- gc horizon -----------------
    8429            4 :         //  |    |                | D2 |
    8430            4 :         // --------- img layer ------------------
    8431            4 :         //
    8432            4 :         // What we should expact from this compaction is:
    8433            4 :         //                             | D3 |
    8434            4 :         //  | Part of D1 |
    8435            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8436            4 : 
    8437            4 :         // img layer at 0x10
    8438            4 :         let img_layer = (0..10)
    8439           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8440            4 :             .collect_vec();
    8441            4 : 
    8442            4 :         let delta1 = vec![
    8443            4 :             (
    8444            4 :                 get_key(1),
    8445            4 :                 Lsn(0x20),
    8446            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8447            4 :             ),
    8448            4 :             (
    8449            4 :                 get_key(2),
    8450            4 :                 Lsn(0x30),
    8451            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8452            4 :             ),
    8453            4 :             (
    8454            4 :                 get_key(3),
    8455            4 :                 Lsn(0x40),
    8456            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8457            4 :             ),
    8458            4 :         ];
    8459            4 :         let delta2 = vec![
    8460            4 :             (
    8461            4 :                 get_key(5),
    8462            4 :                 Lsn(0x20),
    8463            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8464            4 :             ),
    8465            4 :             (
    8466            4 :                 get_key(6),
    8467            4 :                 Lsn(0x20),
    8468            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8469            4 :             ),
    8470            4 :         ];
    8471            4 :         let delta3 = vec![
    8472            4 :             (
    8473            4 :                 get_key(8),
    8474            4 :                 Lsn(0x48),
    8475            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8476            4 :             ),
    8477            4 :             (
    8478            4 :                 get_key(9),
    8479            4 :                 Lsn(0x48),
    8480            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8481            4 :             ),
    8482            4 :         ];
    8483            4 : 
    8484            4 :         let tline = tenant
    8485            4 :             .create_test_timeline_with_layers(
    8486            4 :                 TIMELINE_ID,
    8487            4 :                 Lsn(0x10),
    8488            4 :                 DEFAULT_PG_VERSION,
    8489            4 :                 &ctx,
    8490            4 :                 vec![
    8491            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8492            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8493            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8494            4 :                 ], // delta layers
    8495            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8496            4 :                 Lsn(0x50),
    8497            4 :             )
    8498            4 :             .await?;
    8499            4 :         {
    8500            4 :             tline
    8501            4 :                 .applied_gc_cutoff_lsn
    8502            4 :                 .lock_for_write()
    8503            4 :                 .store_and_unlock(Lsn(0x30))
    8504            4 :                 .wait()
    8505            4 :                 .await;
    8506            4 :             // Update GC info
    8507            4 :             let mut guard = tline.gc_info.write().unwrap();
    8508            4 :             guard.cutoffs.time = Lsn(0x30);
    8509            4 :             guard.cutoffs.space = Lsn(0x30);
    8510            4 :         }
    8511            4 : 
    8512            4 :         let expected_result = [
    8513            4 :             Bytes::from_static(b"value 0@0x10"),
    8514            4 :             Bytes::from_static(b"value 1@0x20"),
    8515            4 :             Bytes::from_static(b"value 2@0x30"),
    8516            4 :             Bytes::from_static(b"value 3@0x40"),
    8517            4 :             Bytes::from_static(b"value 4@0x10"),
    8518            4 :             Bytes::from_static(b"value 5@0x20"),
    8519            4 :             Bytes::from_static(b"value 6@0x20"),
    8520            4 :             Bytes::from_static(b"value 7@0x10"),
    8521            4 :             Bytes::from_static(b"value 8@0x48"),
    8522            4 :             Bytes::from_static(b"value 9@0x48"),
    8523            4 :         ];
    8524            4 : 
    8525           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8526           40 :             assert_eq!(
    8527           40 :                 tline
    8528           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8529           40 :                     .await
    8530           40 :                     .unwrap(),
    8531            4 :                 expected
    8532            4 :             );
    8533            4 :         }
    8534            4 : 
    8535            4 :         let cancel = CancellationToken::new();
    8536            4 :         tline
    8537            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8538            4 :             .await
    8539            4 :             .unwrap();
    8540            4 : 
    8541           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8542           40 :             assert_eq!(
    8543           40 :                 tline
    8544           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8545           40 :                     .await
    8546           40 :                     .unwrap(),
    8547            4 :                 expected
    8548            4 :             );
    8549            4 :         }
    8550            4 : 
    8551            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8552            4 :         let image_at_gc_horizon = tline
    8553            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8554            4 :             .await
    8555            4 :             .unwrap()
    8556            4 :             .into_iter()
    8557           68 :             .filter(|(k, _)| k.is_metadata_key())
    8558            4 :             .collect::<Vec<_>>();
    8559            4 : 
    8560            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8561            4 :         let expected_result = [
    8562            4 :             Bytes::from_static(b"value 0@0x10"),
    8563            4 :             Bytes::from_static(b"value 1@0x20"),
    8564            4 :             Bytes::from_static(b"value 2@0x30"),
    8565            4 :             Bytes::from_static(b"value 3@0x10"),
    8566            4 :             Bytes::from_static(b"value 4@0x10"),
    8567            4 :             Bytes::from_static(b"value 5@0x20"),
    8568            4 :             Bytes::from_static(b"value 6@0x20"),
    8569            4 :             Bytes::from_static(b"value 7@0x10"),
    8570            4 :             Bytes::from_static(b"value 8@0x10"),
    8571            4 :             Bytes::from_static(b"value 9@0x10"),
    8572            4 :         ];
    8573           44 :         for idx in 0..10 {
    8574           40 :             assert_eq!(
    8575           40 :                 image_at_gc_horizon[idx],
    8576           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8577           40 :             );
    8578            4 :         }
    8579            4 : 
    8580            4 :         // Check if old layers are removed / new layers have the expected LSN
    8581            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8582            4 :         assert_eq!(
    8583            4 :             all_layers,
    8584            4 :             vec![
    8585            4 :                 // Image layer at GC horizon
    8586            4 :                 PersistentLayerKey {
    8587            4 :                     key_range: Key::MIN..Key::MAX,
    8588            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8589            4 :                     is_delta: false
    8590            4 :                 },
    8591            4 :                 // The delta layer below the horizon
    8592            4 :                 PersistentLayerKey {
    8593            4 :                     key_range: get_key(3)..get_key(4),
    8594            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8595            4 :                     is_delta: true
    8596            4 :                 },
    8597            4 :                 // The delta3 layer that should not be picked for the compaction
    8598            4 :                 PersistentLayerKey {
    8599            4 :                     key_range: get_key(8)..get_key(10),
    8600            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8601            4 :                     is_delta: true
    8602            4 :                 }
    8603            4 :             ]
    8604            4 :         );
    8605            4 : 
    8606            4 :         // increase GC horizon and compact again
    8607            4 :         {
    8608            4 :             tline
    8609            4 :                 .applied_gc_cutoff_lsn
    8610            4 :                 .lock_for_write()
    8611            4 :                 .store_and_unlock(Lsn(0x40))
    8612            4 :                 .wait()
    8613            4 :                 .await;
    8614            4 :             // Update GC info
    8615            4 :             let mut guard = tline.gc_info.write().unwrap();
    8616            4 :             guard.cutoffs.time = Lsn(0x40);
    8617            4 :             guard.cutoffs.space = Lsn(0x40);
    8618            4 :         }
    8619            4 :         tline
    8620            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8621            4 :             .await
    8622            4 :             .unwrap();
    8623            4 : 
    8624            4 :         Ok(())
    8625            4 :     }
    8626              : 
    8627              :     #[cfg(feature = "testing")]
    8628              :     #[tokio::test]
    8629            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8630            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8631            4 :         let (tenant, ctx) = harness.load().await;
    8632            4 : 
    8633           48 :         fn get_key(id: u32) -> Key {
    8634           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8635           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8636           48 :             key.field6 = id;
    8637           48 :             key
    8638           48 :         }
    8639            4 : 
    8640            4 :         let delta1 = vec![
    8641            4 :             (
    8642            4 :                 get_key(1),
    8643            4 :                 Lsn(0x20),
    8644            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8645            4 :             ),
    8646            4 :             (
    8647            4 :                 get_key(1),
    8648            4 :                 Lsn(0x30),
    8649            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8650            4 :             ),
    8651            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8652            4 :             (
    8653            4 :                 get_key(2),
    8654            4 :                 Lsn(0x20),
    8655            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8656            4 :             ),
    8657            4 :             (
    8658            4 :                 get_key(2),
    8659            4 :                 Lsn(0x30),
    8660            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8661            4 :             ),
    8662            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8663            4 :             (
    8664            4 :                 get_key(3),
    8665            4 :                 Lsn(0x20),
    8666            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8667            4 :             ),
    8668            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8669            4 :             (
    8670            4 :                 get_key(4),
    8671            4 :                 Lsn(0x20),
    8672            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8673            4 :             ),
    8674            4 :         ];
    8675            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8676            4 : 
    8677            4 :         let tline = tenant
    8678            4 :             .create_test_timeline_with_layers(
    8679            4 :                 TIMELINE_ID,
    8680            4 :                 Lsn(0x10),
    8681            4 :                 DEFAULT_PG_VERSION,
    8682            4 :                 &ctx,
    8683            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8684            4 :                     Lsn(0x10)..Lsn(0x40),
    8685            4 :                     delta1,
    8686            4 :                 )], // delta layers
    8687            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8688            4 :                 Lsn(0x50),
    8689            4 :             )
    8690            4 :             .await?;
    8691            4 : 
    8692            4 :         assert_eq!(
    8693            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8694            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8695            4 :         );
    8696            4 :         assert_eq!(
    8697            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8698            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8699            4 :         );
    8700            4 : 
    8701            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8702            4 : 
    8703            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8704            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8705            4 : 
    8706            4 :         Ok(())
    8707            4 :     }
    8708              : 
    8709              :     #[tokio::test(start_paused = true)]
    8710            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8711            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8712            4 :             .await
    8713            4 :             .unwrap()
    8714            4 :             .load()
    8715            4 :             .await;
    8716            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8717            4 :         // initial transition into AttachedSingle.
    8718            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8719            4 :         tokio::time::resume();
    8720            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8721            4 : 
    8722            4 :         let end_lsn = Lsn(0x100);
    8723            4 :         let image_layers = (0x20..=0x90)
    8724            4 :             .step_by(0x10)
    8725           32 :             .map(|n| {
    8726           32 :                 (
    8727           32 :                     Lsn(n),
    8728           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8729           32 :                 )
    8730           32 :             })
    8731            4 :             .collect();
    8732            4 : 
    8733            4 :         let timeline = tenant
    8734            4 :             .create_test_timeline_with_layers(
    8735            4 :                 TIMELINE_ID,
    8736            4 :                 Lsn(0x10),
    8737            4 :                 DEFAULT_PG_VERSION,
    8738            4 :                 &ctx,
    8739            4 :                 Vec::new(),
    8740            4 :                 image_layers,
    8741            4 :                 end_lsn,
    8742            4 :             )
    8743            4 :             .await?;
    8744            4 : 
    8745            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8746            4 :         let mut leases = Vec::new();
    8747           12 :         leased_lsns.iter().for_each(|n| {
    8748           12 :             leases.push(
    8749           12 :                 timeline
    8750           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8751           12 :                     .expect("lease request should succeed"),
    8752           12 :             );
    8753           12 :         });
    8754            4 : 
    8755            4 :         let updated_lease_0 = timeline
    8756            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8757            4 :             .expect("lease renewal should succeed");
    8758            4 :         assert_eq!(
    8759            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8760            4 :             " Renewing with shorter lease should not change the lease."
    8761            4 :         );
    8762            4 : 
    8763            4 :         let updated_lease_1 = timeline
    8764            4 :             .renew_lsn_lease(
    8765            4 :                 Lsn(leased_lsns[1]),
    8766            4 :                 timeline.get_lsn_lease_length() * 2,
    8767            4 :                 &ctx,
    8768            4 :             )
    8769            4 :             .expect("lease renewal should succeed");
    8770            4 :         assert!(
    8771            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8772            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8773            4 :         );
    8774            4 : 
    8775            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8776            4 :         info!(
    8777            4 :             "applied_gc_cutoff_lsn: {}",
    8778            0 :             *timeline.get_applied_gc_cutoff_lsn()
    8779            4 :         );
    8780            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8781            4 : 
    8782            4 :         let res = tenant
    8783            4 :             .gc_iteration(
    8784            4 :                 Some(TIMELINE_ID),
    8785            4 :                 0,
    8786            4 :                 Duration::ZERO,
    8787            4 :                 &CancellationToken::new(),
    8788            4 :                 &ctx,
    8789            4 :             )
    8790            4 :             .await
    8791            4 :             .unwrap();
    8792            4 : 
    8793            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8794            4 :         // 0/10: initdb layer
    8795            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8796            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8797            4 :         // Keeping 0/90 b/c it is the latest layer.
    8798            4 :         assert_eq!(res.layers_not_updated, 1);
    8799            4 :         // Removed 0/80.
    8800            4 :         assert_eq!(res.layers_removed, 1);
    8801            4 : 
    8802            4 :         // Make lease on a already GC-ed LSN.
    8803            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8804            4 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    8805            4 :         timeline
    8806            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8807            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8808            4 : 
    8809            4 :         // Should still be able to renew a currently valid lease
    8810            4 :         // Assumption: original lease to is still valid for 0/50.
    8811            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8812            4 :         timeline
    8813            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8814            4 :             .expect("lease renewal with validation should succeed");
    8815            4 : 
    8816            4 :         Ok(())
    8817            4 :     }
    8818              : 
    8819              :     #[cfg(feature = "testing")]
    8820              :     #[tokio::test]
    8821            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8822            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8823            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8824            4 :             false,
    8825            4 :         )
    8826            4 :         .await
    8827            4 :     }
    8828              : 
    8829              :     #[cfg(feature = "testing")]
    8830              :     #[tokio::test]
    8831            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8832            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8833            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8834            4 :             true,
    8835            4 :         )
    8836            4 :         .await
    8837            4 :     }
    8838              : 
    8839              :     #[cfg(feature = "testing")]
    8840            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8841            8 :         test_name: &'static str,
    8842            8 :         use_delta_bottom_layer: bool,
    8843            8 :     ) -> anyhow::Result<()> {
    8844            8 :         let harness = TenantHarness::create(test_name).await?;
    8845            8 :         let (tenant, ctx) = harness.load().await;
    8846              : 
    8847          552 :         fn get_key(id: u32) -> Key {
    8848          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8849          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8850          552 :             key.field6 = id;
    8851          552 :             key
    8852          552 :         }
    8853              : 
    8854              :         // We create
    8855              :         // - one bottom-most image layer,
    8856              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8857              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8858              :         // - a delta layer D3 above the horizon.
    8859              :         //
    8860              :         //                             | D3 |
    8861              :         //  | D1 |
    8862              :         // -|    |-- gc horizon -----------------
    8863              :         //  |    |                | D2 |
    8864              :         // --------- img layer ------------------
    8865              :         //
    8866              :         // What we should expact from this compaction is:
    8867              :         //                             | D3 |
    8868              :         //  | Part of D1 |
    8869              :         // --------- img layer with D1+D2 at GC horizon------------------
    8870              : 
    8871              :         // img layer at 0x10
    8872            8 :         let img_layer = (0..10)
    8873           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8874            8 :             .collect_vec();
    8875            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8876            8 :         let delta4 = (0..10)
    8877           80 :             .map(|id| {
    8878           80 :                 (
    8879           80 :                     get_key(id),
    8880           80 :                     Lsn(0x08),
    8881           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8882           80 :                 )
    8883           80 :             })
    8884            8 :             .collect_vec();
    8885            8 : 
    8886            8 :         let delta1 = vec![
    8887            8 :             (
    8888            8 :                 get_key(1),
    8889            8 :                 Lsn(0x20),
    8890            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8891            8 :             ),
    8892            8 :             (
    8893            8 :                 get_key(2),
    8894            8 :                 Lsn(0x30),
    8895            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8896            8 :             ),
    8897            8 :             (
    8898            8 :                 get_key(3),
    8899            8 :                 Lsn(0x28),
    8900            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8901            8 :             ),
    8902            8 :             (
    8903            8 :                 get_key(3),
    8904            8 :                 Lsn(0x30),
    8905            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8906            8 :             ),
    8907            8 :             (
    8908            8 :                 get_key(3),
    8909            8 :                 Lsn(0x40),
    8910            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8911            8 :             ),
    8912            8 :         ];
    8913            8 :         let delta2 = vec![
    8914            8 :             (
    8915            8 :                 get_key(5),
    8916            8 :                 Lsn(0x20),
    8917            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8918            8 :             ),
    8919            8 :             (
    8920            8 :                 get_key(6),
    8921            8 :                 Lsn(0x20),
    8922            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8923            8 :             ),
    8924            8 :         ];
    8925            8 :         let delta3 = vec![
    8926            8 :             (
    8927            8 :                 get_key(8),
    8928            8 :                 Lsn(0x48),
    8929            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8930            8 :             ),
    8931            8 :             (
    8932            8 :                 get_key(9),
    8933            8 :                 Lsn(0x48),
    8934            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8935            8 :             ),
    8936            8 :         ];
    8937              : 
    8938            8 :         let tline = if use_delta_bottom_layer {
    8939            4 :             tenant
    8940            4 :                 .create_test_timeline_with_layers(
    8941            4 :                     TIMELINE_ID,
    8942            4 :                     Lsn(0x08),
    8943            4 :                     DEFAULT_PG_VERSION,
    8944            4 :                     &ctx,
    8945            4 :                     vec![
    8946            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8947            4 :                             Lsn(0x08)..Lsn(0x10),
    8948            4 :                             delta4,
    8949            4 :                         ),
    8950            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8951            4 :                             Lsn(0x20)..Lsn(0x48),
    8952            4 :                             delta1,
    8953            4 :                         ),
    8954            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8955            4 :                             Lsn(0x20)..Lsn(0x48),
    8956            4 :                             delta2,
    8957            4 :                         ),
    8958            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8959            4 :                             Lsn(0x48)..Lsn(0x50),
    8960            4 :                             delta3,
    8961            4 :                         ),
    8962            4 :                     ], // delta layers
    8963            4 :                     vec![], // image layers
    8964            4 :                     Lsn(0x50),
    8965            4 :                 )
    8966            4 :                 .await?
    8967              :         } else {
    8968            4 :             tenant
    8969            4 :                 .create_test_timeline_with_layers(
    8970            4 :                     TIMELINE_ID,
    8971            4 :                     Lsn(0x10),
    8972            4 :                     DEFAULT_PG_VERSION,
    8973            4 :                     &ctx,
    8974            4 :                     vec![
    8975            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8976            4 :                             Lsn(0x10)..Lsn(0x48),
    8977            4 :                             delta1,
    8978            4 :                         ),
    8979            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8980            4 :                             Lsn(0x10)..Lsn(0x48),
    8981            4 :                             delta2,
    8982            4 :                         ),
    8983            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8984            4 :                             Lsn(0x48)..Lsn(0x50),
    8985            4 :                             delta3,
    8986            4 :                         ),
    8987            4 :                     ], // delta layers
    8988            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8989            4 :                     Lsn(0x50),
    8990            4 :                 )
    8991            4 :                 .await?
    8992              :         };
    8993              :         {
    8994            8 :             tline
    8995            8 :                 .applied_gc_cutoff_lsn
    8996            8 :                 .lock_for_write()
    8997            8 :                 .store_and_unlock(Lsn(0x30))
    8998            8 :                 .wait()
    8999            8 :                 .await;
    9000              :             // Update GC info
    9001            8 :             let mut guard = tline.gc_info.write().unwrap();
    9002            8 :             *guard = GcInfo {
    9003            8 :                 retain_lsns: vec![],
    9004            8 :                 cutoffs: GcCutoffs {
    9005            8 :                     time: Lsn(0x30),
    9006            8 :                     space: Lsn(0x30),
    9007            8 :                 },
    9008            8 :                 leases: Default::default(),
    9009            8 :                 within_ancestor_pitr: false,
    9010            8 :             };
    9011            8 :         }
    9012            8 : 
    9013            8 :         let expected_result = [
    9014            8 :             Bytes::from_static(b"value 0@0x10"),
    9015            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9016            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9017            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9018            8 :             Bytes::from_static(b"value 4@0x10"),
    9019            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9020            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9021            8 :             Bytes::from_static(b"value 7@0x10"),
    9022            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9023            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9024            8 :         ];
    9025            8 : 
    9026            8 :         let expected_result_at_gc_horizon = [
    9027            8 :             Bytes::from_static(b"value 0@0x10"),
    9028            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9029            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9030            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9031            8 :             Bytes::from_static(b"value 4@0x10"),
    9032            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9033            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9034            8 :             Bytes::from_static(b"value 7@0x10"),
    9035            8 :             Bytes::from_static(b"value 8@0x10"),
    9036            8 :             Bytes::from_static(b"value 9@0x10"),
    9037            8 :         ];
    9038              : 
    9039           88 :         for idx in 0..10 {
    9040           80 :             assert_eq!(
    9041           80 :                 tline
    9042           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9043           80 :                     .await
    9044           80 :                     .unwrap(),
    9045           80 :                 &expected_result[idx]
    9046              :             );
    9047           80 :             assert_eq!(
    9048           80 :                 tline
    9049           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9050           80 :                     .await
    9051           80 :                     .unwrap(),
    9052           80 :                 &expected_result_at_gc_horizon[idx]
    9053              :             );
    9054              :         }
    9055              : 
    9056            8 :         let cancel = CancellationToken::new();
    9057            8 :         tline
    9058            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9059            8 :             .await
    9060            8 :             .unwrap();
    9061              : 
    9062           88 :         for idx in 0..10 {
    9063           80 :             assert_eq!(
    9064           80 :                 tline
    9065           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9066           80 :                     .await
    9067           80 :                     .unwrap(),
    9068           80 :                 &expected_result[idx]
    9069              :             );
    9070           80 :             assert_eq!(
    9071           80 :                 tline
    9072           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9073           80 :                     .await
    9074           80 :                     .unwrap(),
    9075           80 :                 &expected_result_at_gc_horizon[idx]
    9076              :             );
    9077              :         }
    9078              : 
    9079              :         // increase GC horizon and compact again
    9080              :         {
    9081            8 :             tline
    9082            8 :                 .applied_gc_cutoff_lsn
    9083            8 :                 .lock_for_write()
    9084            8 :                 .store_and_unlock(Lsn(0x40))
    9085            8 :                 .wait()
    9086            8 :                 .await;
    9087              :             // Update GC info
    9088            8 :             let mut guard = tline.gc_info.write().unwrap();
    9089            8 :             guard.cutoffs.time = Lsn(0x40);
    9090            8 :             guard.cutoffs.space = Lsn(0x40);
    9091            8 :         }
    9092            8 :         tline
    9093            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9094            8 :             .await
    9095            8 :             .unwrap();
    9096            8 : 
    9097            8 :         Ok(())
    9098            8 :     }
    9099              : 
    9100              :     #[cfg(feature = "testing")]
    9101              :     #[tokio::test]
    9102            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9103            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9104            4 :         let (tenant, ctx) = harness.load().await;
    9105            4 :         let tline = tenant
    9106            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9107            4 :             .await?;
    9108            4 :         tline.force_advance_lsn(Lsn(0x70));
    9109            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9110            4 :         let history = vec![
    9111            4 :             (
    9112            4 :                 key,
    9113            4 :                 Lsn(0x10),
    9114            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9115            4 :             ),
    9116            4 :             (
    9117            4 :                 key,
    9118            4 :                 Lsn(0x20),
    9119            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9120            4 :             ),
    9121            4 :             (
    9122            4 :                 key,
    9123            4 :                 Lsn(0x30),
    9124            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9125            4 :             ),
    9126            4 :             (
    9127            4 :                 key,
    9128            4 :                 Lsn(0x40),
    9129            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9130            4 :             ),
    9131            4 :             (
    9132            4 :                 key,
    9133            4 :                 Lsn(0x50),
    9134            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9135            4 :             ),
    9136            4 :             (
    9137            4 :                 key,
    9138            4 :                 Lsn(0x60),
    9139            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9140            4 :             ),
    9141            4 :             (
    9142            4 :                 key,
    9143            4 :                 Lsn(0x70),
    9144            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9145            4 :             ),
    9146            4 :             (
    9147            4 :                 key,
    9148            4 :                 Lsn(0x80),
    9149            4 :                 Value::Image(Bytes::copy_from_slice(
    9150            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9151            4 :                 )),
    9152            4 :             ),
    9153            4 :             (
    9154            4 :                 key,
    9155            4 :                 Lsn(0x90),
    9156            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9157            4 :             ),
    9158            4 :         ];
    9159            4 :         let res = tline
    9160            4 :             .generate_key_retention(
    9161            4 :                 key,
    9162            4 :                 &history,
    9163            4 :                 Lsn(0x60),
    9164            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9165            4 :                 3,
    9166            4 :                 None,
    9167            4 :             )
    9168            4 :             .await
    9169            4 :             .unwrap();
    9170            4 :         let expected_res = KeyHistoryRetention {
    9171            4 :             below_horizon: vec![
    9172            4 :                 (
    9173            4 :                     Lsn(0x20),
    9174            4 :                     KeyLogAtLsn(vec![(
    9175            4 :                         Lsn(0x20),
    9176            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9177            4 :                     )]),
    9178            4 :                 ),
    9179            4 :                 (
    9180            4 :                     Lsn(0x40),
    9181            4 :                     KeyLogAtLsn(vec![
    9182            4 :                         (
    9183            4 :                             Lsn(0x30),
    9184            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9185            4 :                         ),
    9186            4 :                         (
    9187            4 :                             Lsn(0x40),
    9188            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9189            4 :                         ),
    9190            4 :                     ]),
    9191            4 :                 ),
    9192            4 :                 (
    9193            4 :                     Lsn(0x50),
    9194            4 :                     KeyLogAtLsn(vec![(
    9195            4 :                         Lsn(0x50),
    9196            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9197            4 :                     )]),
    9198            4 :                 ),
    9199            4 :                 (
    9200            4 :                     Lsn(0x60),
    9201            4 :                     KeyLogAtLsn(vec![(
    9202            4 :                         Lsn(0x60),
    9203            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9204            4 :                     )]),
    9205            4 :                 ),
    9206            4 :             ],
    9207            4 :             above_horizon: KeyLogAtLsn(vec![
    9208            4 :                 (
    9209            4 :                     Lsn(0x70),
    9210            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9211            4 :                 ),
    9212            4 :                 (
    9213            4 :                     Lsn(0x80),
    9214            4 :                     Value::Image(Bytes::copy_from_slice(
    9215            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9216            4 :                     )),
    9217            4 :                 ),
    9218            4 :                 (
    9219            4 :                     Lsn(0x90),
    9220            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9221            4 :                 ),
    9222            4 :             ]),
    9223            4 :         };
    9224            4 :         assert_eq!(res, expected_res);
    9225            4 : 
    9226            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9227            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9228            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9229            4 :         // For example, we have
    9230            4 :         // ```plain
    9231            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9232            4 :         // ```
    9233            4 :         // Now the GC horizon moves up, and we have
    9234            4 :         // ```plain
    9235            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9236            4 :         // ```
    9237            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9238            4 :         // We will end up with
    9239            4 :         // ```plain
    9240            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9241            4 :         // ```
    9242            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9243            4 :         // We should be able to handle this partial history and drop everything before the
    9244            4 :         // gc_horizon image.
    9245            4 : 
    9246            4 :         let history = vec![
    9247            4 :             (
    9248            4 :                 key,
    9249            4 :                 Lsn(0x20),
    9250            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9251            4 :             ),
    9252            4 :             (
    9253            4 :                 key,
    9254            4 :                 Lsn(0x30),
    9255            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9256            4 :             ),
    9257            4 :             (
    9258            4 :                 key,
    9259            4 :                 Lsn(0x40),
    9260            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9261            4 :             ),
    9262            4 :             (
    9263            4 :                 key,
    9264            4 :                 Lsn(0x50),
    9265            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9266            4 :             ),
    9267            4 :             (
    9268            4 :                 key,
    9269            4 :                 Lsn(0x60),
    9270            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9271            4 :             ),
    9272            4 :             (
    9273            4 :                 key,
    9274            4 :                 Lsn(0x70),
    9275            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9276            4 :             ),
    9277            4 :             (
    9278            4 :                 key,
    9279            4 :                 Lsn(0x80),
    9280            4 :                 Value::Image(Bytes::copy_from_slice(
    9281            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9282            4 :                 )),
    9283            4 :             ),
    9284            4 :             (
    9285            4 :                 key,
    9286            4 :                 Lsn(0x90),
    9287            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9288            4 :             ),
    9289            4 :         ];
    9290            4 :         let res = tline
    9291            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9292            4 :             .await
    9293            4 :             .unwrap();
    9294            4 :         let expected_res = KeyHistoryRetention {
    9295            4 :             below_horizon: vec![
    9296            4 :                 (
    9297            4 :                     Lsn(0x40),
    9298            4 :                     KeyLogAtLsn(vec![(
    9299            4 :                         Lsn(0x40),
    9300            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9301            4 :                     )]),
    9302            4 :                 ),
    9303            4 :                 (
    9304            4 :                     Lsn(0x50),
    9305            4 :                     KeyLogAtLsn(vec![(
    9306            4 :                         Lsn(0x50),
    9307            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9308            4 :                     )]),
    9309            4 :                 ),
    9310            4 :                 (
    9311            4 :                     Lsn(0x60),
    9312            4 :                     KeyLogAtLsn(vec![(
    9313            4 :                         Lsn(0x60),
    9314            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9315            4 :                     )]),
    9316            4 :                 ),
    9317            4 :             ],
    9318            4 :             above_horizon: KeyLogAtLsn(vec![
    9319            4 :                 (
    9320            4 :                     Lsn(0x70),
    9321            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9322            4 :                 ),
    9323            4 :                 (
    9324            4 :                     Lsn(0x80),
    9325            4 :                     Value::Image(Bytes::copy_from_slice(
    9326            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9327            4 :                     )),
    9328            4 :                 ),
    9329            4 :                 (
    9330            4 :                     Lsn(0x90),
    9331            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9332            4 :                 ),
    9333            4 :             ]),
    9334            4 :         };
    9335            4 :         assert_eq!(res, expected_res);
    9336            4 : 
    9337            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9338            4 :         // the ancestor image in the test case.
    9339            4 : 
    9340            4 :         let history = vec![
    9341            4 :             (
    9342            4 :                 key,
    9343            4 :                 Lsn(0x20),
    9344            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9345            4 :             ),
    9346            4 :             (
    9347            4 :                 key,
    9348            4 :                 Lsn(0x30),
    9349            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9350            4 :             ),
    9351            4 :             (
    9352            4 :                 key,
    9353            4 :                 Lsn(0x40),
    9354            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9355            4 :             ),
    9356            4 :             (
    9357            4 :                 key,
    9358            4 :                 Lsn(0x70),
    9359            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9360            4 :             ),
    9361            4 :         ];
    9362            4 :         let res = tline
    9363            4 :             .generate_key_retention(
    9364            4 :                 key,
    9365            4 :                 &history,
    9366            4 :                 Lsn(0x60),
    9367            4 :                 &[],
    9368            4 :                 3,
    9369            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9370            4 :             )
    9371            4 :             .await
    9372            4 :             .unwrap();
    9373            4 :         let expected_res = KeyHistoryRetention {
    9374            4 :             below_horizon: vec![(
    9375            4 :                 Lsn(0x60),
    9376            4 :                 KeyLogAtLsn(vec![(
    9377            4 :                     Lsn(0x60),
    9378            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9379            4 :                 )]),
    9380            4 :             )],
    9381            4 :             above_horizon: KeyLogAtLsn(vec![(
    9382            4 :                 Lsn(0x70),
    9383            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9384            4 :             )]),
    9385            4 :         };
    9386            4 :         assert_eq!(res, expected_res);
    9387            4 : 
    9388            4 :         let history = vec![
    9389            4 :             (
    9390            4 :                 key,
    9391            4 :                 Lsn(0x20),
    9392            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9393            4 :             ),
    9394            4 :             (
    9395            4 :                 key,
    9396            4 :                 Lsn(0x40),
    9397            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9398            4 :             ),
    9399            4 :             (
    9400            4 :                 key,
    9401            4 :                 Lsn(0x60),
    9402            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9403            4 :             ),
    9404            4 :             (
    9405            4 :                 key,
    9406            4 :                 Lsn(0x70),
    9407            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9408            4 :             ),
    9409            4 :         ];
    9410            4 :         let res = tline
    9411            4 :             .generate_key_retention(
    9412            4 :                 key,
    9413            4 :                 &history,
    9414            4 :                 Lsn(0x60),
    9415            4 :                 &[Lsn(0x30)],
    9416            4 :                 3,
    9417            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9418            4 :             )
    9419            4 :             .await
    9420            4 :             .unwrap();
    9421            4 :         let expected_res = KeyHistoryRetention {
    9422            4 :             below_horizon: vec![
    9423            4 :                 (
    9424            4 :                     Lsn(0x30),
    9425            4 :                     KeyLogAtLsn(vec![(
    9426            4 :                         Lsn(0x20),
    9427            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9428            4 :                     )]),
    9429            4 :                 ),
    9430            4 :                 (
    9431            4 :                     Lsn(0x60),
    9432            4 :                     KeyLogAtLsn(vec![(
    9433            4 :                         Lsn(0x60),
    9434            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9435            4 :                     )]),
    9436            4 :                 ),
    9437            4 :             ],
    9438            4 :             above_horizon: KeyLogAtLsn(vec![(
    9439            4 :                 Lsn(0x70),
    9440            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9441            4 :             )]),
    9442            4 :         };
    9443            4 :         assert_eq!(res, expected_res);
    9444            4 : 
    9445            4 :         Ok(())
    9446            4 :     }
    9447              : 
    9448              :     #[cfg(feature = "testing")]
    9449              :     #[tokio::test]
    9450            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9451            4 :         let harness =
    9452            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9453            4 :         let (tenant, ctx) = harness.load().await;
    9454            4 : 
    9455         1036 :         fn get_key(id: u32) -> Key {
    9456         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9457         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9458         1036 :             key.field6 = id;
    9459         1036 :             key
    9460         1036 :         }
    9461            4 : 
    9462            4 :         let img_layer = (0..10)
    9463           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9464            4 :             .collect_vec();
    9465            4 : 
    9466            4 :         let delta1 = vec![
    9467            4 :             (
    9468            4 :                 get_key(1),
    9469            4 :                 Lsn(0x20),
    9470            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9471            4 :             ),
    9472            4 :             (
    9473            4 :                 get_key(2),
    9474            4 :                 Lsn(0x30),
    9475            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9476            4 :             ),
    9477            4 :             (
    9478            4 :                 get_key(3),
    9479            4 :                 Lsn(0x28),
    9480            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9481            4 :             ),
    9482            4 :             (
    9483            4 :                 get_key(3),
    9484            4 :                 Lsn(0x30),
    9485            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9486            4 :             ),
    9487            4 :             (
    9488            4 :                 get_key(3),
    9489            4 :                 Lsn(0x40),
    9490            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9491            4 :             ),
    9492            4 :         ];
    9493            4 :         let delta2 = vec![
    9494            4 :             (
    9495            4 :                 get_key(5),
    9496            4 :                 Lsn(0x20),
    9497            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9498            4 :             ),
    9499            4 :             (
    9500            4 :                 get_key(6),
    9501            4 :                 Lsn(0x20),
    9502            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9503            4 :             ),
    9504            4 :         ];
    9505            4 :         let delta3 = vec![
    9506            4 :             (
    9507            4 :                 get_key(8),
    9508            4 :                 Lsn(0x48),
    9509            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9510            4 :             ),
    9511            4 :             (
    9512            4 :                 get_key(9),
    9513            4 :                 Lsn(0x48),
    9514            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9515            4 :             ),
    9516            4 :         ];
    9517            4 : 
    9518            4 :         let tline = tenant
    9519            4 :             .create_test_timeline_with_layers(
    9520            4 :                 TIMELINE_ID,
    9521            4 :                 Lsn(0x10),
    9522            4 :                 DEFAULT_PG_VERSION,
    9523            4 :                 &ctx,
    9524            4 :                 vec![
    9525            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9526            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9527            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9528            4 :                 ], // delta layers
    9529            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9530            4 :                 Lsn(0x50),
    9531            4 :             )
    9532            4 :             .await?;
    9533            4 :         {
    9534            4 :             tline
    9535            4 :                 .applied_gc_cutoff_lsn
    9536            4 :                 .lock_for_write()
    9537            4 :                 .store_and_unlock(Lsn(0x30))
    9538            4 :                 .wait()
    9539            4 :                 .await;
    9540            4 :             // Update GC info
    9541            4 :             let mut guard = tline.gc_info.write().unwrap();
    9542            4 :             *guard = GcInfo {
    9543            4 :                 retain_lsns: vec![
    9544            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9545            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9546            4 :                 ],
    9547            4 :                 cutoffs: GcCutoffs {
    9548            4 :                     time: Lsn(0x30),
    9549            4 :                     space: Lsn(0x30),
    9550            4 :                 },
    9551            4 :                 leases: Default::default(),
    9552            4 :                 within_ancestor_pitr: false,
    9553            4 :             };
    9554            4 :         }
    9555            4 : 
    9556            4 :         let expected_result = [
    9557            4 :             Bytes::from_static(b"value 0@0x10"),
    9558            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9559            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9560            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9561            4 :             Bytes::from_static(b"value 4@0x10"),
    9562            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9563            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9564            4 :             Bytes::from_static(b"value 7@0x10"),
    9565            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9566            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9567            4 :         ];
    9568            4 : 
    9569            4 :         let expected_result_at_gc_horizon = [
    9570            4 :             Bytes::from_static(b"value 0@0x10"),
    9571            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9572            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9573            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9574            4 :             Bytes::from_static(b"value 4@0x10"),
    9575            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9576            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9577            4 :             Bytes::from_static(b"value 7@0x10"),
    9578            4 :             Bytes::from_static(b"value 8@0x10"),
    9579            4 :             Bytes::from_static(b"value 9@0x10"),
    9580            4 :         ];
    9581            4 : 
    9582            4 :         let expected_result_at_lsn_20 = [
    9583            4 :             Bytes::from_static(b"value 0@0x10"),
    9584            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9585            4 :             Bytes::from_static(b"value 2@0x10"),
    9586            4 :             Bytes::from_static(b"value 3@0x10"),
    9587            4 :             Bytes::from_static(b"value 4@0x10"),
    9588            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9589            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9590            4 :             Bytes::from_static(b"value 7@0x10"),
    9591            4 :             Bytes::from_static(b"value 8@0x10"),
    9592            4 :             Bytes::from_static(b"value 9@0x10"),
    9593            4 :         ];
    9594            4 : 
    9595            4 :         let expected_result_at_lsn_10 = [
    9596            4 :             Bytes::from_static(b"value 0@0x10"),
    9597            4 :             Bytes::from_static(b"value 1@0x10"),
    9598            4 :             Bytes::from_static(b"value 2@0x10"),
    9599            4 :             Bytes::from_static(b"value 3@0x10"),
    9600            4 :             Bytes::from_static(b"value 4@0x10"),
    9601            4 :             Bytes::from_static(b"value 5@0x10"),
    9602            4 :             Bytes::from_static(b"value 6@0x10"),
    9603            4 :             Bytes::from_static(b"value 7@0x10"),
    9604            4 :             Bytes::from_static(b"value 8@0x10"),
    9605            4 :             Bytes::from_static(b"value 9@0x10"),
    9606            4 :         ];
    9607            4 : 
    9608           24 :         let verify_result = || async {
    9609           24 :             let gc_horizon = {
    9610           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9611           24 :                 gc_info.cutoffs.time
    9612            4 :             };
    9613          264 :             for idx in 0..10 {
    9614          240 :                 assert_eq!(
    9615          240 :                     tline
    9616          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9617          240 :                         .await
    9618          240 :                         .unwrap(),
    9619          240 :                     &expected_result[idx]
    9620            4 :                 );
    9621          240 :                 assert_eq!(
    9622          240 :                     tline
    9623          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9624          240 :                         .await
    9625          240 :                         .unwrap(),
    9626          240 :                     &expected_result_at_gc_horizon[idx]
    9627            4 :                 );
    9628          240 :                 assert_eq!(
    9629          240 :                     tline
    9630          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9631          240 :                         .await
    9632          240 :                         .unwrap(),
    9633          240 :                     &expected_result_at_lsn_20[idx]
    9634            4 :                 );
    9635          240 :                 assert_eq!(
    9636          240 :                     tline
    9637          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9638          240 :                         .await
    9639          240 :                         .unwrap(),
    9640          240 :                     &expected_result_at_lsn_10[idx]
    9641            4 :                 );
    9642            4 :             }
    9643           48 :         };
    9644            4 : 
    9645            4 :         verify_result().await;
    9646            4 : 
    9647            4 :         let cancel = CancellationToken::new();
    9648            4 :         let mut dryrun_flags = EnumSet::new();
    9649            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9650            4 : 
    9651            4 :         tline
    9652            4 :             .compact_with_gc(
    9653            4 :                 &cancel,
    9654            4 :                 CompactOptions {
    9655            4 :                     flags: dryrun_flags,
    9656            4 :                     ..Default::default()
    9657            4 :                 },
    9658            4 :                 &ctx,
    9659            4 :             )
    9660            4 :             .await
    9661            4 :             .unwrap();
    9662            4 :         // 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
    9663            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9664            4 :         verify_result().await;
    9665            4 : 
    9666            4 :         tline
    9667            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9668            4 :             .await
    9669            4 :             .unwrap();
    9670            4 :         verify_result().await;
    9671            4 : 
    9672            4 :         // compact again
    9673            4 :         tline
    9674            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9675            4 :             .await
    9676            4 :             .unwrap();
    9677            4 :         verify_result().await;
    9678            4 : 
    9679            4 :         // increase GC horizon and compact again
    9680            4 :         {
    9681            4 :             tline
    9682            4 :                 .applied_gc_cutoff_lsn
    9683            4 :                 .lock_for_write()
    9684            4 :                 .store_and_unlock(Lsn(0x38))
    9685            4 :                 .wait()
    9686            4 :                 .await;
    9687            4 :             // Update GC info
    9688            4 :             let mut guard = tline.gc_info.write().unwrap();
    9689            4 :             guard.cutoffs.time = Lsn(0x38);
    9690            4 :             guard.cutoffs.space = Lsn(0x38);
    9691            4 :         }
    9692            4 :         tline
    9693            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9694            4 :             .await
    9695            4 :             .unwrap();
    9696            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9697            4 : 
    9698            4 :         // not increasing the GC horizon and compact again
    9699            4 :         tline
    9700            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9701            4 :             .await
    9702            4 :             .unwrap();
    9703            4 :         verify_result().await;
    9704            4 : 
    9705            4 :         Ok(())
    9706            4 :     }
    9707              : 
    9708              :     #[cfg(feature = "testing")]
    9709              :     #[tokio::test]
    9710            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9711            4 :     {
    9712            4 :         let harness =
    9713            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9714            4 :                 .await?;
    9715            4 :         let (tenant, ctx) = harness.load().await;
    9716            4 : 
    9717          704 :         fn get_key(id: u32) -> Key {
    9718          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9719          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9720          704 :             key.field6 = id;
    9721          704 :             key
    9722          704 :         }
    9723            4 : 
    9724            4 :         let img_layer = (0..10)
    9725           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9726            4 :             .collect_vec();
    9727            4 : 
    9728            4 :         let delta1 = vec![
    9729            4 :             (
    9730            4 :                 get_key(1),
    9731            4 :                 Lsn(0x20),
    9732            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9733            4 :             ),
    9734            4 :             (
    9735            4 :                 get_key(1),
    9736            4 :                 Lsn(0x28),
    9737            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9738            4 :             ),
    9739            4 :         ];
    9740            4 :         let delta2 = vec![
    9741            4 :             (
    9742            4 :                 get_key(1),
    9743            4 :                 Lsn(0x30),
    9744            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9745            4 :             ),
    9746            4 :             (
    9747            4 :                 get_key(1),
    9748            4 :                 Lsn(0x38),
    9749            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9750            4 :             ),
    9751            4 :         ];
    9752            4 :         let delta3 = vec![
    9753            4 :             (
    9754            4 :                 get_key(8),
    9755            4 :                 Lsn(0x48),
    9756            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9757            4 :             ),
    9758            4 :             (
    9759            4 :                 get_key(9),
    9760            4 :                 Lsn(0x48),
    9761            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9762            4 :             ),
    9763            4 :         ];
    9764            4 : 
    9765            4 :         let tline = tenant
    9766            4 :             .create_test_timeline_with_layers(
    9767            4 :                 TIMELINE_ID,
    9768            4 :                 Lsn(0x10),
    9769            4 :                 DEFAULT_PG_VERSION,
    9770            4 :                 &ctx,
    9771            4 :                 vec![
    9772            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9773            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9774            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9775            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9776            4 :                 ], // delta layers
    9777            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9778            4 :                 Lsn(0x50),
    9779            4 :             )
    9780            4 :             .await?;
    9781            4 :         {
    9782            4 :             tline
    9783            4 :                 .applied_gc_cutoff_lsn
    9784            4 :                 .lock_for_write()
    9785            4 :                 .store_and_unlock(Lsn(0x30))
    9786            4 :                 .wait()
    9787            4 :                 .await;
    9788            4 :             // Update GC info
    9789            4 :             let mut guard = tline.gc_info.write().unwrap();
    9790            4 :             *guard = GcInfo {
    9791            4 :                 retain_lsns: vec![
    9792            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9793            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9794            4 :                 ],
    9795            4 :                 cutoffs: GcCutoffs {
    9796            4 :                     time: Lsn(0x30),
    9797            4 :                     space: Lsn(0x30),
    9798            4 :                 },
    9799            4 :                 leases: Default::default(),
    9800            4 :                 within_ancestor_pitr: false,
    9801            4 :             };
    9802            4 :         }
    9803            4 : 
    9804            4 :         let expected_result = [
    9805            4 :             Bytes::from_static(b"value 0@0x10"),
    9806            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9807            4 :             Bytes::from_static(b"value 2@0x10"),
    9808            4 :             Bytes::from_static(b"value 3@0x10"),
    9809            4 :             Bytes::from_static(b"value 4@0x10"),
    9810            4 :             Bytes::from_static(b"value 5@0x10"),
    9811            4 :             Bytes::from_static(b"value 6@0x10"),
    9812            4 :             Bytes::from_static(b"value 7@0x10"),
    9813            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9814            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9815            4 :         ];
    9816            4 : 
    9817            4 :         let expected_result_at_gc_horizon = [
    9818            4 :             Bytes::from_static(b"value 0@0x10"),
    9819            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9820            4 :             Bytes::from_static(b"value 2@0x10"),
    9821            4 :             Bytes::from_static(b"value 3@0x10"),
    9822            4 :             Bytes::from_static(b"value 4@0x10"),
    9823            4 :             Bytes::from_static(b"value 5@0x10"),
    9824            4 :             Bytes::from_static(b"value 6@0x10"),
    9825            4 :             Bytes::from_static(b"value 7@0x10"),
    9826            4 :             Bytes::from_static(b"value 8@0x10"),
    9827            4 :             Bytes::from_static(b"value 9@0x10"),
    9828            4 :         ];
    9829            4 : 
    9830            4 :         let expected_result_at_lsn_20 = [
    9831            4 :             Bytes::from_static(b"value 0@0x10"),
    9832            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9833            4 :             Bytes::from_static(b"value 2@0x10"),
    9834            4 :             Bytes::from_static(b"value 3@0x10"),
    9835            4 :             Bytes::from_static(b"value 4@0x10"),
    9836            4 :             Bytes::from_static(b"value 5@0x10"),
    9837            4 :             Bytes::from_static(b"value 6@0x10"),
    9838            4 :             Bytes::from_static(b"value 7@0x10"),
    9839            4 :             Bytes::from_static(b"value 8@0x10"),
    9840            4 :             Bytes::from_static(b"value 9@0x10"),
    9841            4 :         ];
    9842            4 : 
    9843            4 :         let expected_result_at_lsn_10 = [
    9844            4 :             Bytes::from_static(b"value 0@0x10"),
    9845            4 :             Bytes::from_static(b"value 1@0x10"),
    9846            4 :             Bytes::from_static(b"value 2@0x10"),
    9847            4 :             Bytes::from_static(b"value 3@0x10"),
    9848            4 :             Bytes::from_static(b"value 4@0x10"),
    9849            4 :             Bytes::from_static(b"value 5@0x10"),
    9850            4 :             Bytes::from_static(b"value 6@0x10"),
    9851            4 :             Bytes::from_static(b"value 7@0x10"),
    9852            4 :             Bytes::from_static(b"value 8@0x10"),
    9853            4 :             Bytes::from_static(b"value 9@0x10"),
    9854            4 :         ];
    9855            4 : 
    9856           16 :         let verify_result = || async {
    9857           16 :             let gc_horizon = {
    9858           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9859           16 :                 gc_info.cutoffs.time
    9860            4 :             };
    9861          176 :             for idx in 0..10 {
    9862          160 :                 assert_eq!(
    9863          160 :                     tline
    9864          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9865          160 :                         .await
    9866          160 :                         .unwrap(),
    9867          160 :                     &expected_result[idx]
    9868            4 :                 );
    9869          160 :                 assert_eq!(
    9870          160 :                     tline
    9871          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9872          160 :                         .await
    9873          160 :                         .unwrap(),
    9874          160 :                     &expected_result_at_gc_horizon[idx]
    9875            4 :                 );
    9876          160 :                 assert_eq!(
    9877          160 :                     tline
    9878          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9879          160 :                         .await
    9880          160 :                         .unwrap(),
    9881          160 :                     &expected_result_at_lsn_20[idx]
    9882            4 :                 );
    9883          160 :                 assert_eq!(
    9884          160 :                     tline
    9885          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9886          160 :                         .await
    9887          160 :                         .unwrap(),
    9888          160 :                     &expected_result_at_lsn_10[idx]
    9889            4 :                 );
    9890            4 :             }
    9891           32 :         };
    9892            4 : 
    9893            4 :         verify_result().await;
    9894            4 : 
    9895            4 :         let cancel = CancellationToken::new();
    9896            4 :         let mut dryrun_flags = EnumSet::new();
    9897            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9898            4 : 
    9899            4 :         tline
    9900            4 :             .compact_with_gc(
    9901            4 :                 &cancel,
    9902            4 :                 CompactOptions {
    9903            4 :                     flags: dryrun_flags,
    9904            4 :                     ..Default::default()
    9905            4 :                 },
    9906            4 :                 &ctx,
    9907            4 :             )
    9908            4 :             .await
    9909            4 :             .unwrap();
    9910            4 :         // 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
    9911            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9912            4 :         verify_result().await;
    9913            4 : 
    9914            4 :         tline
    9915            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9916            4 :             .await
    9917            4 :             .unwrap();
    9918            4 :         verify_result().await;
    9919            4 : 
    9920            4 :         // compact again
    9921            4 :         tline
    9922            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9923            4 :             .await
    9924            4 :             .unwrap();
    9925            4 :         verify_result().await;
    9926            4 : 
    9927            4 :         Ok(())
    9928            4 :     }
    9929              : 
    9930              :     #[cfg(feature = "testing")]
    9931              :     #[tokio::test]
    9932            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9933            4 :         use models::CompactLsnRange;
    9934            4 : 
    9935            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9936            4 :         let (tenant, ctx) = harness.load().await;
    9937            4 : 
    9938          332 :         fn get_key(id: u32) -> Key {
    9939          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9940          332 :             key.field6 = id;
    9941          332 :             key
    9942          332 :         }
    9943            4 : 
    9944            4 :         let img_layer = (0..10)
    9945           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9946            4 :             .collect_vec();
    9947            4 : 
    9948            4 :         let delta1 = vec![
    9949            4 :             (
    9950            4 :                 get_key(1),
    9951            4 :                 Lsn(0x20),
    9952            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9953            4 :             ),
    9954            4 :             (
    9955            4 :                 get_key(2),
    9956            4 :                 Lsn(0x30),
    9957            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9958            4 :             ),
    9959            4 :             (
    9960            4 :                 get_key(3),
    9961            4 :                 Lsn(0x28),
    9962            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9963            4 :             ),
    9964            4 :             (
    9965            4 :                 get_key(3),
    9966            4 :                 Lsn(0x30),
    9967            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9968            4 :             ),
    9969            4 :             (
    9970            4 :                 get_key(3),
    9971            4 :                 Lsn(0x40),
    9972            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9973            4 :             ),
    9974            4 :         ];
    9975            4 :         let delta2 = vec![
    9976            4 :             (
    9977            4 :                 get_key(5),
    9978            4 :                 Lsn(0x20),
    9979            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9980            4 :             ),
    9981            4 :             (
    9982            4 :                 get_key(6),
    9983            4 :                 Lsn(0x20),
    9984            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9985            4 :             ),
    9986            4 :         ];
    9987            4 :         let delta3 = vec![
    9988            4 :             (
    9989            4 :                 get_key(8),
    9990            4 :                 Lsn(0x48),
    9991            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9992            4 :             ),
    9993            4 :             (
    9994            4 :                 get_key(9),
    9995            4 :                 Lsn(0x48),
    9996            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9997            4 :             ),
    9998            4 :         ];
    9999            4 : 
   10000            4 :         let parent_tline = tenant
   10001            4 :             .create_test_timeline_with_layers(
   10002            4 :                 TIMELINE_ID,
   10003            4 :                 Lsn(0x10),
   10004            4 :                 DEFAULT_PG_VERSION,
   10005            4 :                 &ctx,
   10006            4 :                 vec![],                       // delta layers
   10007            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10008            4 :                 Lsn(0x18),
   10009            4 :             )
   10010            4 :             .await?;
   10011            4 : 
   10012            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10013            4 : 
   10014            4 :         let branch_tline = tenant
   10015            4 :             .branch_timeline_test_with_layers(
   10016            4 :                 &parent_tline,
   10017            4 :                 NEW_TIMELINE_ID,
   10018            4 :                 Some(Lsn(0x18)),
   10019            4 :                 &ctx,
   10020            4 :                 vec![
   10021            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10022            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10023            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10024            4 :                 ], // delta layers
   10025            4 :                 vec![], // image layers
   10026            4 :                 Lsn(0x50),
   10027            4 :             )
   10028            4 :             .await?;
   10029            4 : 
   10030            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10031            4 : 
   10032            4 :         {
   10033            4 :             parent_tline
   10034            4 :                 .applied_gc_cutoff_lsn
   10035            4 :                 .lock_for_write()
   10036            4 :                 .store_and_unlock(Lsn(0x10))
   10037            4 :                 .wait()
   10038            4 :                 .await;
   10039            4 :             // Update GC info
   10040            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10041            4 :             *guard = GcInfo {
   10042            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10043            4 :                 cutoffs: GcCutoffs {
   10044            4 :                     time: Lsn(0x10),
   10045            4 :                     space: Lsn(0x10),
   10046            4 :                 },
   10047            4 :                 leases: Default::default(),
   10048            4 :                 within_ancestor_pitr: false,
   10049            4 :             };
   10050            4 :         }
   10051            4 : 
   10052            4 :         {
   10053            4 :             branch_tline
   10054            4 :                 .applied_gc_cutoff_lsn
   10055            4 :                 .lock_for_write()
   10056            4 :                 .store_and_unlock(Lsn(0x50))
   10057            4 :                 .wait()
   10058            4 :                 .await;
   10059            4 :             // Update GC info
   10060            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10061            4 :             *guard = GcInfo {
   10062            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10063            4 :                 cutoffs: GcCutoffs {
   10064            4 :                     time: Lsn(0x50),
   10065            4 :                     space: Lsn(0x50),
   10066            4 :                 },
   10067            4 :                 leases: Default::default(),
   10068            4 :                 within_ancestor_pitr: false,
   10069            4 :             };
   10070            4 :         }
   10071            4 : 
   10072            4 :         let expected_result_at_gc_horizon = [
   10073            4 :             Bytes::from_static(b"value 0@0x10"),
   10074            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10075            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10076            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10077            4 :             Bytes::from_static(b"value 4@0x10"),
   10078            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10079            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10080            4 :             Bytes::from_static(b"value 7@0x10"),
   10081            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10082            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10083            4 :         ];
   10084            4 : 
   10085            4 :         let expected_result_at_lsn_40 = [
   10086            4 :             Bytes::from_static(b"value 0@0x10"),
   10087            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10088            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10089            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10090            4 :             Bytes::from_static(b"value 4@0x10"),
   10091            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10092            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10093            4 :             Bytes::from_static(b"value 7@0x10"),
   10094            4 :             Bytes::from_static(b"value 8@0x10"),
   10095            4 :             Bytes::from_static(b"value 9@0x10"),
   10096            4 :         ];
   10097            4 : 
   10098           12 :         let verify_result = || async {
   10099          132 :             for idx in 0..10 {
   10100          120 :                 assert_eq!(
   10101          120 :                     branch_tline
   10102          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10103          120 :                         .await
   10104          120 :                         .unwrap(),
   10105          120 :                     &expected_result_at_gc_horizon[idx]
   10106            4 :                 );
   10107          120 :                 assert_eq!(
   10108          120 :                     branch_tline
   10109          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10110          120 :                         .await
   10111          120 :                         .unwrap(),
   10112          120 :                     &expected_result_at_lsn_40[idx]
   10113            4 :                 );
   10114            4 :             }
   10115           24 :         };
   10116            4 : 
   10117            4 :         verify_result().await;
   10118            4 : 
   10119            4 :         let cancel = CancellationToken::new();
   10120            4 :         branch_tline
   10121            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10122            4 :             .await
   10123            4 :             .unwrap();
   10124            4 : 
   10125            4 :         verify_result().await;
   10126            4 : 
   10127            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10128            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10129            4 :         branch_tline
   10130            4 :             .compact_with_gc(
   10131            4 :                 &cancel,
   10132            4 :                 CompactOptions {
   10133            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10134            4 :                     ..Default::default()
   10135            4 :                 },
   10136            4 :                 &ctx,
   10137            4 :             )
   10138            4 :             .await
   10139            4 :             .unwrap();
   10140            4 : 
   10141            4 :         verify_result().await;
   10142            4 : 
   10143            4 :         Ok(())
   10144            4 :     }
   10145              : 
   10146              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10147              :     // Create an image arrangement where we have to read at different LSN ranges
   10148              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10149              :     // a delta layer. Like so:
   10150              :     //
   10151              :     //     A      B
   10152              :     // +----------------+ -> delta_layer
   10153              :     // |                |                           ^ lsn
   10154              :     // |       =========|-> nested_image_layer      |
   10155              :     // |       C        |                           |
   10156              :     // +----------------+                           |
   10157              :     // ======== -> baseline_image_layer             +-------> key
   10158              :     //
   10159              :     //
   10160              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10161              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10162              :     #[cfg(feature = "testing")]
   10163              :     #[tokio::test]
   10164            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10165            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10166            4 :         let (tenant, ctx) = harness.load().await;
   10167            4 : 
   10168            4 :         let will_init_keys = [2, 6];
   10169           88 :         fn get_key(id: u32) -> Key {
   10170           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10171           88 :             key.field6 = id;
   10172           88 :             key
   10173           88 :         }
   10174            4 : 
   10175            4 :         let mut expected_key_values = HashMap::new();
   10176            4 : 
   10177            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10178            4 :         let mut baseline_img_layer = Vec::new();
   10179           24 :         for i in 0..5 {
   10180           20 :             let key = get_key(i);
   10181           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10182           20 : 
   10183           20 :             let removed = expected_key_values.insert(key, value.clone());
   10184           20 :             assert!(removed.is_none());
   10185            4 : 
   10186           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10187            4 :         }
   10188            4 : 
   10189            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10190            4 :         let mut nested_img_layer = Vec::new();
   10191           24 :         for i in 5..10 {
   10192           20 :             let key = get_key(i);
   10193           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10194           20 : 
   10195           20 :             let removed = expected_key_values.insert(key, value.clone());
   10196           20 :             assert!(removed.is_none());
   10197            4 : 
   10198           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10199            4 :         }
   10200            4 : 
   10201            4 :         let mut delta_layer_spec = Vec::default();
   10202            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10203            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10204            4 : 
   10205           44 :         for i in 0..10 {
   10206           40 :             let key = get_key(i);
   10207           40 :             let key_in_nested = nested_img_layer
   10208           40 :                 .iter()
   10209          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10210           40 :             let lsn = {
   10211           40 :                 if key_in_nested {
   10212           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10213            4 :                 } else {
   10214           20 :                     delta_layer_start_lsn
   10215            4 :                 }
   10216            4 :             };
   10217            4 : 
   10218           40 :             let will_init = will_init_keys.contains(&i);
   10219           40 :             if will_init {
   10220            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10221            8 : 
   10222            8 :                 expected_key_values.insert(key, "".to_string());
   10223           32 :             } else {
   10224           32 :                 let delta = format!("@{lsn}");
   10225           32 :                 delta_layer_spec.push((
   10226           32 :                     key,
   10227           32 :                     lsn,
   10228           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10229           32 :                 ));
   10230           32 : 
   10231           32 :                 expected_key_values
   10232           32 :                     .get_mut(&key)
   10233           32 :                     .expect("An image exists for each key")
   10234           32 :                     .push_str(delta.as_str());
   10235           32 :             }
   10236           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10237            4 :         }
   10238            4 : 
   10239            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10240            4 : 
   10241            4 :         assert!(
   10242            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10243            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10244            4 :         );
   10245            4 : 
   10246            4 :         let tline = tenant
   10247            4 :             .create_test_timeline_with_layers(
   10248            4 :                 TIMELINE_ID,
   10249            4 :                 baseline_image_layer_lsn,
   10250            4 :                 DEFAULT_PG_VERSION,
   10251            4 :                 &ctx,
   10252            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10253            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10254            4 :                     delta_layer_spec,
   10255            4 :                 )], // delta layers
   10256            4 :                 vec![
   10257            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10258            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10259            4 :                 ], // image layers
   10260            4 :                 delta_layer_end_lsn,
   10261            4 :             )
   10262            4 :             .await?;
   10263            4 : 
   10264            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10265            4 :         let results = tline
   10266            4 :             .get_vectored(
   10267            4 :                 keyspace,
   10268            4 :                 delta_layer_end_lsn,
   10269            4 :                 IoConcurrency::sequential(),
   10270            4 :                 &ctx,
   10271            4 :             )
   10272            4 :             .await
   10273            4 :             .expect("No vectored errors");
   10274           44 :         for (key, res) in results {
   10275           40 :             let value = res.expect("No key errors");
   10276           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10277           40 :             assert_eq!(value, Bytes::from(expected_value));
   10278            4 :         }
   10279            4 : 
   10280            4 :         Ok(())
   10281            4 :     }
   10282              : 
   10283          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10284          428 :         (
   10285          428 :             k1.is_delta,
   10286          428 :             k1.key_range.start,
   10287          428 :             k1.key_range.end,
   10288          428 :             k1.lsn_range.start,
   10289          428 :             k1.lsn_range.end,
   10290          428 :         )
   10291          428 :             .cmp(&(
   10292          428 :                 k2.is_delta,
   10293          428 :                 k2.key_range.start,
   10294          428 :                 k2.key_range.end,
   10295          428 :                 k2.lsn_range.start,
   10296          428 :                 k2.lsn_range.end,
   10297          428 :             ))
   10298          428 :     }
   10299              : 
   10300           48 :     async fn inspect_and_sort(
   10301           48 :         tline: &Arc<Timeline>,
   10302           48 :         filter: Option<std::ops::Range<Key>>,
   10303           48 :     ) -> Vec<PersistentLayerKey> {
   10304           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10305           48 :         if let Some(filter) = filter {
   10306          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10307           44 :         }
   10308           48 :         all_layers.sort_by(sort_layer_key);
   10309           48 :         all_layers
   10310           48 :     }
   10311              : 
   10312              :     #[cfg(feature = "testing")]
   10313           44 :     fn check_layer_map_key_eq(
   10314           44 :         mut left: Vec<PersistentLayerKey>,
   10315           44 :         mut right: Vec<PersistentLayerKey>,
   10316           44 :     ) {
   10317           44 :         left.sort_by(sort_layer_key);
   10318           44 :         right.sort_by(sort_layer_key);
   10319           44 :         if left != right {
   10320            0 :             eprintln!("---LEFT---");
   10321            0 :             for left in left.iter() {
   10322            0 :                 eprintln!("{}", left);
   10323            0 :             }
   10324            0 :             eprintln!("---RIGHT---");
   10325            0 :             for right in right.iter() {
   10326            0 :                 eprintln!("{}", right);
   10327            0 :             }
   10328            0 :             assert_eq!(left, right);
   10329           44 :         }
   10330           44 :     }
   10331              : 
   10332              :     #[cfg(feature = "testing")]
   10333              :     #[tokio::test]
   10334            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10335            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10336            4 :         let (tenant, ctx) = harness.load().await;
   10337            4 : 
   10338          364 :         fn get_key(id: u32) -> Key {
   10339          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10340          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10341          364 :             key.field6 = id;
   10342          364 :             key
   10343          364 :         }
   10344            4 : 
   10345            4 :         // img layer at 0x10
   10346            4 :         let img_layer = (0..10)
   10347           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10348            4 :             .collect_vec();
   10349            4 : 
   10350            4 :         let delta1 = vec![
   10351            4 :             (
   10352            4 :                 get_key(1),
   10353            4 :                 Lsn(0x20),
   10354            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10355            4 :             ),
   10356            4 :             (
   10357            4 :                 get_key(2),
   10358            4 :                 Lsn(0x30),
   10359            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10360            4 :             ),
   10361            4 :             (
   10362            4 :                 get_key(3),
   10363            4 :                 Lsn(0x40),
   10364            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10365            4 :             ),
   10366            4 :         ];
   10367            4 :         let delta2 = vec![
   10368            4 :             (
   10369            4 :                 get_key(5),
   10370            4 :                 Lsn(0x20),
   10371            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10372            4 :             ),
   10373            4 :             (
   10374            4 :                 get_key(6),
   10375            4 :                 Lsn(0x20),
   10376            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10377            4 :             ),
   10378            4 :         ];
   10379            4 :         let delta3 = vec![
   10380            4 :             (
   10381            4 :                 get_key(8),
   10382            4 :                 Lsn(0x48),
   10383            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10384            4 :             ),
   10385            4 :             (
   10386            4 :                 get_key(9),
   10387            4 :                 Lsn(0x48),
   10388            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10389            4 :             ),
   10390            4 :         ];
   10391            4 : 
   10392            4 :         let tline = tenant
   10393            4 :             .create_test_timeline_with_layers(
   10394            4 :                 TIMELINE_ID,
   10395            4 :                 Lsn(0x10),
   10396            4 :                 DEFAULT_PG_VERSION,
   10397            4 :                 &ctx,
   10398            4 :                 vec![
   10399            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10400            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10401            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10402            4 :                 ], // delta layers
   10403            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10404            4 :                 Lsn(0x50),
   10405            4 :             )
   10406            4 :             .await?;
   10407            4 : 
   10408            4 :         {
   10409            4 :             tline
   10410            4 :                 .applied_gc_cutoff_lsn
   10411            4 :                 .lock_for_write()
   10412            4 :                 .store_and_unlock(Lsn(0x30))
   10413            4 :                 .wait()
   10414            4 :                 .await;
   10415            4 :             // Update GC info
   10416            4 :             let mut guard = tline.gc_info.write().unwrap();
   10417            4 :             *guard = GcInfo {
   10418            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10419            4 :                 cutoffs: GcCutoffs {
   10420            4 :                     time: Lsn(0x30),
   10421            4 :                     space: Lsn(0x30),
   10422            4 :                 },
   10423            4 :                 leases: Default::default(),
   10424            4 :                 within_ancestor_pitr: false,
   10425            4 :             };
   10426            4 :         }
   10427            4 : 
   10428            4 :         let cancel = CancellationToken::new();
   10429            4 : 
   10430            4 :         // Do a partial compaction on key range 0..2
   10431            4 :         tline
   10432            4 :             .compact_with_gc(
   10433            4 :                 &cancel,
   10434            4 :                 CompactOptions {
   10435            4 :                     flags: EnumSet::new(),
   10436            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10437            4 :                     ..Default::default()
   10438            4 :                 },
   10439            4 :                 &ctx,
   10440            4 :             )
   10441            4 :             .await
   10442            4 :             .unwrap();
   10443            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10444            4 :         check_layer_map_key_eq(
   10445            4 :             all_layers,
   10446            4 :             vec![
   10447            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10448            4 :                 PersistentLayerKey {
   10449            4 :                     key_range: get_key(0)..get_key(2),
   10450            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10451            4 :                     is_delta: false,
   10452            4 :                 },
   10453            4 :                 PersistentLayerKey {
   10454            4 :                     key_range: get_key(0)..get_key(10),
   10455            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10456            4 :                     is_delta: false,
   10457            4 :                 },
   10458            4 :                 // delta1 is split and the second part is rewritten
   10459            4 :                 PersistentLayerKey {
   10460            4 :                     key_range: get_key(2)..get_key(4),
   10461            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10462            4 :                     is_delta: true,
   10463            4 :                 },
   10464            4 :                 PersistentLayerKey {
   10465            4 :                     key_range: get_key(5)..get_key(7),
   10466            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10467            4 :                     is_delta: true,
   10468            4 :                 },
   10469            4 :                 PersistentLayerKey {
   10470            4 :                     key_range: get_key(8)..get_key(10),
   10471            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10472            4 :                     is_delta: true,
   10473            4 :                 },
   10474            4 :             ],
   10475            4 :         );
   10476            4 : 
   10477            4 :         // Do a partial compaction on key range 2..4
   10478            4 :         tline
   10479            4 :             .compact_with_gc(
   10480            4 :                 &cancel,
   10481            4 :                 CompactOptions {
   10482            4 :                     flags: EnumSet::new(),
   10483            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10484            4 :                     ..Default::default()
   10485            4 :                 },
   10486            4 :                 &ctx,
   10487            4 :             )
   10488            4 :             .await
   10489            4 :             .unwrap();
   10490            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10491            4 :         check_layer_map_key_eq(
   10492            4 :             all_layers,
   10493            4 :             vec![
   10494            4 :                 PersistentLayerKey {
   10495            4 :                     key_range: get_key(0)..get_key(2),
   10496            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10497            4 :                     is_delta: false,
   10498            4 :                 },
   10499            4 :                 PersistentLayerKey {
   10500            4 :                     key_range: get_key(0)..get_key(10),
   10501            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10502            4 :                     is_delta: false,
   10503            4 :                 },
   10504            4 :                 // image layer generated for the compaction range 2-4
   10505            4 :                 PersistentLayerKey {
   10506            4 :                     key_range: get_key(2)..get_key(4),
   10507            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10508            4 :                     is_delta: false,
   10509            4 :                 },
   10510            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10511            4 :                 PersistentLayerKey {
   10512            4 :                     key_range: get_key(2)..get_key(4),
   10513            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10514            4 :                     is_delta: true,
   10515            4 :                 },
   10516            4 :                 PersistentLayerKey {
   10517            4 :                     key_range: get_key(5)..get_key(7),
   10518            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10519            4 :                     is_delta: true,
   10520            4 :                 },
   10521            4 :                 PersistentLayerKey {
   10522            4 :                     key_range: get_key(8)..get_key(10),
   10523            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10524            4 :                     is_delta: true,
   10525            4 :                 },
   10526            4 :             ],
   10527            4 :         );
   10528            4 : 
   10529            4 :         // Do a partial compaction on key range 4..9
   10530            4 :         tline
   10531            4 :             .compact_with_gc(
   10532            4 :                 &cancel,
   10533            4 :                 CompactOptions {
   10534            4 :                     flags: EnumSet::new(),
   10535            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10536            4 :                     ..Default::default()
   10537            4 :                 },
   10538            4 :                 &ctx,
   10539            4 :             )
   10540            4 :             .await
   10541            4 :             .unwrap();
   10542            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10543            4 :         check_layer_map_key_eq(
   10544            4 :             all_layers,
   10545            4 :             vec![
   10546            4 :                 PersistentLayerKey {
   10547            4 :                     key_range: get_key(0)..get_key(2),
   10548            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10549            4 :                     is_delta: false,
   10550            4 :                 },
   10551            4 :                 PersistentLayerKey {
   10552            4 :                     key_range: get_key(0)..get_key(10),
   10553            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10554            4 :                     is_delta: false,
   10555            4 :                 },
   10556            4 :                 PersistentLayerKey {
   10557            4 :                     key_range: get_key(2)..get_key(4),
   10558            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10559            4 :                     is_delta: false,
   10560            4 :                 },
   10561            4 :                 PersistentLayerKey {
   10562            4 :                     key_range: get_key(2)..get_key(4),
   10563            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10564            4 :                     is_delta: true,
   10565            4 :                 },
   10566            4 :                 // image layer generated for this compaction range
   10567            4 :                 PersistentLayerKey {
   10568            4 :                     key_range: get_key(4)..get_key(9),
   10569            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10570            4 :                     is_delta: false,
   10571            4 :                 },
   10572            4 :                 PersistentLayerKey {
   10573            4 :                     key_range: get_key(8)..get_key(10),
   10574            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10575            4 :                     is_delta: true,
   10576            4 :                 },
   10577            4 :             ],
   10578            4 :         );
   10579            4 : 
   10580            4 :         // Do a partial compaction on key range 9..10
   10581            4 :         tline
   10582            4 :             .compact_with_gc(
   10583            4 :                 &cancel,
   10584            4 :                 CompactOptions {
   10585            4 :                     flags: EnumSet::new(),
   10586            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10587            4 :                     ..Default::default()
   10588            4 :                 },
   10589            4 :                 &ctx,
   10590            4 :             )
   10591            4 :             .await
   10592            4 :             .unwrap();
   10593            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10594            4 :         check_layer_map_key_eq(
   10595            4 :             all_layers,
   10596            4 :             vec![
   10597            4 :                 PersistentLayerKey {
   10598            4 :                     key_range: get_key(0)..get_key(2),
   10599            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10600            4 :                     is_delta: false,
   10601            4 :                 },
   10602            4 :                 PersistentLayerKey {
   10603            4 :                     key_range: get_key(0)..get_key(10),
   10604            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10605            4 :                     is_delta: false,
   10606            4 :                 },
   10607            4 :                 PersistentLayerKey {
   10608            4 :                     key_range: get_key(2)..get_key(4),
   10609            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10610            4 :                     is_delta: false,
   10611            4 :                 },
   10612            4 :                 PersistentLayerKey {
   10613            4 :                     key_range: get_key(2)..get_key(4),
   10614            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10615            4 :                     is_delta: true,
   10616            4 :                 },
   10617            4 :                 PersistentLayerKey {
   10618            4 :                     key_range: get_key(4)..get_key(9),
   10619            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10620            4 :                     is_delta: false,
   10621            4 :                 },
   10622            4 :                 // image layer generated for the compaction range
   10623            4 :                 PersistentLayerKey {
   10624            4 :                     key_range: get_key(9)..get_key(10),
   10625            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10626            4 :                     is_delta: false,
   10627            4 :                 },
   10628            4 :                 PersistentLayerKey {
   10629            4 :                     key_range: get_key(8)..get_key(10),
   10630            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10631            4 :                     is_delta: true,
   10632            4 :                 },
   10633            4 :             ],
   10634            4 :         );
   10635            4 : 
   10636            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10637            4 :         tline
   10638            4 :             .compact_with_gc(
   10639            4 :                 &cancel,
   10640            4 :                 CompactOptions {
   10641            4 :                     flags: EnumSet::new(),
   10642            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10643            4 :                     ..Default::default()
   10644            4 :                 },
   10645            4 :                 &ctx,
   10646            4 :             )
   10647            4 :             .await
   10648            4 :             .unwrap();
   10649            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10650            4 :         check_layer_map_key_eq(
   10651            4 :             all_layers,
   10652            4 :             vec![
   10653            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10654            4 :                 PersistentLayerKey {
   10655            4 :                     key_range: get_key(0)..get_key(10),
   10656            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10657            4 :                     is_delta: false,
   10658            4 :                 },
   10659            4 :                 PersistentLayerKey {
   10660            4 :                     key_range: get_key(2)..get_key(4),
   10661            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10662            4 :                     is_delta: true,
   10663            4 :                 },
   10664            4 :                 PersistentLayerKey {
   10665            4 :                     key_range: get_key(8)..get_key(10),
   10666            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10667            4 :                     is_delta: true,
   10668            4 :                 },
   10669            4 :             ],
   10670            4 :         );
   10671            4 :         Ok(())
   10672            4 :     }
   10673              : 
   10674              :     #[cfg(feature = "testing")]
   10675              :     #[tokio::test]
   10676            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10677            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10678            4 :             .await
   10679            4 :             .unwrap();
   10680            4 :         let (tenant, ctx) = harness.load().await;
   10681            4 :         let tline_parent = tenant
   10682            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10683            4 :             .await
   10684            4 :             .unwrap();
   10685            4 :         let tline_child = tenant
   10686            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10687            4 :             .await
   10688            4 :             .unwrap();
   10689            4 :         {
   10690            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10691            4 :             assert_eq!(
   10692            4 :                 gc_info_parent.retain_lsns,
   10693            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10694            4 :             );
   10695            4 :         }
   10696            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10697            4 :         tline_child
   10698            4 :             .remote_client
   10699            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10700            4 :             .unwrap();
   10701            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10702            4 :         offload_timeline(&tenant, &tline_child)
   10703            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10704            4 :             .await.unwrap();
   10705            4 :         let child_timeline_id = tline_child.timeline_id;
   10706            4 :         Arc::try_unwrap(tline_child).unwrap();
   10707            4 : 
   10708            4 :         {
   10709            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10710            4 :             assert_eq!(
   10711            4 :                 gc_info_parent.retain_lsns,
   10712            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10713            4 :             );
   10714            4 :         }
   10715            4 : 
   10716            4 :         tenant
   10717            4 :             .get_offloaded_timeline(child_timeline_id)
   10718            4 :             .unwrap()
   10719            4 :             .defuse_for_tenant_drop();
   10720            4 : 
   10721            4 :         Ok(())
   10722            4 :     }
   10723              : 
   10724              :     #[cfg(feature = "testing")]
   10725              :     #[tokio::test]
   10726            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10727            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10728            4 :         let (tenant, ctx) = harness.load().await;
   10729            4 : 
   10730          592 :         fn get_key(id: u32) -> Key {
   10731          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10732          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10733          592 :             key.field6 = id;
   10734          592 :             key
   10735          592 :         }
   10736            4 : 
   10737            4 :         let img_layer = (0..10)
   10738           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10739            4 :             .collect_vec();
   10740            4 : 
   10741            4 :         let delta1 = vec![(
   10742            4 :             get_key(1),
   10743            4 :             Lsn(0x20),
   10744            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10745            4 :         )];
   10746            4 :         let delta4 = vec![(
   10747            4 :             get_key(1),
   10748            4 :             Lsn(0x28),
   10749            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10750            4 :         )];
   10751            4 :         let delta2 = vec![
   10752            4 :             (
   10753            4 :                 get_key(1),
   10754            4 :                 Lsn(0x30),
   10755            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10756            4 :             ),
   10757            4 :             (
   10758            4 :                 get_key(1),
   10759            4 :                 Lsn(0x38),
   10760            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10761            4 :             ),
   10762            4 :         ];
   10763            4 :         let delta3 = vec![
   10764            4 :             (
   10765            4 :                 get_key(8),
   10766            4 :                 Lsn(0x48),
   10767            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10768            4 :             ),
   10769            4 :             (
   10770            4 :                 get_key(9),
   10771            4 :                 Lsn(0x48),
   10772            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10773            4 :             ),
   10774            4 :         ];
   10775            4 : 
   10776            4 :         let tline = tenant
   10777            4 :             .create_test_timeline_with_layers(
   10778            4 :                 TIMELINE_ID,
   10779            4 :                 Lsn(0x10),
   10780            4 :                 DEFAULT_PG_VERSION,
   10781            4 :                 &ctx,
   10782            4 :                 vec![
   10783            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10784            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10785            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10786            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10787            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10788            4 :                 ], // delta layers
   10789            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10790            4 :                 Lsn(0x50),
   10791            4 :             )
   10792            4 :             .await?;
   10793            4 :         {
   10794            4 :             tline
   10795            4 :                 .applied_gc_cutoff_lsn
   10796            4 :                 .lock_for_write()
   10797            4 :                 .store_and_unlock(Lsn(0x30))
   10798            4 :                 .wait()
   10799            4 :                 .await;
   10800            4 :             // Update GC info
   10801            4 :             let mut guard = tline.gc_info.write().unwrap();
   10802            4 :             *guard = GcInfo {
   10803            4 :                 retain_lsns: vec![
   10804            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10805            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10806            4 :                 ],
   10807            4 :                 cutoffs: GcCutoffs {
   10808            4 :                     time: Lsn(0x30),
   10809            4 :                     space: Lsn(0x30),
   10810            4 :                 },
   10811            4 :                 leases: Default::default(),
   10812            4 :                 within_ancestor_pitr: false,
   10813            4 :             };
   10814            4 :         }
   10815            4 : 
   10816            4 :         let expected_result = [
   10817            4 :             Bytes::from_static(b"value 0@0x10"),
   10818            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10819            4 :             Bytes::from_static(b"value 2@0x10"),
   10820            4 :             Bytes::from_static(b"value 3@0x10"),
   10821            4 :             Bytes::from_static(b"value 4@0x10"),
   10822            4 :             Bytes::from_static(b"value 5@0x10"),
   10823            4 :             Bytes::from_static(b"value 6@0x10"),
   10824            4 :             Bytes::from_static(b"value 7@0x10"),
   10825            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10826            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10827            4 :         ];
   10828            4 : 
   10829            4 :         let expected_result_at_gc_horizon = [
   10830            4 :             Bytes::from_static(b"value 0@0x10"),
   10831            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10832            4 :             Bytes::from_static(b"value 2@0x10"),
   10833            4 :             Bytes::from_static(b"value 3@0x10"),
   10834            4 :             Bytes::from_static(b"value 4@0x10"),
   10835            4 :             Bytes::from_static(b"value 5@0x10"),
   10836            4 :             Bytes::from_static(b"value 6@0x10"),
   10837            4 :             Bytes::from_static(b"value 7@0x10"),
   10838            4 :             Bytes::from_static(b"value 8@0x10"),
   10839            4 :             Bytes::from_static(b"value 9@0x10"),
   10840            4 :         ];
   10841            4 : 
   10842            4 :         let expected_result_at_lsn_20 = [
   10843            4 :             Bytes::from_static(b"value 0@0x10"),
   10844            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10845            4 :             Bytes::from_static(b"value 2@0x10"),
   10846            4 :             Bytes::from_static(b"value 3@0x10"),
   10847            4 :             Bytes::from_static(b"value 4@0x10"),
   10848            4 :             Bytes::from_static(b"value 5@0x10"),
   10849            4 :             Bytes::from_static(b"value 6@0x10"),
   10850            4 :             Bytes::from_static(b"value 7@0x10"),
   10851            4 :             Bytes::from_static(b"value 8@0x10"),
   10852            4 :             Bytes::from_static(b"value 9@0x10"),
   10853            4 :         ];
   10854            4 : 
   10855            4 :         let expected_result_at_lsn_10 = [
   10856            4 :             Bytes::from_static(b"value 0@0x10"),
   10857            4 :             Bytes::from_static(b"value 1@0x10"),
   10858            4 :             Bytes::from_static(b"value 2@0x10"),
   10859            4 :             Bytes::from_static(b"value 3@0x10"),
   10860            4 :             Bytes::from_static(b"value 4@0x10"),
   10861            4 :             Bytes::from_static(b"value 5@0x10"),
   10862            4 :             Bytes::from_static(b"value 6@0x10"),
   10863            4 :             Bytes::from_static(b"value 7@0x10"),
   10864            4 :             Bytes::from_static(b"value 8@0x10"),
   10865            4 :             Bytes::from_static(b"value 9@0x10"),
   10866            4 :         ];
   10867            4 : 
   10868           12 :         let verify_result = || async {
   10869           12 :             let gc_horizon = {
   10870           12 :                 let gc_info = tline.gc_info.read().unwrap();
   10871           12 :                 gc_info.cutoffs.time
   10872            4 :             };
   10873          132 :             for idx in 0..10 {
   10874          120 :                 assert_eq!(
   10875          120 :                     tline
   10876          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10877          120 :                         .await
   10878          120 :                         .unwrap(),
   10879          120 :                     &expected_result[idx]
   10880            4 :                 );
   10881          120 :                 assert_eq!(
   10882          120 :                     tline
   10883          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10884          120 :                         .await
   10885          120 :                         .unwrap(),
   10886          120 :                     &expected_result_at_gc_horizon[idx]
   10887            4 :                 );
   10888          120 :                 assert_eq!(
   10889          120 :                     tline
   10890          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10891          120 :                         .await
   10892          120 :                         .unwrap(),
   10893          120 :                     &expected_result_at_lsn_20[idx]
   10894            4 :                 );
   10895          120 :                 assert_eq!(
   10896          120 :                     tline
   10897          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10898          120 :                         .await
   10899          120 :                         .unwrap(),
   10900          120 :                     &expected_result_at_lsn_10[idx]
   10901            4 :                 );
   10902            4 :             }
   10903           24 :         };
   10904            4 : 
   10905            4 :         verify_result().await;
   10906            4 : 
   10907            4 :         let cancel = CancellationToken::new();
   10908            4 :         tline
   10909            4 :             .compact_with_gc(
   10910            4 :                 &cancel,
   10911            4 :                 CompactOptions {
   10912            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10913            4 :                     ..Default::default()
   10914            4 :                 },
   10915            4 :                 &ctx,
   10916            4 :             )
   10917            4 :             .await
   10918            4 :             .unwrap();
   10919            4 :         verify_result().await;
   10920            4 : 
   10921            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10922            4 :         check_layer_map_key_eq(
   10923            4 :             all_layers,
   10924            4 :             vec![
   10925            4 :                 // The original image layer, not compacted
   10926            4 :                 PersistentLayerKey {
   10927            4 :                     key_range: get_key(0)..get_key(10),
   10928            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10929            4 :                     is_delta: false,
   10930            4 :                 },
   10931            4 :                 // Delta layer below the specified above_lsn not compacted
   10932            4 :                 PersistentLayerKey {
   10933            4 :                     key_range: get_key(1)..get_key(2),
   10934            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10935            4 :                     is_delta: true,
   10936            4 :                 },
   10937            4 :                 // Delta layer compacted above the LSN
   10938            4 :                 PersistentLayerKey {
   10939            4 :                     key_range: get_key(1)..get_key(10),
   10940            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10941            4 :                     is_delta: true,
   10942            4 :                 },
   10943            4 :             ],
   10944            4 :         );
   10945            4 : 
   10946            4 :         // compact again
   10947            4 :         tline
   10948            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10949            4 :             .await
   10950            4 :             .unwrap();
   10951            4 :         verify_result().await;
   10952            4 : 
   10953            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10954            4 :         check_layer_map_key_eq(
   10955            4 :             all_layers,
   10956            4 :             vec![
   10957            4 :                 // The compacted image layer (full key range)
   10958            4 :                 PersistentLayerKey {
   10959            4 :                     key_range: Key::MIN..Key::MAX,
   10960            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10961            4 :                     is_delta: false,
   10962            4 :                 },
   10963            4 :                 // All other data in the delta layer
   10964            4 :                 PersistentLayerKey {
   10965            4 :                     key_range: get_key(1)..get_key(10),
   10966            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10967            4 :                     is_delta: true,
   10968            4 :                 },
   10969            4 :             ],
   10970            4 :         );
   10971            4 : 
   10972            4 :         Ok(())
   10973            4 :     }
   10974              : 
   10975              :     #[cfg(feature = "testing")]
   10976              :     #[tokio::test]
   10977            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   10978            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   10979            4 :         let (tenant, ctx) = harness.load().await;
   10980            4 : 
   10981         1016 :         fn get_key(id: u32) -> Key {
   10982         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10983         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10984         1016 :             key.field6 = id;
   10985         1016 :             key
   10986         1016 :         }
   10987            4 : 
   10988            4 :         let img_layer = (0..10)
   10989           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10990            4 :             .collect_vec();
   10991            4 : 
   10992            4 :         let delta1 = vec![(
   10993            4 :             get_key(1),
   10994            4 :             Lsn(0x20),
   10995            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10996            4 :         )];
   10997            4 :         let delta4 = vec![(
   10998            4 :             get_key(1),
   10999            4 :             Lsn(0x28),
   11000            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11001            4 :         )];
   11002            4 :         let delta2 = vec![
   11003            4 :             (
   11004            4 :                 get_key(1),
   11005            4 :                 Lsn(0x30),
   11006            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11007            4 :             ),
   11008            4 :             (
   11009            4 :                 get_key(1),
   11010            4 :                 Lsn(0x38),
   11011            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11012            4 :             ),
   11013            4 :         ];
   11014            4 :         let delta3 = vec![
   11015            4 :             (
   11016            4 :                 get_key(8),
   11017            4 :                 Lsn(0x48),
   11018            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11019            4 :             ),
   11020            4 :             (
   11021            4 :                 get_key(9),
   11022            4 :                 Lsn(0x48),
   11023            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11024            4 :             ),
   11025            4 :         ];
   11026            4 : 
   11027            4 :         let tline = tenant
   11028            4 :             .create_test_timeline_with_layers(
   11029            4 :                 TIMELINE_ID,
   11030            4 :                 Lsn(0x10),
   11031            4 :                 DEFAULT_PG_VERSION,
   11032            4 :                 &ctx,
   11033            4 :                 vec![
   11034            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11035            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11036            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11037            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11038            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11039            4 :                 ], // delta layers
   11040            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11041            4 :                 Lsn(0x50),
   11042            4 :             )
   11043            4 :             .await?;
   11044            4 :         {
   11045            4 :             tline
   11046            4 :                 .applied_gc_cutoff_lsn
   11047            4 :                 .lock_for_write()
   11048            4 :                 .store_and_unlock(Lsn(0x30))
   11049            4 :                 .wait()
   11050            4 :                 .await;
   11051            4 :             // Update GC info
   11052            4 :             let mut guard = tline.gc_info.write().unwrap();
   11053            4 :             *guard = GcInfo {
   11054            4 :                 retain_lsns: vec![
   11055            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11056            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11057            4 :                 ],
   11058            4 :                 cutoffs: GcCutoffs {
   11059            4 :                     time: Lsn(0x30),
   11060            4 :                     space: Lsn(0x30),
   11061            4 :                 },
   11062            4 :                 leases: Default::default(),
   11063            4 :                 within_ancestor_pitr: false,
   11064            4 :             };
   11065            4 :         }
   11066            4 : 
   11067            4 :         let expected_result = [
   11068            4 :             Bytes::from_static(b"value 0@0x10"),
   11069            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11070            4 :             Bytes::from_static(b"value 2@0x10"),
   11071            4 :             Bytes::from_static(b"value 3@0x10"),
   11072            4 :             Bytes::from_static(b"value 4@0x10"),
   11073            4 :             Bytes::from_static(b"value 5@0x10"),
   11074            4 :             Bytes::from_static(b"value 6@0x10"),
   11075            4 :             Bytes::from_static(b"value 7@0x10"),
   11076            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11077            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11078            4 :         ];
   11079            4 : 
   11080            4 :         let expected_result_at_gc_horizon = [
   11081            4 :             Bytes::from_static(b"value 0@0x10"),
   11082            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11083            4 :             Bytes::from_static(b"value 2@0x10"),
   11084            4 :             Bytes::from_static(b"value 3@0x10"),
   11085            4 :             Bytes::from_static(b"value 4@0x10"),
   11086            4 :             Bytes::from_static(b"value 5@0x10"),
   11087            4 :             Bytes::from_static(b"value 6@0x10"),
   11088            4 :             Bytes::from_static(b"value 7@0x10"),
   11089            4 :             Bytes::from_static(b"value 8@0x10"),
   11090            4 :             Bytes::from_static(b"value 9@0x10"),
   11091            4 :         ];
   11092            4 : 
   11093            4 :         let expected_result_at_lsn_20 = [
   11094            4 :             Bytes::from_static(b"value 0@0x10"),
   11095            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11096            4 :             Bytes::from_static(b"value 2@0x10"),
   11097            4 :             Bytes::from_static(b"value 3@0x10"),
   11098            4 :             Bytes::from_static(b"value 4@0x10"),
   11099            4 :             Bytes::from_static(b"value 5@0x10"),
   11100            4 :             Bytes::from_static(b"value 6@0x10"),
   11101            4 :             Bytes::from_static(b"value 7@0x10"),
   11102            4 :             Bytes::from_static(b"value 8@0x10"),
   11103            4 :             Bytes::from_static(b"value 9@0x10"),
   11104            4 :         ];
   11105            4 : 
   11106            4 :         let expected_result_at_lsn_10 = [
   11107            4 :             Bytes::from_static(b"value 0@0x10"),
   11108            4 :             Bytes::from_static(b"value 1@0x10"),
   11109            4 :             Bytes::from_static(b"value 2@0x10"),
   11110            4 :             Bytes::from_static(b"value 3@0x10"),
   11111            4 :             Bytes::from_static(b"value 4@0x10"),
   11112            4 :             Bytes::from_static(b"value 5@0x10"),
   11113            4 :             Bytes::from_static(b"value 6@0x10"),
   11114            4 :             Bytes::from_static(b"value 7@0x10"),
   11115            4 :             Bytes::from_static(b"value 8@0x10"),
   11116            4 :             Bytes::from_static(b"value 9@0x10"),
   11117            4 :         ];
   11118            4 : 
   11119           20 :         let verify_result = || async {
   11120           20 :             let gc_horizon = {
   11121           20 :                 let gc_info = tline.gc_info.read().unwrap();
   11122           20 :                 gc_info.cutoffs.time
   11123            4 :             };
   11124          220 :             for idx in 0..10 {
   11125          200 :                 assert_eq!(
   11126          200 :                     tline
   11127          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11128          200 :                         .await
   11129          200 :                         .unwrap(),
   11130          200 :                     &expected_result[idx]
   11131            4 :                 );
   11132          200 :                 assert_eq!(
   11133          200 :                     tline
   11134          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11135          200 :                         .await
   11136          200 :                         .unwrap(),
   11137          200 :                     &expected_result_at_gc_horizon[idx]
   11138            4 :                 );
   11139          200 :                 assert_eq!(
   11140          200 :                     tline
   11141          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11142          200 :                         .await
   11143          200 :                         .unwrap(),
   11144          200 :                     &expected_result_at_lsn_20[idx]
   11145            4 :                 );
   11146          200 :                 assert_eq!(
   11147          200 :                     tline
   11148          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11149          200 :                         .await
   11150          200 :                         .unwrap(),
   11151          200 :                     &expected_result_at_lsn_10[idx]
   11152            4 :                 );
   11153            4 :             }
   11154           40 :         };
   11155            4 : 
   11156            4 :         verify_result().await;
   11157            4 : 
   11158            4 :         let cancel = CancellationToken::new();
   11159            4 : 
   11160            4 :         tline
   11161            4 :             .compact_with_gc(
   11162            4 :                 &cancel,
   11163            4 :                 CompactOptions {
   11164            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11165            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11166            4 :                     ..Default::default()
   11167            4 :                 },
   11168            4 :                 &ctx,
   11169            4 :             )
   11170            4 :             .await
   11171            4 :             .unwrap();
   11172            4 :         verify_result().await;
   11173            4 : 
   11174            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11175            4 :         check_layer_map_key_eq(
   11176            4 :             all_layers,
   11177            4 :             vec![
   11178            4 :                 // The original image layer, not compacted
   11179            4 :                 PersistentLayerKey {
   11180            4 :                     key_range: get_key(0)..get_key(10),
   11181            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11182            4 :                     is_delta: false,
   11183            4 :                 },
   11184            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11185            4 :                 // the layer 0x28-0x30 into one.
   11186            4 :                 PersistentLayerKey {
   11187            4 :                     key_range: get_key(1)..get_key(2),
   11188            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11189            4 :                     is_delta: true,
   11190            4 :                 },
   11191            4 :                 // Above the upper bound and untouched
   11192            4 :                 PersistentLayerKey {
   11193            4 :                     key_range: get_key(1)..get_key(2),
   11194            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11195            4 :                     is_delta: true,
   11196            4 :                 },
   11197            4 :                 // This layer is untouched
   11198            4 :                 PersistentLayerKey {
   11199            4 :                     key_range: get_key(8)..get_key(10),
   11200            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11201            4 :                     is_delta: true,
   11202            4 :                 },
   11203            4 :             ],
   11204            4 :         );
   11205            4 : 
   11206            4 :         tline
   11207            4 :             .compact_with_gc(
   11208            4 :                 &cancel,
   11209            4 :                 CompactOptions {
   11210            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11211            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11212            4 :                     ..Default::default()
   11213            4 :                 },
   11214            4 :                 &ctx,
   11215            4 :             )
   11216            4 :             .await
   11217            4 :             .unwrap();
   11218            4 :         verify_result().await;
   11219            4 : 
   11220            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11221            4 :         check_layer_map_key_eq(
   11222            4 :             all_layers,
   11223            4 :             vec![
   11224            4 :                 // The original image layer, not compacted
   11225            4 :                 PersistentLayerKey {
   11226            4 :                     key_range: get_key(0)..get_key(10),
   11227            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11228            4 :                     is_delta: false,
   11229            4 :                 },
   11230            4 :                 // Not in the compaction key range, uncompacted
   11231            4 :                 PersistentLayerKey {
   11232            4 :                     key_range: get_key(1)..get_key(2),
   11233            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11234            4 :                     is_delta: true,
   11235            4 :                 },
   11236            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11237            4 :                 PersistentLayerKey {
   11238            4 :                     key_range: get_key(1)..get_key(2),
   11239            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11240            4 :                     is_delta: true,
   11241            4 :                 },
   11242            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11243            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11244            4 :                 // becomes 0x50.
   11245            4 :                 PersistentLayerKey {
   11246            4 :                     key_range: get_key(8)..get_key(10),
   11247            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11248            4 :                     is_delta: true,
   11249            4 :                 },
   11250            4 :             ],
   11251            4 :         );
   11252            4 : 
   11253            4 :         // compact again
   11254            4 :         tline
   11255            4 :             .compact_with_gc(
   11256            4 :                 &cancel,
   11257            4 :                 CompactOptions {
   11258            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11259            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11260            4 :                     ..Default::default()
   11261            4 :                 },
   11262            4 :                 &ctx,
   11263            4 :             )
   11264            4 :             .await
   11265            4 :             .unwrap();
   11266            4 :         verify_result().await;
   11267            4 : 
   11268            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11269            4 :         check_layer_map_key_eq(
   11270            4 :             all_layers,
   11271            4 :             vec![
   11272            4 :                 // The original image layer, not compacted
   11273            4 :                 PersistentLayerKey {
   11274            4 :                     key_range: get_key(0)..get_key(10),
   11275            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11276            4 :                     is_delta: false,
   11277            4 :                 },
   11278            4 :                 // The range gets compacted
   11279            4 :                 PersistentLayerKey {
   11280            4 :                     key_range: get_key(1)..get_key(2),
   11281            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11282            4 :                     is_delta: true,
   11283            4 :                 },
   11284            4 :                 // Not touched during this iteration of compaction
   11285            4 :                 PersistentLayerKey {
   11286            4 :                     key_range: get_key(8)..get_key(10),
   11287            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11288            4 :                     is_delta: true,
   11289            4 :                 },
   11290            4 :             ],
   11291            4 :         );
   11292            4 : 
   11293            4 :         // final full compaction
   11294            4 :         tline
   11295            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11296            4 :             .await
   11297            4 :             .unwrap();
   11298            4 :         verify_result().await;
   11299            4 : 
   11300            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11301            4 :         check_layer_map_key_eq(
   11302            4 :             all_layers,
   11303            4 :             vec![
   11304            4 :                 // The compacted image layer (full key range)
   11305            4 :                 PersistentLayerKey {
   11306            4 :                     key_range: Key::MIN..Key::MAX,
   11307            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11308            4 :                     is_delta: false,
   11309            4 :                 },
   11310            4 :                 // All other data in the delta layer
   11311            4 :                 PersistentLayerKey {
   11312            4 :                     key_range: get_key(1)..get_key(10),
   11313            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11314            4 :                     is_delta: true,
   11315            4 :                 },
   11316            4 :             ],
   11317            4 :         );
   11318            4 : 
   11319            4 :         Ok(())
   11320            4 :     }
   11321              : }
        

Generated by: LCOV version 2.1-beta