LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 35c4cad035e5234d8d9f74554a48bbe25e157302.info Lines: 76.3 % 8546 6518
Test Date: 2025-02-18 19:18:45 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::Other(err) => {
    3154            0 :                 self.compaction_circuit_breaker
    3155            0 :                     .lock()
    3156            0 :                     .unwrap()
    3157            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3158            0 :             }
    3159              :         }
    3160            0 :     }
    3161              : 
    3162              :     /// Cancel scheduled compaction tasks
    3163            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3164            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3165            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3166            0 :             q.cancel_scheduled();
    3167            0 :         }
    3168            0 :     }
    3169              : 
    3170            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3171            0 :         &self,
    3172            0 :         timeline_id: TimelineId,
    3173            0 :     ) -> Vec<CompactInfoResponse> {
    3174            0 :         let res = {
    3175            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3176            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3177              :         };
    3178            0 :         let Some((running, remaining)) = res else {
    3179            0 :             return Vec::new();
    3180              :         };
    3181            0 :         let mut result = Vec::new();
    3182            0 :         if let Some((id, running)) = running {
    3183            0 :             result.extend(running.into_compact_info_resp(id, true));
    3184            0 :         }
    3185            0 :         for (id, job) in remaining {
    3186            0 :             result.extend(job.into_compact_info_resp(id, false));
    3187            0 :         }
    3188            0 :         result
    3189            0 :     }
    3190              : 
    3191              :     /// Schedule a compaction task for a timeline.
    3192            0 :     pub(crate) async fn schedule_compaction(
    3193            0 :         &self,
    3194            0 :         timeline_id: TimelineId,
    3195            0 :         options: CompactOptions,
    3196            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3197            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3198            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3199            0 :         let q = guard
    3200            0 :             .entry(timeline_id)
    3201            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3202            0 :         q.schedule_manual_compaction(options, Some(tx));
    3203            0 :         Ok(rx)
    3204            0 :     }
    3205              : 
    3206              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3207            0 :     async fn housekeeping(&self) {
    3208            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3209            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3210            0 :         let timelines = self
    3211            0 :             .timelines
    3212            0 :             .lock()
    3213            0 :             .unwrap()
    3214            0 :             .values()
    3215            0 :             .filter(|tli| tli.is_active())
    3216            0 :             .cloned()
    3217            0 :             .collect_vec();
    3218              : 
    3219            0 :         for timeline in timelines {
    3220            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3221              :         }
    3222              : 
    3223              :         // Shut down walredo if idle.
    3224              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3225            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3226            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3227            0 :         }
    3228            0 :     }
    3229              : 
    3230            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3231            0 :         let timelines = self.timelines.lock().unwrap();
    3232            0 :         !timelines
    3233            0 :             .iter()
    3234            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3235            0 :     }
    3236              : 
    3237         3468 :     pub fn current_state(&self) -> TenantState {
    3238         3468 :         self.state.borrow().clone()
    3239         3468 :     }
    3240              : 
    3241         1944 :     pub fn is_active(&self) -> bool {
    3242         1944 :         self.current_state() == TenantState::Active
    3243         1944 :     }
    3244              : 
    3245            0 :     pub fn generation(&self) -> Generation {
    3246            0 :         self.generation
    3247            0 :     }
    3248              : 
    3249            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3250            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3251            0 :     }
    3252              : 
    3253              :     /// Changes tenant status to active, unless shutdown was already requested.
    3254              :     ///
    3255              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3256              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3257            0 :     fn activate(
    3258            0 :         self: &Arc<Self>,
    3259            0 :         broker_client: BrokerClientChannel,
    3260            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3261            0 :         ctx: &RequestContext,
    3262            0 :     ) {
    3263            0 :         span::debug_assert_current_span_has_tenant_id();
    3264            0 : 
    3265            0 :         let mut activating = false;
    3266            0 :         self.state.send_modify(|current_state| {
    3267              :             use pageserver_api::models::ActivatingFrom;
    3268            0 :             match &*current_state {
    3269              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3270            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3271              :                 }
    3272            0 :                 TenantState::Attaching => {
    3273            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3274            0 :                 }
    3275            0 :             }
    3276            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3277            0 :             activating = true;
    3278            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3279            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3280            0 :         });
    3281            0 : 
    3282            0 :         if activating {
    3283            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3284            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3285            0 :             let timelines_to_activate = timelines_accessor
    3286            0 :                 .values()
    3287            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3288            0 : 
    3289            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3290            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3291            0 : 
    3292            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3293            0 :             // down when they notice that the tenant is inactive.
    3294            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3295            0 : 
    3296            0 :             let mut activated_timelines = 0;
    3297              : 
    3298            0 :             for timeline in timelines_to_activate {
    3299            0 :                 timeline.activate(
    3300            0 :                     self.clone(),
    3301            0 :                     broker_client.clone(),
    3302            0 :                     background_jobs_can_start,
    3303            0 :                     ctx,
    3304            0 :                 );
    3305            0 :                 activated_timelines += 1;
    3306            0 :             }
    3307              : 
    3308            0 :             self.state.send_modify(move |current_state| {
    3309            0 :                 assert!(
    3310            0 :                     matches!(current_state, TenantState::Activating(_)),
    3311            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3312              :                 );
    3313            0 :                 *current_state = TenantState::Active;
    3314            0 : 
    3315            0 :                 let elapsed = self.constructed_at.elapsed();
    3316            0 :                 let total_timelines = timelines_accessor.len();
    3317            0 : 
    3318            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3319            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3320            0 :                 info!(
    3321            0 :                     since_creation_millis = elapsed.as_millis(),
    3322            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3323            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3324            0 :                     activated_timelines,
    3325            0 :                     total_timelines,
    3326            0 :                     post_state = <&'static str>::from(&*current_state),
    3327            0 :                     "activation attempt finished"
    3328              :                 );
    3329              : 
    3330            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3331            0 :             });
    3332            0 :         }
    3333            0 :     }
    3334              : 
    3335              :     /// Shutdown the tenant and join all of the spawned tasks.
    3336              :     ///
    3337              :     /// The method caters for all use-cases:
    3338              :     /// - pageserver shutdown (freeze_and_flush == true)
    3339              :     /// - detach + ignore (freeze_and_flush == false)
    3340              :     ///
    3341              :     /// This will attempt to shutdown even if tenant is broken.
    3342              :     ///
    3343              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3344              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3345              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3346              :     /// the ongoing shutdown.
    3347           12 :     async fn shutdown(
    3348           12 :         &self,
    3349           12 :         shutdown_progress: completion::Barrier,
    3350           12 :         shutdown_mode: timeline::ShutdownMode,
    3351           12 :     ) -> Result<(), completion::Barrier> {
    3352           12 :         span::debug_assert_current_span_has_tenant_id();
    3353              : 
    3354              :         // Set tenant (and its timlines) to Stoppping state.
    3355              :         //
    3356              :         // Since we can only transition into Stopping state after activation is complete,
    3357              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3358              :         //
    3359              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3360              :         // 1. Lock out any new requests to the tenants.
    3361              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3362              :         // 3. Signal cancellation for other tenant background loops.
    3363              :         // 4. ???
    3364              :         //
    3365              :         // The waiting for the cancellation is not done uniformly.
    3366              :         // We certainly wait for WAL receivers to shut down.
    3367              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3368              :         // But the tenant background loops are joined-on in our caller.
    3369              :         // It's mesed up.
    3370              :         // we just ignore the failure to stop
    3371              : 
    3372              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3373              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3374              :         // is very slow.
    3375           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3376            0 :             self.cancel.cancel();
    3377            0 : 
    3378            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3379            0 :             // are children of ours, so their flush loops will have shut down already
    3380            0 :             timeline::ShutdownMode::Hard
    3381              :         } else {
    3382           12 :             shutdown_mode
    3383              :         };
    3384              : 
    3385           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3386           12 :             Ok(()) => {}
    3387            0 :             Err(SetStoppingError::Broken) => {
    3388            0 :                 // assume that this is acceptable
    3389            0 :             }
    3390            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3391            0 :                 // give caller the option to wait for this this shutdown
    3392            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3393            0 :                 return Err(other);
    3394              :             }
    3395              :         };
    3396              : 
    3397           12 :         let mut js = tokio::task::JoinSet::new();
    3398           12 :         {
    3399           12 :             let timelines = self.timelines.lock().unwrap();
    3400           12 :             timelines.values().for_each(|timeline| {
    3401           12 :                 let timeline = Arc::clone(timeline);
    3402           12 :                 let timeline_id = timeline.timeline_id;
    3403           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3404           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3405           12 :             });
    3406           12 :         }
    3407           12 :         {
    3408           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3409           12 :             timelines_offloaded.values().for_each(|timeline| {
    3410            0 :                 timeline.defuse_for_tenant_drop();
    3411           12 :             });
    3412           12 :         }
    3413           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3414           12 :         tracing::info!("Waiting for timelines...");
    3415           24 :         while let Some(res) = js.join_next().await {
    3416            0 :             match res {
    3417           12 :                 Ok(()) => {}
    3418            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3419            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3420            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3421              :             }
    3422              :         }
    3423              : 
    3424           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3425            0 :             tracing::info!("Flushing deletion queue");
    3426            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3427            0 :                 match e {
    3428            0 :                     DeletionQueueError::ShuttingDown => {
    3429            0 :                         // This is the only error we expect for now. In the future, if more error
    3430            0 :                         // variants are added, we should handle them here.
    3431            0 :                     }
    3432              :                 }
    3433            0 :             }
    3434           12 :         }
    3435              : 
    3436              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3437              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3438           12 :         tracing::debug!("Cancelling CancellationToken");
    3439           12 :         self.cancel.cancel();
    3440           12 : 
    3441           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3442           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3443           12 :         //
    3444           12 :         // this will additionally shutdown and await all timeline tasks.
    3445           12 :         tracing::debug!("Waiting for tasks...");
    3446           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3447              : 
    3448           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3449           12 :             walredo_mgr.shutdown().await;
    3450            0 :         }
    3451              : 
    3452              :         // Wait for any in-flight operations to complete
    3453           12 :         self.gate.close().await;
    3454              : 
    3455           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3456           12 : 
    3457           12 :         Ok(())
    3458           12 :     }
    3459              : 
    3460              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3461              :     ///
    3462              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3463              :     ///
    3464              :     /// This function is not cancel-safe!
    3465              :     ///
    3466              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3467              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3468           12 :     async fn set_stopping(
    3469           12 :         &self,
    3470           12 :         progress: completion::Barrier,
    3471           12 :         _allow_transition_from_loading: bool,
    3472           12 :         allow_transition_from_attaching: bool,
    3473           12 :     ) -> Result<(), SetStoppingError> {
    3474           12 :         let mut rx = self.state.subscribe();
    3475           12 : 
    3476           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3477           12 :         rx.wait_for(|state| match state {
    3478            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3479              :             TenantState::Activating(_) | TenantState::Attaching => {
    3480            0 :                 info!(
    3481            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3482            0 :                     <&'static str>::from(state)
    3483              :                 );
    3484            0 :                 false
    3485              :             }
    3486           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3487           12 :         })
    3488           12 :         .await
    3489           12 :         .expect("cannot drop self.state while on a &self method");
    3490           12 : 
    3491           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3492           12 :         let mut err = None;
    3493           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3494              :             TenantState::Activating(_) => {
    3495            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3496              :             }
    3497              :             TenantState::Attaching => {
    3498            0 :                 if !allow_transition_from_attaching {
    3499            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3500            0 :                 };
    3501            0 :                 *current_state = TenantState::Stopping { progress };
    3502            0 :                 true
    3503              :             }
    3504              :             TenantState::Active => {
    3505              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3506              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3507              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3508           12 :                 *current_state = TenantState::Stopping { progress };
    3509           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3510           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3511           12 :                 true
    3512              :             }
    3513            0 :             TenantState::Broken { reason, .. } => {
    3514            0 :                 info!(
    3515            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3516              :                 );
    3517            0 :                 err = Some(SetStoppingError::Broken);
    3518            0 :                 false
    3519              :             }
    3520            0 :             TenantState::Stopping { progress } => {
    3521            0 :                 info!("Tenant is already in Stopping state");
    3522            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3523            0 :                 false
    3524              :             }
    3525           12 :         });
    3526           12 :         match (stopping, err) {
    3527           12 :             (true, None) => {} // continue
    3528            0 :             (false, Some(err)) => return Err(err),
    3529            0 :             (true, Some(_)) => unreachable!(
    3530            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3531            0 :             ),
    3532            0 :             (false, None) => unreachable!(
    3533            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3534            0 :             ),
    3535              :         }
    3536              : 
    3537           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3538           12 :         let not_broken_timelines = timelines_accessor
    3539           12 :             .values()
    3540           12 :             .filter(|timeline| !timeline.is_broken());
    3541           24 :         for timeline in not_broken_timelines {
    3542           12 :             timeline.set_state(TimelineState::Stopping);
    3543           12 :         }
    3544           12 :         Ok(())
    3545           12 :     }
    3546              : 
    3547              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3548              :     /// `remove_tenant_from_memory`
    3549              :     ///
    3550              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3551              :     ///
    3552              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3553            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3554            0 :         let mut rx = self.state.subscribe();
    3555            0 : 
    3556            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3557            0 :         // So, wait until it's done.
    3558            0 :         rx.wait_for(|state| match state {
    3559              :             TenantState::Activating(_) | TenantState::Attaching => {
    3560            0 :                 info!(
    3561            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3562            0 :                     <&'static str>::from(state)
    3563              :                 );
    3564            0 :                 false
    3565              :             }
    3566            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3567            0 :         })
    3568            0 :         .await
    3569            0 :         .expect("cannot drop self.state while on a &self method");
    3570            0 : 
    3571            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3572            0 :         self.set_broken_no_wait(reason)
    3573            0 :     }
    3574              : 
    3575            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3576            0 :         let reason = reason.to_string();
    3577            0 :         self.state.send_modify(|current_state| {
    3578            0 :             match *current_state {
    3579              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3580            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3581              :                 }
    3582              :                 TenantState::Active => {
    3583            0 :                     if cfg!(feature = "testing") {
    3584            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3585            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3586              :                     } else {
    3587            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3588              :                     }
    3589              :                 }
    3590              :                 TenantState::Broken { .. } => {
    3591            0 :                     warn!("Tenant is already in Broken state");
    3592              :                 }
    3593              :                 // This is the only "expected" path, any other path is a bug.
    3594              :                 TenantState::Stopping { .. } => {
    3595            0 :                     warn!(
    3596            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3597              :                         reason
    3598              :                     );
    3599            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3600              :                 }
    3601              :            }
    3602            0 :         });
    3603            0 :     }
    3604              : 
    3605            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3606            0 :         self.state.subscribe()
    3607            0 :     }
    3608              : 
    3609              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3610              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3611            0 :     pub(crate) fn activate_now(&self) {
    3612            0 :         self.activate_now_sem.add_permits(1);
    3613            0 :     }
    3614              : 
    3615            0 :     pub(crate) async fn wait_to_become_active(
    3616            0 :         &self,
    3617            0 :         timeout: Duration,
    3618            0 :     ) -> Result<(), GetActiveTenantError> {
    3619            0 :         let mut receiver = self.state.subscribe();
    3620              :         loop {
    3621            0 :             let current_state = receiver.borrow_and_update().clone();
    3622            0 :             match current_state {
    3623              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3624              :                     // in these states, there's a chance that we can reach ::Active
    3625            0 :                     self.activate_now();
    3626            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3627            0 :                         Ok(r) => {
    3628            0 :                             r.map_err(
    3629            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3630              :                                 // Tenant existed but was dropped: report it as non-existent
    3631            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3632            0 :                         )?
    3633              :                         }
    3634              :                         Err(TimeoutCancellableError::Cancelled) => {
    3635            0 :                             return Err(GetActiveTenantError::Cancelled);
    3636              :                         }
    3637              :                         Err(TimeoutCancellableError::Timeout) => {
    3638            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3639            0 :                                 latest_state: Some(self.current_state()),
    3640            0 :                                 wait_time: timeout,
    3641            0 :                             });
    3642              :                         }
    3643              :                     }
    3644              :                 }
    3645              :                 TenantState::Active { .. } => {
    3646            0 :                     return Ok(());
    3647              :                 }
    3648            0 :                 TenantState::Broken { reason, .. } => {
    3649            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3650            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3651            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3652              :                 }
    3653              :                 TenantState::Stopping { .. } => {
    3654              :                     // There's no chance the tenant can transition back into ::Active
    3655            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3656              :                 }
    3657              :             }
    3658              :         }
    3659            0 :     }
    3660              : 
    3661            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3662            0 :         self.tenant_conf.load().location.attach_mode
    3663            0 :     }
    3664              : 
    3665              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3666              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3667              :     /// rare external API calls, like a reconciliation at startup.
    3668            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3669            0 :         let conf = self.tenant_conf.load();
    3670              : 
    3671            0 :         let location_config_mode = match conf.location.attach_mode {
    3672            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3673            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3674            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3675              :         };
    3676              : 
    3677              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3678            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3679            0 : 
    3680            0 :         models::LocationConfig {
    3681            0 :             mode: location_config_mode,
    3682            0 :             generation: self.generation.into(),
    3683            0 :             secondary_conf: None,
    3684            0 :             shard_number: self.shard_identity.number.0,
    3685            0 :             shard_count: self.shard_identity.count.literal(),
    3686            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3687            0 :             tenant_conf: tenant_config,
    3688            0 :         }
    3689            0 :     }
    3690              : 
    3691            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3692            0 :         &self.tenant_shard_id
    3693            0 :     }
    3694              : 
    3695            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3696            0 :         self.shard_identity.stripe_size
    3697            0 :     }
    3698              : 
    3699            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3700            0 :         self.generation
    3701            0 :     }
    3702              : 
    3703              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3704              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3705              :     /// resetting this tenant to a valid state if we fail.
    3706            0 :     pub(crate) async fn split_prepare(
    3707            0 :         &self,
    3708            0 :         child_shards: &Vec<TenantShardId>,
    3709            0 :     ) -> anyhow::Result<()> {
    3710            0 :         let (timelines, offloaded) = {
    3711            0 :             let timelines = self.timelines.lock().unwrap();
    3712            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3713            0 :             (timelines.clone(), offloaded.clone())
    3714            0 :         };
    3715            0 :         let timelines_iter = timelines
    3716            0 :             .values()
    3717            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3718            0 :             .chain(
    3719            0 :                 offloaded
    3720            0 :                     .values()
    3721            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3722            0 :             );
    3723            0 :         for timeline in timelines_iter {
    3724              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3725              :             // to ensure that they do not start a split if currently in the process of doing these.
    3726              : 
    3727            0 :             let timeline_id = timeline.timeline_id();
    3728              : 
    3729            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3730              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3731              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3732              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3733            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3734            0 :                 timeline
    3735            0 :                     .remote_client
    3736            0 :                     .schedule_index_upload_for_file_changes()?;
    3737            0 :                 timeline.remote_client.wait_completion().await?;
    3738            0 :             }
    3739              : 
    3740            0 :             let remote_client = match timeline {
    3741            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3742            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3743            0 :                     let remote_client = self
    3744            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3745            0 :                     Arc::new(remote_client)
    3746              :                 }
    3747              :             };
    3748              : 
    3749              :             // Shut down the timeline's remote client: this means that the indices we write
    3750              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3751            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3752            0 :             remote_client.shutdown().await;
    3753              : 
    3754              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3755              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3756              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3757              :             // we use here really is the remotely persistent one).
    3758            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3759            0 :             let result = remote_client
    3760            0 :                 .download_index_file(&self.cancel)
    3761            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))
    3762            0 :                 .await?;
    3763            0 :             let index_part = match result {
    3764              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3765            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3766              :                 }
    3767            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3768              :             };
    3769              : 
    3770            0 :             for child_shard in child_shards {
    3771            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3772            0 :                 upload_index_part(
    3773            0 :                     &self.remote_storage,
    3774            0 :                     child_shard,
    3775            0 :                     &timeline_id,
    3776            0 :                     self.generation,
    3777            0 :                     &index_part,
    3778            0 :                     &self.cancel,
    3779            0 :                 )
    3780            0 :                 .await?;
    3781              :             }
    3782              :         }
    3783              : 
    3784            0 :         let tenant_manifest = self.build_tenant_manifest();
    3785            0 :         for child_shard in child_shards {
    3786            0 :             tracing::info!(
    3787            0 :                 "Uploading tenant manifest for child {}",
    3788            0 :                 child_shard.to_index()
    3789              :             );
    3790            0 :             upload_tenant_manifest(
    3791            0 :                 &self.remote_storage,
    3792            0 :                 child_shard,
    3793            0 :                 self.generation,
    3794            0 :                 &tenant_manifest,
    3795            0 :                 &self.cancel,
    3796            0 :             )
    3797            0 :             .await?;
    3798              :         }
    3799              : 
    3800            0 :         Ok(())
    3801            0 :     }
    3802              : 
    3803            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3804            0 :         let mut result = TopTenantShardItem {
    3805            0 :             id: self.tenant_shard_id,
    3806            0 :             resident_size: 0,
    3807            0 :             physical_size: 0,
    3808            0 :             max_logical_size: 0,
    3809            0 :         };
    3810              : 
    3811            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3812            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3813            0 : 
    3814            0 :             result.physical_size += timeline
    3815            0 :                 .remote_client
    3816            0 :                 .metrics
    3817            0 :                 .remote_physical_size_gauge
    3818            0 :                 .get();
    3819            0 :             result.max_logical_size = std::cmp::max(
    3820            0 :                 result.max_logical_size,
    3821            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3822            0 :             );
    3823            0 :         }
    3824              : 
    3825            0 :         result
    3826            0 :     }
    3827              : }
    3828              : 
    3829              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3830              : /// perform a topological sort, so that the parent of each timeline comes
    3831              : /// before the children.
    3832              : /// E extracts the ancestor from T
    3833              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3834          444 : fn tree_sort_timelines<T, E>(
    3835          444 :     timelines: HashMap<TimelineId, T>,
    3836          444 :     extractor: E,
    3837          444 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3838          444 : where
    3839          444 :     E: Fn(&T) -> Option<TimelineId>,
    3840          444 : {
    3841          444 :     let mut result = Vec::with_capacity(timelines.len());
    3842          444 : 
    3843          444 :     let mut now = Vec::with_capacity(timelines.len());
    3844          444 :     // (ancestor, children)
    3845          444 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3846          444 :         HashMap::with_capacity(timelines.len());
    3847              : 
    3848          456 :     for (timeline_id, value) in timelines {
    3849           12 :         if let Some(ancestor_id) = extractor(&value) {
    3850            4 :             let children = later.entry(ancestor_id).or_default();
    3851            4 :             children.push((timeline_id, value));
    3852            8 :         } else {
    3853            8 :             now.push((timeline_id, value));
    3854            8 :         }
    3855              :     }
    3856              : 
    3857          456 :     while let Some((timeline_id, metadata)) = now.pop() {
    3858           12 :         result.push((timeline_id, metadata));
    3859              :         // All children of this can be loaded now
    3860           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3861            4 :             now.append(&mut children);
    3862            8 :         }
    3863              :     }
    3864              : 
    3865              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3866          444 :     if !later.is_empty() {
    3867            0 :         for (missing_id, orphan_ids) in later {
    3868            0 :             for (orphan_id, _) in orphan_ids {
    3869            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3870              :             }
    3871              :         }
    3872            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3873          444 :     }
    3874          444 : 
    3875          444 :     Ok(result)
    3876          444 : }
    3877              : 
    3878              : enum ActivateTimelineArgs {
    3879              :     Yes {
    3880              :         broker_client: storage_broker::BrokerClientChannel,
    3881              :     },
    3882              :     No,
    3883              : }
    3884              : 
    3885              : impl Tenant {
    3886            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3887            0 :         self.tenant_conf.load().tenant_conf.clone()
    3888            0 :     }
    3889              : 
    3890            0 :     pub fn effective_config(&self) -> TenantConf {
    3891            0 :         self.tenant_specific_overrides()
    3892            0 :             .merge(self.conf.default_tenant_conf.clone())
    3893            0 :     }
    3894              : 
    3895            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3896            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3897            0 :         tenant_conf
    3898            0 :             .checkpoint_distance
    3899            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3900            0 :     }
    3901              : 
    3902            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3903            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3904            0 :         tenant_conf
    3905            0 :             .checkpoint_timeout
    3906            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3907            0 :     }
    3908              : 
    3909            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3910            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3911            0 :         tenant_conf
    3912            0 :             .compaction_target_size
    3913            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3914            0 :     }
    3915              : 
    3916            0 :     pub fn get_compaction_period(&self) -> Duration {
    3917            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3918            0 :         tenant_conf
    3919            0 :             .compaction_period
    3920            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3921            0 :     }
    3922              : 
    3923            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3924            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3925            0 :         tenant_conf
    3926            0 :             .compaction_threshold
    3927            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3928            0 :     }
    3929              : 
    3930            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3931            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3932            0 :         tenant_conf
    3933            0 :             .rel_size_v2_enabled
    3934            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    3935            0 :     }
    3936              : 
    3937            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3938            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3939            0 :         tenant_conf
    3940            0 :             .compaction_upper_limit
    3941            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3942            0 :     }
    3943              : 
    3944            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    3945            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3946            0 :         tenant_conf
    3947            0 :             .compaction_l0_first
    3948            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    3949            0 :     }
    3950              : 
    3951            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3952            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3953            0 :         tenant_conf
    3954            0 :             .gc_horizon
    3955            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3956            0 :     }
    3957              : 
    3958            0 :     pub fn get_gc_period(&self) -> Duration {
    3959            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3960            0 :         tenant_conf
    3961            0 :             .gc_period
    3962            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3963            0 :     }
    3964              : 
    3965            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3966            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3967            0 :         tenant_conf
    3968            0 :             .image_creation_threshold
    3969            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3970            0 :     }
    3971              : 
    3972            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3973            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3974            0 :         tenant_conf
    3975            0 :             .pitr_interval
    3976            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3977            0 :     }
    3978              : 
    3979            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3980            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3981            0 :         tenant_conf
    3982            0 :             .min_resident_size_override
    3983            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3984            0 :     }
    3985              : 
    3986            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3987            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3988            0 :         let heatmap_period = tenant_conf
    3989            0 :             .heatmap_period
    3990            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3991            0 :         if heatmap_period.is_zero() {
    3992            0 :             None
    3993              :         } else {
    3994            0 :             Some(heatmap_period)
    3995              :         }
    3996            0 :     }
    3997              : 
    3998            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3999            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4000            8 :         tenant_conf
    4001            8 :             .lsn_lease_length
    4002            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4003            8 :     }
    4004              : 
    4005            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4006            0 :         if self.conf.timeline_offloading {
    4007            0 :             return true;
    4008            0 :         }
    4009            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4010            0 :         tenant_conf
    4011            0 :             .timeline_offloading
    4012            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4013            0 :     }
    4014              : 
    4015              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4016            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4017            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    4018            4 : 
    4019            4 :         let mut timeline_manifests = timelines_offloaded
    4020            4 :             .iter()
    4021            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    4022            4 :             .collect::<Vec<_>>();
    4023            4 :         // Sort the manifests so that our output is deterministic
    4024            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    4025            4 : 
    4026            4 :         TenantManifest {
    4027            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4028            4 :             offloaded_timelines: timeline_manifests,
    4029            4 :         }
    4030            4 :     }
    4031              : 
    4032            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    4033            0 :         &self,
    4034            0 :         update: F,
    4035            0 :     ) -> anyhow::Result<TenantConfOpt> {
    4036            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4037            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    4038            0 :         // this race is not possible if both request types come from the storage
    4039            0 :         // controller (as they should!) because an exclusive op lock is required
    4040            0 :         // on the storage controller side.
    4041            0 : 
    4042            0 :         self.tenant_conf
    4043            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4044            0 :                 Ok(Arc::new(AttachedTenantConf {
    4045            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4046            0 :                     location: attached_conf.location,
    4047            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4048              :                 }))
    4049            0 :             })?;
    4050              : 
    4051            0 :         let updated = self.tenant_conf.load();
    4052            0 : 
    4053            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4054            0 :         // Don't hold self.timelines.lock() during the notifies.
    4055            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4056            0 :         // mutexes in struct Timeline in the future.
    4057            0 :         let timelines = self.list_timelines();
    4058            0 :         for timeline in timelines {
    4059            0 :             timeline.tenant_conf_updated(&updated);
    4060            0 :         }
    4061              : 
    4062            0 :         Ok(updated.tenant_conf.clone())
    4063            0 :     }
    4064              : 
    4065            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4066            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4067            0 : 
    4068            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4069            0 : 
    4070            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4071            0 :         // Don't hold self.timelines.lock() during the notifies.
    4072            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4073            0 :         // mutexes in struct Timeline in the future.
    4074            0 :         let timelines = self.list_timelines();
    4075            0 :         for timeline in timelines {
    4076            0 :             timeline.tenant_conf_updated(&new_conf);
    4077            0 :         }
    4078            0 :     }
    4079              : 
    4080          444 :     fn get_pagestream_throttle_config(
    4081          444 :         psconf: &'static PageServerConf,
    4082          444 :         overrides: &TenantConfOpt,
    4083          444 :     ) -> throttle::Config {
    4084          444 :         overrides
    4085          444 :             .timeline_get_throttle
    4086          444 :             .clone()
    4087          444 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4088          444 :     }
    4089              : 
    4090            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    4091            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4092            0 :         self.pagestream_throttle.reconfigure(conf)
    4093            0 :     }
    4094              : 
    4095              :     /// Helper function to create a new Timeline struct.
    4096              :     ///
    4097              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4098              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4099              :     /// map.
    4100              :     ///
    4101              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4102              :     /// and we might not have the ancestor present anymore which is fine for to be
    4103              :     /// deleted timelines.
    4104              :     #[allow(clippy::too_many_arguments)]
    4105          896 :     fn create_timeline_struct(
    4106          896 :         &self,
    4107          896 :         new_timeline_id: TimelineId,
    4108          896 :         new_metadata: &TimelineMetadata,
    4109          896 :         previous_heatmap: Option<PreviousHeatmap>,
    4110          896 :         ancestor: Option<Arc<Timeline>>,
    4111          896 :         resources: TimelineResources,
    4112          896 :         cause: CreateTimelineCause,
    4113          896 :         create_idempotency: CreateTimelineIdempotency,
    4114          896 :     ) -> anyhow::Result<Arc<Timeline>> {
    4115          896 :         let state = match cause {
    4116              :             CreateTimelineCause::Load => {
    4117          896 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4118          896 :                 anyhow::ensure!(
    4119          896 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4120            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4121              :                 );
    4122          896 :                 TimelineState::Loading
    4123              :             }
    4124            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4125              :         };
    4126              : 
    4127          896 :         let pg_version = new_metadata.pg_version();
    4128          896 : 
    4129          896 :         let timeline = Timeline::new(
    4130          896 :             self.conf,
    4131          896 :             Arc::clone(&self.tenant_conf),
    4132          896 :             new_metadata,
    4133          896 :             previous_heatmap,
    4134          896 :             ancestor,
    4135          896 :             new_timeline_id,
    4136          896 :             self.tenant_shard_id,
    4137          896 :             self.generation,
    4138          896 :             self.shard_identity,
    4139          896 :             self.walredo_mgr.clone(),
    4140          896 :             resources,
    4141          896 :             pg_version,
    4142          896 :             state,
    4143          896 :             self.attach_wal_lag_cooldown.clone(),
    4144          896 :             create_idempotency,
    4145          896 :             self.cancel.child_token(),
    4146          896 :         );
    4147          896 : 
    4148          896 :         Ok(timeline)
    4149          896 :     }
    4150              : 
    4151              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4152              :     /// to ensure proper cleanup of background tasks and metrics.
    4153              :     //
    4154              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4155              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4156              :     #[allow(clippy::too_many_arguments)]
    4157          444 :     fn new(
    4158          444 :         state: TenantState,
    4159          444 :         conf: &'static PageServerConf,
    4160          444 :         attached_conf: AttachedTenantConf,
    4161          444 :         shard_identity: ShardIdentity,
    4162          444 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4163          444 :         tenant_shard_id: TenantShardId,
    4164          444 :         remote_storage: GenericRemoteStorage,
    4165          444 :         deletion_queue_client: DeletionQueueClient,
    4166          444 :         l0_flush_global_state: L0FlushGlobalState,
    4167          444 :     ) -> Tenant {
    4168          444 :         debug_assert!(
    4169          444 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4170              :         );
    4171              : 
    4172          444 :         let (state, mut rx) = watch::channel(state);
    4173          444 : 
    4174          444 :         tokio::spawn(async move {
    4175          443 :             // reflect tenant state in metrics:
    4176          443 :             // - global per tenant state: TENANT_STATE_METRIC
    4177          443 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4178          443 :             //
    4179          443 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4180          443 :             // alerting.
    4181          443 : 
    4182          443 :             let tid = tenant_shard_id.to_string();
    4183          443 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4184          443 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4185              : 
    4186          886 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4187          886 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4188          886 :             }
    4189              : 
    4190          443 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4191          443 : 
    4192          443 :             let is_broken = tuple.1;
    4193          443 :             let mut counted_broken = if is_broken {
    4194              :                 // add the id to the set right away, there should not be any updates on the channel
    4195              :                 // after before tenant is removed, if ever
    4196            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4197            0 :                 true
    4198              :             } else {
    4199          443 :                 false
    4200              :             };
    4201              : 
    4202              :             loop {
    4203          886 :                 let labels = &tuple.0;
    4204          886 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4205          886 :                 current.inc();
    4206          886 : 
    4207          886 :                 if rx.changed().await.is_err() {
    4208              :                     // tenant has been dropped
    4209           28 :                     current.dec();
    4210           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4211           28 :                     break;
    4212          443 :                 }
    4213          443 : 
    4214          443 :                 current.dec();
    4215          443 :                 tuple = inspect_state(&rx.borrow_and_update());
    4216          443 : 
    4217          443 :                 let is_broken = tuple.1;
    4218          443 :                 if is_broken && !counted_broken {
    4219            0 :                     counted_broken = true;
    4220            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4221            0 :                     // access
    4222            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4223          443 :                 }
    4224              :             }
    4225          444 :         });
    4226          444 : 
    4227          444 :         Tenant {
    4228          444 :             tenant_shard_id,
    4229          444 :             shard_identity,
    4230          444 :             generation: attached_conf.location.generation,
    4231          444 :             conf,
    4232          444 :             // using now here is good enough approximation to catch tenants with really long
    4233          444 :             // activation times.
    4234          444 :             constructed_at: Instant::now(),
    4235          444 :             timelines: Mutex::new(HashMap::new()),
    4236          444 :             timelines_creating: Mutex::new(HashSet::new()),
    4237          444 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4238          444 :             tenant_manifest_upload: Default::default(),
    4239          444 :             gc_cs: tokio::sync::Mutex::new(()),
    4240          444 :             walredo_mgr,
    4241          444 :             remote_storage,
    4242          444 :             deletion_queue_client,
    4243          444 :             state,
    4244          444 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4245          444 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4246          444 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4247          444 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4248          444 :                 format!("compaction-{tenant_shard_id}"),
    4249          444 :                 5,
    4250          444 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4251          444 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4252          444 :                 // use an extremely long backoff.
    4253          444 :                 Some(Duration::from_secs(3600 * 24)),
    4254          444 :             )),
    4255          444 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4256          444 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4257          444 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4258          444 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4259          444 :             cancel: CancellationToken::default(),
    4260          444 :             gate: Gate::default(),
    4261          444 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4262          444 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4263          444 :             )),
    4264          444 :             pagestream_throttle_metrics: Arc::new(
    4265          444 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4266          444 :             ),
    4267          444 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4268          444 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4269          444 :             gc_block: Default::default(),
    4270          444 :             l0_flush_global_state,
    4271          444 :         }
    4272          444 :     }
    4273              : 
    4274              :     /// Locate and load config
    4275            0 :     pub(super) fn load_tenant_config(
    4276            0 :         conf: &'static PageServerConf,
    4277            0 :         tenant_shard_id: &TenantShardId,
    4278            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4279            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4280            0 : 
    4281            0 :         info!("loading tenant configuration from {config_path}");
    4282              : 
    4283              :         // load and parse file
    4284            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4285            0 :             match e.kind() {
    4286              :                 std::io::ErrorKind::NotFound => {
    4287              :                     // The config should almost always exist for a tenant directory:
    4288              :                     //  - When attaching a tenant, the config is the first thing we write
    4289              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4290              :                     //    before deleting contents.
    4291              :                     //
    4292              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4293              :                     // between creating directory and writing config.  Callers should handle that as if the
    4294              :                     // directory didn't exist.
    4295              : 
    4296            0 :                     LoadConfigError::NotFound(config_path)
    4297              :                 }
    4298              :                 _ => {
    4299              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4300              :                     // that we cannot cleanly recover
    4301            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4302              :                 }
    4303              :             }
    4304            0 :         })?;
    4305              : 
    4306            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4307            0 :     }
    4308              : 
    4309              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4310              :     pub(super) async fn persist_tenant_config(
    4311              :         conf: &'static PageServerConf,
    4312              :         tenant_shard_id: &TenantShardId,
    4313              :         location_conf: &LocationConf,
    4314              :     ) -> std::io::Result<()> {
    4315              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4316              : 
    4317              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4318              :     }
    4319              : 
    4320              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4321              :     pub(super) async fn persist_tenant_config_at(
    4322              :         tenant_shard_id: &TenantShardId,
    4323              :         config_path: &Utf8Path,
    4324              :         location_conf: &LocationConf,
    4325              :     ) -> std::io::Result<()> {
    4326              :         debug!("persisting tenantconf to {config_path}");
    4327              : 
    4328              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4329              : #  It is read in case of pageserver restart.
    4330              : "#
    4331              :         .to_string();
    4332              : 
    4333            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4334            0 :             Err(std::io::Error::new(
    4335            0 :                 std::io::ErrorKind::Other,
    4336            0 :                 "tenant-config-before-write",
    4337            0 :             ))
    4338            0 :         });
    4339              : 
    4340              :         // Convert the config to a toml file.
    4341              :         conf_content +=
    4342              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4343              : 
    4344              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4345              : 
    4346              :         let conf_content = conf_content.into_bytes();
    4347              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4348              :     }
    4349              : 
    4350              :     //
    4351              :     // How garbage collection works:
    4352              :     //
    4353              :     //                    +--bar------------->
    4354              :     //                   /
    4355              :     //             +----+-----foo---------------->
    4356              :     //            /
    4357              :     // ----main--+-------------------------->
    4358              :     //                \
    4359              :     //                 +-----baz-------->
    4360              :     //
    4361              :     //
    4362              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4363              :     //    `gc_infos` are being refreshed
    4364              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4365              :     //    all the points where other timelines have been branched off.
    4366              :     //    We will refrain from removing page versions at those LSNs.
    4367              :     // 3. For each timeline, scan all layer files on the timeline.
    4368              :     //    Remove all files for which a newer file exists and which
    4369              :     //    don't cover any branch point LSNs.
    4370              :     //
    4371              :     // TODO:
    4372              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4373              :     //   don't need to keep that in the parent anymore. But currently
    4374              :     //   we do.
    4375            8 :     async fn gc_iteration_internal(
    4376            8 :         &self,
    4377            8 :         target_timeline_id: Option<TimelineId>,
    4378            8 :         horizon: u64,
    4379            8 :         pitr: Duration,
    4380            8 :         cancel: &CancellationToken,
    4381            8 :         ctx: &RequestContext,
    4382            8 :     ) -> Result<GcResult, GcError> {
    4383            8 :         let mut totals: GcResult = Default::default();
    4384            8 :         let now = Instant::now();
    4385              : 
    4386            8 :         let gc_timelines = self
    4387            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4388            8 :             .await?;
    4389              : 
    4390            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4391              : 
    4392              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4393            8 :         if !gc_timelines.is_empty() {
    4394            8 :             info!("{} timelines need GC", gc_timelines.len());
    4395              :         } else {
    4396            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4397              :         }
    4398              : 
    4399              :         // Perform GC for each timeline.
    4400              :         //
    4401              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4402              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4403              :         // with branch creation.
    4404              :         //
    4405              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4406              :         // creation task can run concurrently with timeline's GC iteration.
    4407           16 :         for timeline in gc_timelines {
    4408            8 :             if cancel.is_cancelled() {
    4409              :                 // We were requested to shut down. Stop and return with the progress we
    4410              :                 // made.
    4411            0 :                 break;
    4412            8 :             }
    4413            8 :             let result = match timeline.gc().await {
    4414              :                 Err(GcError::TimelineCancelled) => {
    4415            0 :                     if target_timeline_id.is_some() {
    4416              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4417            0 :                         return Err(GcError::TimelineCancelled);
    4418              :                     } else {
    4419              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4420              :                         // skip past this and proceed to try GC on other timelines.
    4421            0 :                         continue;
    4422              :                     }
    4423              :                 }
    4424            8 :                 r => r?,
    4425              :             };
    4426            8 :             totals += result;
    4427              :         }
    4428              : 
    4429            8 :         totals.elapsed = now.elapsed();
    4430            8 :         Ok(totals)
    4431            8 :     }
    4432              : 
    4433              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4434              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4435              :     /// [`Tenant::get_gc_horizon`].
    4436              :     ///
    4437              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4438            0 :     pub(crate) async fn refresh_gc_info(
    4439            0 :         &self,
    4440            0 :         cancel: &CancellationToken,
    4441            0 :         ctx: &RequestContext,
    4442            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4443            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4444            0 :         // might be that these configuration values get applied faster than what it was previously,
    4445            0 :         // since these were only read from the gc task.
    4446            0 :         let horizon = self.get_gc_horizon();
    4447            0 :         let pitr = self.get_pitr_interval();
    4448            0 : 
    4449            0 :         // refresh all timelines
    4450            0 :         let target_timeline_id = None;
    4451            0 : 
    4452            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4453            0 :             .await
    4454            0 :     }
    4455              : 
    4456              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4457              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4458              :     ///
    4459              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4460            0 :     fn initialize_gc_info(
    4461            0 :         &self,
    4462            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4463            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4464            0 :         restrict_to_timeline: Option<TimelineId>,
    4465            0 :     ) {
    4466            0 :         if restrict_to_timeline.is_none() {
    4467              :             // This function must be called before activation: after activation timeline create/delete operations
    4468              :             // might happen, and this function is not safe to run concurrently with those.
    4469            0 :             assert!(!self.is_active());
    4470            0 :         }
    4471              : 
    4472              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4473              :         // the branch point where it was created.
    4474            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4475            0 :             BTreeMap::new();
    4476            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4477            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4478            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4479            0 :                 ancestor_children.push((
    4480            0 :                     timeline_entry.get_ancestor_lsn(),
    4481            0 :                     *timeline_id,
    4482            0 :                     MaybeOffloaded::No,
    4483            0 :                 ));
    4484            0 :             }
    4485            0 :         });
    4486            0 :         timelines_offloaded
    4487            0 :             .iter()
    4488            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4489            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4490            0 :                     return;
    4491              :                 };
    4492            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4493            0 :                     return;
    4494              :                 };
    4495            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4496            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4497            0 :             });
    4498            0 : 
    4499            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4500            0 :         let horizon = self.get_gc_horizon();
    4501              : 
    4502              :         // Populate each timeline's GcInfo with information about its child branches
    4503            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4504            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4505              :         } else {
    4506            0 :             itertools::Either::Right(timelines.values())
    4507              :         };
    4508            0 :         for timeline in timelines_to_write {
    4509            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4510            0 :                 .remove(&timeline.timeline_id)
    4511            0 :                 .unwrap_or_default();
    4512            0 : 
    4513            0 :             branchpoints.sort_by_key(|b| b.0);
    4514            0 : 
    4515            0 :             let mut target = timeline.gc_info.write().unwrap();
    4516            0 : 
    4517            0 :             target.retain_lsns = branchpoints;
    4518            0 : 
    4519            0 :             let space_cutoff = timeline
    4520            0 :                 .get_last_record_lsn()
    4521            0 :                 .checked_sub(horizon)
    4522            0 :                 .unwrap_or(Lsn(0));
    4523            0 : 
    4524            0 :             target.cutoffs = GcCutoffs {
    4525            0 :                 space: space_cutoff,
    4526            0 :                 time: Lsn::INVALID,
    4527            0 :             };
    4528            0 :         }
    4529            0 :     }
    4530              : 
    4531            8 :     async fn refresh_gc_info_internal(
    4532            8 :         &self,
    4533            8 :         target_timeline_id: Option<TimelineId>,
    4534            8 :         horizon: u64,
    4535            8 :         pitr: Duration,
    4536            8 :         cancel: &CancellationToken,
    4537            8 :         ctx: &RequestContext,
    4538            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4539            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4540            8 :         // currently visible timelines.
    4541            8 :         let timelines = self
    4542            8 :             .timelines
    4543            8 :             .lock()
    4544            8 :             .unwrap()
    4545            8 :             .values()
    4546            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4547            8 :                 Some(target) => &tl.timeline_id == target,
    4548            0 :                 None => true,
    4549            8 :             })
    4550            8 :             .cloned()
    4551            8 :             .collect::<Vec<_>>();
    4552            8 : 
    4553            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4554              :             // We were to act on a particular timeline and it wasn't found
    4555            0 :             return Err(GcError::TimelineNotFound);
    4556            8 :         }
    4557            8 : 
    4558            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4559            8 :             HashMap::with_capacity(timelines.len());
    4560            8 : 
    4561            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4562            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4563            8 :         for timeline in timelines.iter() {
    4564            8 :             let cutoff = timeline
    4565            8 :                 .get_last_record_lsn()
    4566            8 :                 .checked_sub(horizon)
    4567            8 :                 .unwrap_or(Lsn(0));
    4568              : 
    4569            8 :             let cutoffs = timeline
    4570            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4571            8 :                 .await?;
    4572            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4573            8 :             assert!(old.is_none());
    4574              :         }
    4575              : 
    4576            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4577            0 :             return Err(GcError::TenantCancelled);
    4578            8 :         }
    4579              : 
    4580              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4581              :         // because that will stall branch creation.
    4582            8 :         let gc_cs = self.gc_cs.lock().await;
    4583              : 
    4584              :         // Ok, we now know all the branch points.
    4585              :         // Update the GC information for each timeline.
    4586            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4587           16 :         for timeline in timelines {
    4588              :             // We filtered the timeline list above
    4589            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4590            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4591            0 :             }
    4592              : 
    4593              :             {
    4594            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4595            8 : 
    4596            8 :                 // Cull any expired leases
    4597            8 :                 let now = SystemTime::now();
    4598           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4599            8 : 
    4600            8 :                 timeline
    4601            8 :                     .metrics
    4602            8 :                     .valid_lsn_lease_count_gauge
    4603            8 :                     .set(target.leases.len() as u64);
    4604              : 
    4605              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4606            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4607            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4608            0 :                         target.within_ancestor_pitr =
    4609            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4610            0 :                     }
    4611            8 :                 }
    4612              : 
    4613              :                 // Update metrics that depend on GC state
    4614            8 :                 timeline
    4615            8 :                     .metrics
    4616            8 :                     .archival_size
    4617            8 :                     .set(if target.within_ancestor_pitr {
    4618            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4619              :                     } else {
    4620            8 :                         0
    4621              :                     });
    4622            8 :                 timeline.metrics.pitr_history_size.set(
    4623            8 :                     timeline
    4624            8 :                         .get_last_record_lsn()
    4625            8 :                         .checked_sub(target.cutoffs.time)
    4626            8 :                         .unwrap_or(Lsn(0))
    4627            8 :                         .0,
    4628            8 :                 );
    4629              : 
    4630              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4631              :                 // - this timeline was created while we were finding cutoffs
    4632              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4633            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4634            8 :                     let original_cutoffs = target.cutoffs.clone();
    4635            8 :                     // GC cutoffs should never go back
    4636            8 :                     target.cutoffs = GcCutoffs {
    4637            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4638            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4639            8 :                     }
    4640            0 :                 }
    4641              :             }
    4642              : 
    4643            8 :             gc_timelines.push(timeline);
    4644              :         }
    4645            8 :         drop(gc_cs);
    4646            8 :         Ok(gc_timelines)
    4647            8 :     }
    4648              : 
    4649              :     /// A substitute for `branch_timeline` for use in unit tests.
    4650              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4651              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4652              :     /// timeline background tasks are launched, except the flush loop.
    4653              :     #[cfg(test)]
    4654          464 :     async fn branch_timeline_test(
    4655          464 :         self: &Arc<Self>,
    4656          464 :         src_timeline: &Arc<Timeline>,
    4657          464 :         dst_id: TimelineId,
    4658          464 :         ancestor_lsn: Option<Lsn>,
    4659          464 :         ctx: &RequestContext,
    4660          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4661          464 :         let tl = self
    4662          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4663          464 :             .await?
    4664          456 :             .into_timeline_for_test();
    4665          456 :         tl.set_state(TimelineState::Active);
    4666          456 :         Ok(tl)
    4667          464 :     }
    4668              : 
    4669              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4670              :     #[cfg(test)]
    4671              :     #[allow(clippy::too_many_arguments)]
    4672           12 :     pub async fn branch_timeline_test_with_layers(
    4673           12 :         self: &Arc<Self>,
    4674           12 :         src_timeline: &Arc<Timeline>,
    4675           12 :         dst_id: TimelineId,
    4676           12 :         ancestor_lsn: Option<Lsn>,
    4677           12 :         ctx: &RequestContext,
    4678           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4679           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4680           12 :         end_lsn: Lsn,
    4681           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4682              :         use checks::check_valid_layermap;
    4683              :         use itertools::Itertools;
    4684              : 
    4685           12 :         let tline = self
    4686           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4687           12 :             .await?;
    4688           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4689           12 :             ancestor_lsn
    4690              :         } else {
    4691            0 :             tline.get_last_record_lsn()
    4692              :         };
    4693           12 :         assert!(end_lsn >= ancestor_lsn);
    4694           12 :         tline.force_advance_lsn(end_lsn);
    4695           24 :         for deltas in delta_layer_desc {
    4696           12 :             tline
    4697           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4698           12 :                 .await?;
    4699              :         }
    4700           20 :         for (lsn, images) in image_layer_desc {
    4701            8 :             tline
    4702            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4703            8 :                 .await?;
    4704              :         }
    4705           12 :         let layer_names = tline
    4706           12 :             .layers
    4707           12 :             .read()
    4708           12 :             .await
    4709           12 :             .layer_map()
    4710           12 :             .unwrap()
    4711           12 :             .iter_historic_layers()
    4712           20 :             .map(|layer| layer.layer_name())
    4713           12 :             .collect_vec();
    4714           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4715            0 :             bail!("invalid layermap: {err}");
    4716           12 :         }
    4717           12 :         Ok(tline)
    4718           12 :     }
    4719              : 
    4720              :     /// Branch an existing timeline.
    4721            0 :     async fn branch_timeline(
    4722            0 :         self: &Arc<Self>,
    4723            0 :         src_timeline: &Arc<Timeline>,
    4724            0 :         dst_id: TimelineId,
    4725            0 :         start_lsn: Option<Lsn>,
    4726            0 :         ctx: &RequestContext,
    4727            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4728            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4729            0 :             .await
    4730            0 :     }
    4731              : 
    4732          464 :     async fn branch_timeline_impl(
    4733          464 :         self: &Arc<Self>,
    4734          464 :         src_timeline: &Arc<Timeline>,
    4735          464 :         dst_id: TimelineId,
    4736          464 :         start_lsn: Option<Lsn>,
    4737          464 :         _ctx: &RequestContext,
    4738          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4739          464 :         let src_id = src_timeline.timeline_id;
    4740              : 
    4741              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4742              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4743              :         // valid while we are creating the branch.
    4744          464 :         let _gc_cs = self.gc_cs.lock().await;
    4745              : 
    4746              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4747          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4748            4 :             let lsn = src_timeline.get_last_record_lsn();
    4749            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4750            4 :             lsn
    4751          464 :         });
    4752              : 
    4753              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4754          464 :         let timeline_create_guard = match self
    4755          464 :             .start_creating_timeline(
    4756          464 :                 dst_id,
    4757          464 :                 CreateTimelineIdempotency::Branch {
    4758          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4759          464 :                     ancestor_start_lsn: start_lsn,
    4760          464 :                 },
    4761          464 :             )
    4762          464 :             .await?
    4763              :         {
    4764          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4765            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4766            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4767              :             }
    4768              :         };
    4769              : 
    4770              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4771              :         // horizon on the source timeline
    4772              :         //
    4773              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4774              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4775              :         // planned GC cutoff in 'gc_info' is normally larger than
    4776              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4777              :         // changed the GC settings for the tenant to make the PITR window
    4778              :         // larger, but some of the data was already removed by an earlier GC
    4779              :         // iteration.
    4780              : 
    4781              :         // check against last actual 'latest_gc_cutoff' first
    4782          464 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4783          464 :         {
    4784          464 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4785          464 :             let planned_cutoff = gc_info.min_cutoff();
    4786          464 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4787            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);
    4788              :             } else {
    4789          464 :                 src_timeline
    4790          464 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4791          464 :                     .context(format!(
    4792          464 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4793          464 :                         *applied_gc_cutoff_lsn,
    4794          464 :                     ))
    4795          464 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4796              : 
    4797              :                 // and then the planned GC cutoff
    4798          456 :                 if start_lsn < planned_cutoff {
    4799            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4800            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4801            0 :                     )));
    4802          456 :                 }
    4803              :             }
    4804              :         }
    4805              : 
    4806              :         //
    4807              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4808              :         // so that GC cannot advance the GC cutoff until we are finished.
    4809              :         // Proceed with the branch creation.
    4810              :         //
    4811              : 
    4812              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4813              :         // the timeline was branched at the current end of the source timeline.
    4814              :         let RecordLsn {
    4815          456 :             last: src_last,
    4816          456 :             prev: src_prev,
    4817          456 :         } = src_timeline.get_last_record_rlsn();
    4818          456 :         let dst_prev = if src_last == start_lsn {
    4819          432 :             Some(src_prev)
    4820              :         } else {
    4821           24 :             None
    4822              :         };
    4823              : 
    4824              :         // Create the metadata file, noting the ancestor of the new timeline.
    4825              :         // There is initially no data in it, but all the read-calls know to look
    4826              :         // into the ancestor.
    4827          456 :         let metadata = TimelineMetadata::new(
    4828          456 :             start_lsn,
    4829          456 :             dst_prev,
    4830          456 :             Some(src_id),
    4831          456 :             start_lsn,
    4832          456 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4833          456 :             src_timeline.initdb_lsn,
    4834          456 :             src_timeline.pg_version,
    4835          456 :         );
    4836              : 
    4837          456 :         let uninitialized_timeline = self
    4838          456 :             .prepare_new_timeline(
    4839          456 :                 dst_id,
    4840          456 :                 &metadata,
    4841          456 :                 timeline_create_guard,
    4842          456 :                 start_lsn + 1,
    4843          456 :                 Some(Arc::clone(src_timeline)),
    4844          456 :             )
    4845          456 :             .await?;
    4846              : 
    4847          456 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4848              : 
    4849              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4850              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4851              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4852              :         // could get incorrect information and remove more layers, than needed.
    4853              :         // See also https://github.com/neondatabase/neon/issues/3865
    4854          456 :         new_timeline
    4855          456 :             .remote_client
    4856          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4857          456 :             .context("branch initial metadata upload")?;
    4858              : 
    4859              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4860              : 
    4861          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4862          464 :     }
    4863              : 
    4864              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4865              :     #[cfg(test)]
    4866              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4867              :     pub(crate) async fn bootstrap_timeline_test(
    4868              :         self: &Arc<Self>,
    4869              :         timeline_id: TimelineId,
    4870              :         pg_version: u32,
    4871              :         load_existing_initdb: Option<TimelineId>,
    4872              :         ctx: &RequestContext,
    4873              :     ) -> anyhow::Result<Arc<Timeline>> {
    4874              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4875              :             .await
    4876              :             .map_err(anyhow::Error::new)
    4877            4 :             .map(|r| r.into_timeline_for_test())
    4878              :     }
    4879              : 
    4880              :     /// Get exclusive access to the timeline ID for creation.
    4881              :     ///
    4882              :     /// Timeline-creating code paths must use this function before making changes
    4883              :     /// to in-memory or persistent state.
    4884              :     ///
    4885              :     /// The `state` parameter is a description of the timeline creation operation
    4886              :     /// we intend to perform.
    4887              :     /// If the timeline was already created in the meantime, we check whether this
    4888              :     /// request conflicts or is idempotent , based on `state`.
    4889          896 :     async fn start_creating_timeline(
    4890          896 :         self: &Arc<Self>,
    4891          896 :         new_timeline_id: TimelineId,
    4892          896 :         idempotency: CreateTimelineIdempotency,
    4893          896 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4894          896 :         let allow_offloaded = false;
    4895          896 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4896          892 :             Ok(create_guard) => {
    4897          892 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4898          892 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4899              :             }
    4900            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4901              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4902              :                 // Creation is in progress, we cannot create it again, and we cannot
    4903              :                 // check if this request matches the existing one, so caller must try
    4904              :                 // again later.
    4905            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4906              :             }
    4907            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4908              :             Err(TimelineExclusionError::AlreadyExists {
    4909            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4910            0 :                 ..
    4911            0 :             }) => {
    4912            0 :                 info!("timeline already exists but is offloaded");
    4913            0 :                 Err(CreateTimelineError::Conflict)
    4914              :             }
    4915              :             Err(TimelineExclusionError::AlreadyExists {
    4916            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4917            4 :                 arg,
    4918            4 :             }) => {
    4919            4 :                 {
    4920            4 :                     let existing = &existing.create_idempotency;
    4921            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4922            4 :                     debug!("timeline already exists");
    4923              : 
    4924            4 :                     match (existing, &arg) {
    4925              :                         // FailWithConflict => no idempotency check
    4926              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4927              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4928            4 :                             warn!("timeline already exists, failing request");
    4929            4 :                             return Err(CreateTimelineError::Conflict);
    4930              :                         }
    4931              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4932            0 :                         (x, y) if x == y => {
    4933            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4934              :                             // fallthrough
    4935              :                         }
    4936              :                         (_, _) => {
    4937            0 :                             warn!("idempotency conflict, failing request");
    4938            0 :                             return Err(CreateTimelineError::Conflict);
    4939              :                         }
    4940              :                     }
    4941              :                 }
    4942              : 
    4943            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4944              :             }
    4945              :         }
    4946          896 :     }
    4947              : 
    4948            0 :     async fn upload_initdb(
    4949            0 :         &self,
    4950            0 :         timelines_path: &Utf8PathBuf,
    4951            0 :         pgdata_path: &Utf8PathBuf,
    4952            0 :         timeline_id: &TimelineId,
    4953            0 :     ) -> anyhow::Result<()> {
    4954            0 :         let temp_path = timelines_path.join(format!(
    4955            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4956            0 :         ));
    4957            0 : 
    4958            0 :         scopeguard::defer! {
    4959            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4960            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4961            0 :             }
    4962            0 :         }
    4963              : 
    4964            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4965              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4966            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4967            0 :             warn!(
    4968            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4969              :             );
    4970            0 :         }
    4971              : 
    4972            0 :         pausable_failpoint!("before-initdb-upload");
    4973              : 
    4974            0 :         backoff::retry(
    4975            0 :             || async {
    4976            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4977            0 :                     &self.remote_storage,
    4978            0 :                     &self.tenant_shard_id.tenant_id,
    4979            0 :                     timeline_id,
    4980            0 :                     pgdata_zstd.try_clone().await?,
    4981            0 :                     tar_zst_size,
    4982            0 :                     &self.cancel,
    4983            0 :                 )
    4984            0 :                 .await
    4985            0 :             },
    4986            0 :             |_| false,
    4987            0 :             3,
    4988            0 :             u32::MAX,
    4989            0 :             "persist_initdb_tar_zst",
    4990            0 :             &self.cancel,
    4991            0 :         )
    4992            0 :         .await
    4993            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4994            0 :         .and_then(|x| x)
    4995            0 :     }
    4996              : 
    4997              :     /// - run initdb to init temporary instance and get bootstrap data
    4998              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4999            4 :     async fn bootstrap_timeline(
    5000            4 :         self: &Arc<Self>,
    5001            4 :         timeline_id: TimelineId,
    5002            4 :         pg_version: u32,
    5003            4 :         load_existing_initdb: Option<TimelineId>,
    5004            4 :         ctx: &RequestContext,
    5005            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5006            4 :         let timeline_create_guard = match self
    5007            4 :             .start_creating_timeline(
    5008            4 :                 timeline_id,
    5009            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5010            4 :             )
    5011            4 :             .await?
    5012              :         {
    5013            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5014            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5015            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    5016              :             }
    5017              :         };
    5018              : 
    5019              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5020              :         // temporary directory for basebackup files for the given timeline.
    5021              : 
    5022            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5023            4 :         let pgdata_path = path_with_suffix_extension(
    5024            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5025            4 :             TEMP_FILE_SUFFIX,
    5026            4 :         );
    5027            4 : 
    5028            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5029            4 :         // we won't race with other creations or existent timelines with the same path.
    5030            4 :         if pgdata_path.exists() {
    5031            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5032            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5033            0 :             })?;
    5034            4 :         }
    5035              : 
    5036              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5037            4 :         let pgdata_path_deferred = pgdata_path.clone();
    5038            4 :         scopeguard::defer! {
    5039            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
    5040            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5041            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5042            4 :             }
    5043            4 :         }
    5044            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5045            4 :             if existing_initdb_timeline_id != timeline_id {
    5046            0 :                 let source_path = &remote_initdb_archive_path(
    5047            0 :                     &self.tenant_shard_id.tenant_id,
    5048            0 :                     &existing_initdb_timeline_id,
    5049            0 :                 );
    5050            0 :                 let dest_path =
    5051            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5052            0 : 
    5053            0 :                 // if this fails, it will get retried by retried control plane requests
    5054            0 :                 self.remote_storage
    5055            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5056            0 :                     .await
    5057            0 :                     .context("copy initdb tar")?;
    5058            4 :             }
    5059            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5060            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5061            4 :                     self.conf,
    5062            4 :                     &self.remote_storage,
    5063            4 :                     &self.tenant_shard_id,
    5064            4 :                     &existing_initdb_timeline_id,
    5065            4 :                     &self.cancel,
    5066            4 :                 )
    5067            4 :                 .await
    5068            4 :                 .context("download initdb tar")?;
    5069              : 
    5070            4 :             scopeguard::defer! {
    5071            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5072            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5073            4 :                 }
    5074            4 :             }
    5075            4 : 
    5076            4 :             let buf_read =
    5077            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5078            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    5079            4 :                 .await
    5080            4 :                 .context("extract initdb tar")?;
    5081              :         } else {
    5082              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5083            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5084            0 :                 .await
    5085            0 :                 .context("run initdb")?;
    5086              : 
    5087              :             // Upload the created data dir to S3
    5088            0 :             if self.tenant_shard_id().is_shard_zero() {
    5089            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5090            0 :                     .await?;
    5091            0 :             }
    5092              :         }
    5093            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5094            4 : 
    5095            4 :         // Import the contents of the data directory at the initial checkpoint
    5096            4 :         // LSN, and any WAL after that.
    5097            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5098            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5099            4 :         let new_metadata = TimelineMetadata::new(
    5100            4 :             Lsn(0),
    5101            4 :             None,
    5102            4 :             None,
    5103            4 :             Lsn(0),
    5104            4 :             pgdata_lsn,
    5105            4 :             pgdata_lsn,
    5106            4 :             pg_version,
    5107            4 :         );
    5108            4 :         let mut raw_timeline = self
    5109            4 :             .prepare_new_timeline(
    5110            4 :                 timeline_id,
    5111            4 :                 &new_metadata,
    5112            4 :                 timeline_create_guard,
    5113            4 :                 pgdata_lsn,
    5114            4 :                 None,
    5115            4 :             )
    5116            4 :             .await?;
    5117              : 
    5118            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5119            4 :         raw_timeline
    5120            4 :             .write(|unfinished_timeline| async move {
    5121            4 :                 import_datadir::import_timeline_from_postgres_datadir(
    5122            4 :                     &unfinished_timeline,
    5123            4 :                     &pgdata_path,
    5124            4 :                     pgdata_lsn,
    5125            4 :                     ctx,
    5126            4 :                 )
    5127            4 :                 .await
    5128            4 :                 .with_context(|| {
    5129            0 :                     format!(
    5130            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5131            0 :                     )
    5132            4 :                 })?;
    5133              : 
    5134            4 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5135            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5136            0 :                         "failpoint before-checkpoint-new-timeline"
    5137            0 :                     )))
    5138            4 :                 });
    5139              : 
    5140            4 :                 Ok(())
    5141            8 :             })
    5142            4 :             .await?;
    5143              : 
    5144              :         // All done!
    5145            4 :         let timeline = raw_timeline.finish_creation().await?;
    5146              : 
    5147              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5148              : 
    5149            4 :         Ok(CreateTimelineResult::Created(timeline))
    5150            4 :     }
    5151              : 
    5152          884 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5153          884 :         RemoteTimelineClient::new(
    5154          884 :             self.remote_storage.clone(),
    5155          884 :             self.deletion_queue_client.clone(),
    5156          884 :             self.conf,
    5157          884 :             self.tenant_shard_id,
    5158          884 :             timeline_id,
    5159          884 :             self.generation,
    5160          884 :             &self.tenant_conf.load().location,
    5161          884 :         )
    5162          884 :     }
    5163              : 
    5164              :     /// Builds required resources for a new timeline.
    5165          884 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5166          884 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5167          884 :         self.get_timeline_resources_for(remote_client)
    5168          884 :     }
    5169              : 
    5170              :     /// Builds timeline resources for the given remote client.
    5171          896 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5172          896 :         TimelineResources {
    5173          896 :             remote_client,
    5174          896 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5175          896 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5176          896 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5177          896 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5178          896 :         }
    5179          896 :     }
    5180              : 
    5181              :     /// Creates intermediate timeline structure and its files.
    5182              :     ///
    5183              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5184              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5185              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5186          884 :     async fn prepare_new_timeline<'a>(
    5187          884 :         &'a self,
    5188          884 :         new_timeline_id: TimelineId,
    5189          884 :         new_metadata: &TimelineMetadata,
    5190          884 :         create_guard: TimelineCreateGuard,
    5191          884 :         start_lsn: Lsn,
    5192          884 :         ancestor: Option<Arc<Timeline>>,
    5193          884 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5194          884 :         let tenant_shard_id = self.tenant_shard_id;
    5195          884 : 
    5196          884 :         let resources = self.build_timeline_resources(new_timeline_id);
    5197          884 :         resources
    5198          884 :             .remote_client
    5199          884 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5200              : 
    5201          884 :         let timeline_struct = self
    5202          884 :             .create_timeline_struct(
    5203          884 :                 new_timeline_id,
    5204          884 :                 new_metadata,
    5205          884 :                 None,
    5206          884 :                 ancestor,
    5207          884 :                 resources,
    5208          884 :                 CreateTimelineCause::Load,
    5209          884 :                 create_guard.idempotency.clone(),
    5210          884 :             )
    5211          884 :             .context("Failed to create timeline data structure")?;
    5212              : 
    5213          884 :         timeline_struct.init_empty_layer_map(start_lsn);
    5214              : 
    5215          884 :         if let Err(e) = self
    5216          884 :             .create_timeline_files(&create_guard.timeline_path)
    5217          884 :             .await
    5218              :         {
    5219            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5220            0 :             cleanup_timeline_directory(create_guard);
    5221            0 :             return Err(e);
    5222          884 :         }
    5223          884 : 
    5224          884 :         debug!(
    5225            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5226              :         );
    5227              : 
    5228          884 :         Ok(UninitializedTimeline::new(
    5229          884 :             self,
    5230          884 :             new_timeline_id,
    5231          884 :             Some((timeline_struct, create_guard)),
    5232          884 :         ))
    5233          884 :     }
    5234              : 
    5235          884 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5236          884 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5237              : 
    5238          884 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5239            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5240          884 :         });
    5241              : 
    5242          884 :         Ok(())
    5243          884 :     }
    5244              : 
    5245              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5246              :     /// concurrent attempts to create the same timeline.
    5247              :     ///
    5248              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5249              :     /// offloaded timelines or not.
    5250          896 :     fn create_timeline_create_guard(
    5251          896 :         self: &Arc<Self>,
    5252          896 :         timeline_id: TimelineId,
    5253          896 :         idempotency: CreateTimelineIdempotency,
    5254          896 :         allow_offloaded: bool,
    5255          896 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5256          896 :         let tenant_shard_id = self.tenant_shard_id;
    5257          896 : 
    5258          896 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5259              : 
    5260          896 :         let create_guard = TimelineCreateGuard::new(
    5261          896 :             self,
    5262          896 :             timeline_id,
    5263          896 :             timeline_path.clone(),
    5264          896 :             idempotency,
    5265          896 :             allow_offloaded,
    5266          896 :         )?;
    5267              : 
    5268              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5269              :         // for creation.
    5270              :         // A timeline directory should never exist on disk already:
    5271              :         // - a previous failed creation would have cleaned up after itself
    5272              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5273              :         //
    5274              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5275              :         // this error may indicate a bug in cleanup on failed creations.
    5276          892 :         if timeline_path.exists() {
    5277            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5278            0 :                 "Timeline directory already exists! This is a bug."
    5279            0 :             )));
    5280          892 :         }
    5281          892 : 
    5282          892 :         Ok(create_guard)
    5283          896 :     }
    5284              : 
    5285              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5286              :     ///
    5287              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5288              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5289              :     pub async fn gather_size_inputs(
    5290              :         &self,
    5291              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5292              :         // (only if it is shorter than the real cutoff).
    5293              :         max_retention_period: Option<u64>,
    5294              :         cause: LogicalSizeCalculationCause,
    5295              :         cancel: &CancellationToken,
    5296              :         ctx: &RequestContext,
    5297              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5298              :         let logical_sizes_at_once = self
    5299              :             .conf
    5300              :             .concurrent_tenant_size_logical_size_queries
    5301              :             .inner();
    5302              : 
    5303              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5304              :         //
    5305              :         // But the only case where we need to run multiple of these at once is when we
    5306              :         // request a size for a tenant manually via API, while another background calculation
    5307              :         // is in progress (which is not a common case).
    5308              :         //
    5309              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5310              :         let mut shared_cache = tokio::select! {
    5311              :             locked = self.cached_logical_sizes.lock() => locked,
    5312              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5313              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5314              :         };
    5315              : 
    5316              :         size::gather_inputs(
    5317              :             self,
    5318              :             logical_sizes_at_once,
    5319              :             max_retention_period,
    5320              :             &mut shared_cache,
    5321              :             cause,
    5322              :             cancel,
    5323              :             ctx,
    5324              :         )
    5325              :         .await
    5326              :     }
    5327              : 
    5328              :     /// Calculate synthetic tenant size and cache the result.
    5329              :     /// This is periodically called by background worker.
    5330              :     /// result is cached in tenant struct
    5331              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5332              :     pub async fn calculate_synthetic_size(
    5333              :         &self,
    5334              :         cause: LogicalSizeCalculationCause,
    5335              :         cancel: &CancellationToken,
    5336              :         ctx: &RequestContext,
    5337              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5338              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5339              : 
    5340              :         let size = inputs.calculate();
    5341              : 
    5342              :         self.set_cached_synthetic_size(size);
    5343              : 
    5344              :         Ok(size)
    5345              :     }
    5346              : 
    5347              :     /// Cache given synthetic size and update the metric value
    5348            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5349            0 :         self.cached_synthetic_tenant_size
    5350            0 :             .store(size, Ordering::Relaxed);
    5351            0 : 
    5352            0 :         // Only shard zero should be calculating synthetic sizes
    5353            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5354              : 
    5355            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5356            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5357            0 :             .unwrap()
    5358            0 :             .set(size);
    5359            0 :     }
    5360              : 
    5361            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5362            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5363            0 :     }
    5364              : 
    5365              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5366              :     ///
    5367              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5368              :     /// from an external API handler.
    5369              :     ///
    5370              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5371              :     /// still bounded by tenant/timeline shutdown.
    5372              :     #[tracing::instrument(skip_all)]
    5373              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5374              :         let timelines = self.timelines.lock().unwrap().clone();
    5375              : 
    5376            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5377            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5378            0 :             timeline.freeze_and_flush().await?;
    5379            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5380            0 :             timeline.remote_client.wait_completion().await?;
    5381              : 
    5382            0 :             Ok(())
    5383            0 :         }
    5384              : 
    5385              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5386              :         // aborted when this function's future is cancelled: they should stay alive
    5387              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5388              :         // before Timeline shutdown completes.
    5389              :         let mut results = FuturesUnordered::new();
    5390              : 
    5391              :         for (_timeline_id, timeline) in timelines {
    5392              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5393              :             // means that if this function's future is cancelled, the Timeline shutdown
    5394              :             // will still wait for any I/O in here to complete.
    5395              :             let Ok(gate) = timeline.gate.enter() else {
    5396              :                 continue;
    5397              :             };
    5398            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5399              :             results.push(jh);
    5400              :         }
    5401              : 
    5402              :         while let Some(r) = results.next().await {
    5403              :             if let Err(e) = r {
    5404              :                 if !e.is_cancelled() && !e.is_panic() {
    5405              :                     tracing::error!("unexpected join error: {e:?}");
    5406              :                 }
    5407              :             }
    5408              :         }
    5409              : 
    5410              :         // The flushes we did above were just writes, but the Tenant might have had
    5411              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5412              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5413              :         // because it's typically a no-op.
    5414              :         match self.deletion_queue_client.flush_execute().await {
    5415              :             Ok(_) => {}
    5416              :             Err(DeletionQueueError::ShuttingDown) => {}
    5417              :         }
    5418              : 
    5419              :         Ok(())
    5420              :     }
    5421              : 
    5422            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5423            0 :         self.tenant_conf.load().tenant_conf.clone()
    5424            0 :     }
    5425              : 
    5426              :     /// How much local storage would this tenant like to have?  It can cope with
    5427              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5428              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5429              :     /// by keeping important things on local disk.
    5430              :     ///
    5431              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5432              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5433              :     /// actually use more than they report here.
    5434            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5435            0 :         let timelines = self.timelines.lock().unwrap();
    5436            0 : 
    5437            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5438            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5439            0 :         // of them is used actively enough to occupy space on disk.
    5440            0 :         timelines
    5441            0 :             .values()
    5442            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5443            0 :             .max()
    5444            0 :             .unwrap_or(0)
    5445            0 :     }
    5446              : 
    5447              :     /// Serialize and write the latest TenantManifest to remote storage.
    5448            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5449              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5450              :         // must be loaded while holding this lock. This makes it safe to call this function
    5451              :         // from anywhere without worrying about colliding updates.
    5452            4 :         let mut guard = tokio::select! {
    5453            4 :             g = self.tenant_manifest_upload.lock() => {
    5454            4 :                 g
    5455              :             },
    5456            4 :             _ = self.cancel.cancelled() => {
    5457            0 :                 return Err(TenantManifestError::Cancelled);
    5458              :             }
    5459              :         };
    5460              : 
    5461            4 :         let manifest = self.build_tenant_manifest();
    5462            4 :         if Some(&manifest) == (*guard).as_ref() {
    5463              :             // Optimisation: skip uploads that don't change anything.
    5464            0 :             return Ok(());
    5465            4 :         }
    5466            4 : 
    5467            4 :         // Remote storage does no retries internally, so wrap it
    5468            4 :         match backoff::retry(
    5469            4 :             || async {
    5470            4 :                 upload_tenant_manifest(
    5471            4 :                     &self.remote_storage,
    5472            4 :                     &self.tenant_shard_id,
    5473            4 :                     self.generation,
    5474            4 :                     &manifest,
    5475            4 :                     &self.cancel,
    5476            4 :                 )
    5477            4 :                 .await
    5478            8 :             },
    5479            4 :             |_e| self.cancel.is_cancelled(),
    5480            4 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5481            4 :             FAILED_REMOTE_OP_RETRIES,
    5482            4 :             "uploading tenant manifest",
    5483            4 :             &self.cancel,
    5484            4 :         )
    5485            4 :         .await
    5486              :         {
    5487            0 :             None => Err(TenantManifestError::Cancelled),
    5488            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5489            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5490              :             Some(Ok(_)) => {
    5491              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5492              :                 // re-uploading the same thing.
    5493            4 :                 *guard = Some(manifest);
    5494            4 : 
    5495            4 :                 Ok(())
    5496              :             }
    5497              :         }
    5498            4 :     }
    5499              : }
    5500              : 
    5501              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5502              : /// to get bootstrap data for timeline initialization.
    5503            0 : async fn run_initdb(
    5504            0 :     conf: &'static PageServerConf,
    5505            0 :     initdb_target_dir: &Utf8Path,
    5506            0 :     pg_version: u32,
    5507            0 :     cancel: &CancellationToken,
    5508            0 : ) -> Result<(), InitdbError> {
    5509            0 :     let initdb_bin_path = conf
    5510            0 :         .pg_bin_dir(pg_version)
    5511            0 :         .map_err(InitdbError::Other)?
    5512            0 :         .join("initdb");
    5513            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5514            0 :     info!(
    5515            0 :         "running {} in {}, libdir: {}",
    5516              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5517              :     );
    5518              : 
    5519            0 :     let _permit = {
    5520            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5521            0 :         INIT_DB_SEMAPHORE.acquire().await
    5522              :     };
    5523              : 
    5524            0 :     CONCURRENT_INITDBS.inc();
    5525            0 :     scopeguard::defer! {
    5526            0 :         CONCURRENT_INITDBS.dec();
    5527            0 :     }
    5528            0 : 
    5529            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5530            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5531            0 :         superuser: &conf.superuser,
    5532            0 :         locale: &conf.locale,
    5533            0 :         initdb_bin: &initdb_bin_path,
    5534            0 :         pg_version,
    5535            0 :         library_search_path: &initdb_lib_dir,
    5536            0 :         pgdata: initdb_target_dir,
    5537            0 :     })
    5538            0 :     .await
    5539            0 :     .map_err(InitdbError::Inner);
    5540            0 : 
    5541            0 :     // This isn't true cancellation support, see above. Still return an error to
    5542            0 :     // excercise the cancellation code path.
    5543            0 :     if cancel.is_cancelled() {
    5544            0 :         return Err(InitdbError::Cancelled);
    5545            0 :     }
    5546            0 : 
    5547            0 :     res
    5548            0 : }
    5549              : 
    5550              : /// Dump contents of a layer file to stdout.
    5551            0 : pub async fn dump_layerfile_from_path(
    5552            0 :     path: &Utf8Path,
    5553            0 :     verbose: bool,
    5554            0 :     ctx: &RequestContext,
    5555            0 : ) -> anyhow::Result<()> {
    5556              :     use std::os::unix::fs::FileExt;
    5557              : 
    5558              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5559              :     // file.
    5560            0 :     let file = File::open(path)?;
    5561            0 :     let mut header_buf = [0u8; 2];
    5562            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5563              : 
    5564            0 :     match u16::from_be_bytes(header_buf) {
    5565              :         crate::IMAGE_FILE_MAGIC => {
    5566            0 :             ImageLayer::new_for_path(path, file)?
    5567            0 :                 .dump(verbose, ctx)
    5568            0 :                 .await?
    5569              :         }
    5570              :         crate::DELTA_FILE_MAGIC => {
    5571            0 :             DeltaLayer::new_for_path(path, file)?
    5572            0 :                 .dump(verbose, ctx)
    5573            0 :                 .await?
    5574              :         }
    5575            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5576              :     }
    5577              : 
    5578            0 :     Ok(())
    5579            0 : }
    5580              : 
    5581              : #[cfg(test)]
    5582              : pub(crate) mod harness {
    5583              :     use bytes::{Bytes, BytesMut};
    5584              :     use once_cell::sync::OnceCell;
    5585              :     use pageserver_api::models::ShardParameters;
    5586              :     use pageserver_api::shard::ShardIndex;
    5587              :     use utils::logging;
    5588              : 
    5589              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5590              :     use crate::l0_flush::L0FlushConfig;
    5591              :     use crate::walredo::apply_neon;
    5592              :     use pageserver_api::key::Key;
    5593              :     use pageserver_api::record::NeonWalRecord;
    5594              : 
    5595              :     use super::*;
    5596              :     use hex_literal::hex;
    5597              :     use utils::id::TenantId;
    5598              : 
    5599              :     pub const TIMELINE_ID: TimelineId =
    5600              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5601              :     pub const NEW_TIMELINE_ID: TimelineId =
    5602              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5603              : 
    5604              :     /// Convenience function to create a page image with given string as the only content
    5605     10057545 :     pub fn test_img(s: &str) -> Bytes {
    5606     10057545 :         let mut buf = BytesMut::new();
    5607     10057545 :         buf.extend_from_slice(s.as_bytes());
    5608     10057545 :         buf.resize(64, 0);
    5609     10057545 : 
    5610     10057545 :         buf.freeze()
    5611     10057545 :     }
    5612              : 
    5613              :     impl From<TenantConf> for TenantConfOpt {
    5614          444 :         fn from(tenant_conf: TenantConf) -> Self {
    5615          444 :             Self {
    5616          444 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5617          444 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5618          444 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5619          444 :                 compaction_period: Some(tenant_conf.compaction_period),
    5620          444 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5621          444 :                 compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
    5622          444 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5623          444 :                 compaction_l0_first: Some(tenant_conf.compaction_l0_first),
    5624          444 :                 compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
    5625          444 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5626          444 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5627          444 :                 l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
    5628          444 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5629          444 :                 gc_period: Some(tenant_conf.gc_period),
    5630          444 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5631          444 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5632          444 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5633          444 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5634          444 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5635          444 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5636          444 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5637          444 :                 evictions_low_residence_duration_metric_threshold: Some(
    5638          444 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5639          444 :                 ),
    5640          444 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5641          444 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5642          444 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5643          444 :                 image_layer_creation_check_threshold: Some(
    5644          444 :                     tenant_conf.image_layer_creation_check_threshold,
    5645          444 :                 ),
    5646          444 :                 image_creation_preempt_threshold: Some(
    5647          444 :                     tenant_conf.image_creation_preempt_threshold,
    5648          444 :                 ),
    5649          444 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5650          444 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5651          444 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5652          444 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5653          444 :                 rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
    5654          444 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5655          444 :                 gc_compaction_initial_threshold_kb: Some(
    5656          444 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5657          444 :                 ),
    5658          444 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5659          444 :             }
    5660          444 :         }
    5661              :     }
    5662              : 
    5663              :     pub struct TenantHarness {
    5664              :         pub conf: &'static PageServerConf,
    5665              :         pub tenant_conf: TenantConf,
    5666              :         pub tenant_shard_id: TenantShardId,
    5667              :         pub generation: Generation,
    5668              :         pub shard: ShardIndex,
    5669              :         pub remote_storage: GenericRemoteStorage,
    5670              :         pub remote_fs_dir: Utf8PathBuf,
    5671              :         pub deletion_queue: MockDeletionQueue,
    5672              :     }
    5673              : 
    5674              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5675              : 
    5676          492 :     pub(crate) fn setup_logging() {
    5677          492 :         LOG_HANDLE.get_or_init(|| {
    5678          468 :             logging::init(
    5679          468 :                 logging::LogFormat::Test,
    5680          468 :                 // enable it in case the tests exercise code paths that use
    5681          468 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5682          468 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5683          468 :                 logging::Output::Stdout,
    5684          468 :             )
    5685          468 :             .expect("Failed to init test logging")
    5686          492 :         });
    5687          492 :     }
    5688              : 
    5689              :     impl TenantHarness {
    5690          444 :         pub async fn create_custom(
    5691          444 :             test_name: &'static str,
    5692          444 :             tenant_conf: TenantConf,
    5693          444 :             tenant_id: TenantId,
    5694          444 :             shard_identity: ShardIdentity,
    5695          444 :             generation: Generation,
    5696          444 :         ) -> anyhow::Result<Self> {
    5697          444 :             setup_logging();
    5698          444 : 
    5699          444 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5700          444 :             let _ = fs::remove_dir_all(&repo_dir);
    5701          444 :             fs::create_dir_all(&repo_dir)?;
    5702              : 
    5703          444 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5704          444 :             // Make a static copy of the config. This can never be free'd, but that's
    5705          444 :             // OK in a test.
    5706          444 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5707          444 : 
    5708          444 :             let shard = shard_identity.shard_index();
    5709          444 :             let tenant_shard_id = TenantShardId {
    5710          444 :                 tenant_id,
    5711          444 :                 shard_number: shard.shard_number,
    5712          444 :                 shard_count: shard.shard_count,
    5713          444 :             };
    5714          444 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5715          444 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5716              : 
    5717              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5718          444 :             let remote_fs_dir = conf.workdir.join("localfs");
    5719          444 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5720          444 :             let config = RemoteStorageConfig {
    5721          444 :                 storage: RemoteStorageKind::LocalFs {
    5722          444 :                     local_path: remote_fs_dir.clone(),
    5723          444 :                 },
    5724          444 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5725          444 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5726          444 :             };
    5727          444 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5728          444 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5729          444 : 
    5730          444 :             Ok(Self {
    5731          444 :                 conf,
    5732          444 :                 tenant_conf,
    5733          444 :                 tenant_shard_id,
    5734          444 :                 generation,
    5735          444 :                 shard,
    5736          444 :                 remote_storage,
    5737          444 :                 remote_fs_dir,
    5738          444 :                 deletion_queue,
    5739          444 :             })
    5740          444 :         }
    5741              : 
    5742          420 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5743          420 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5744          420 :             // The tests perform them manually if needed.
    5745          420 :             let tenant_conf = TenantConf {
    5746          420 :                 gc_period: Duration::ZERO,
    5747          420 :                 compaction_period: Duration::ZERO,
    5748          420 :                 ..TenantConf::default()
    5749          420 :             };
    5750          420 :             let tenant_id = TenantId::generate();
    5751          420 :             let shard = ShardIdentity::unsharded();
    5752          420 :             Self::create_custom(
    5753          420 :                 test_name,
    5754          420 :                 tenant_conf,
    5755          420 :                 tenant_id,
    5756          420 :                 shard,
    5757          420 :                 Generation::new(0xdeadbeef),
    5758          420 :             )
    5759          420 :             .await
    5760          420 :         }
    5761              : 
    5762           40 :         pub fn span(&self) -> tracing::Span {
    5763           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5764           40 :         }
    5765              : 
    5766          444 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5767          444 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5768          444 :             (
    5769          444 :                 self.do_try_load(&ctx)
    5770          444 :                     .await
    5771          444 :                     .expect("failed to load test tenant"),
    5772          444 :                 ctx,
    5773          444 :             )
    5774          444 :         }
    5775              : 
    5776              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5777              :         pub(crate) async fn do_try_load(
    5778              :             &self,
    5779              :             ctx: &RequestContext,
    5780              :         ) -> anyhow::Result<Arc<Tenant>> {
    5781              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5782              : 
    5783              :             let tenant = Arc::new(Tenant::new(
    5784              :                 TenantState::Attaching,
    5785              :                 self.conf,
    5786              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5787              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5788              :                     self.generation,
    5789              :                     &ShardParameters::default(),
    5790              :                 ))
    5791              :                 .unwrap(),
    5792              :                 // This is a legacy/test code path: sharding isn't supported here.
    5793              :                 ShardIdentity::unsharded(),
    5794              :                 Some(walredo_mgr),
    5795              :                 self.tenant_shard_id,
    5796              :                 self.remote_storage.clone(),
    5797              :                 self.deletion_queue.new_client(),
    5798              :                 // TODO: ideally we should run all unit tests with both configs
    5799              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5800              :             ));
    5801              : 
    5802              :             let preload = tenant
    5803              :                 .preload(&self.remote_storage, CancellationToken::new())
    5804              :                 .await?;
    5805              :             tenant.attach(Some(preload), ctx).await?;
    5806              : 
    5807              :             tenant.state.send_replace(TenantState::Active);
    5808              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5809              :                 timeline.set_state(TimelineState::Active);
    5810              :             }
    5811              :             Ok(tenant)
    5812              :         }
    5813              : 
    5814            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5815            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5816            4 :         }
    5817              :     }
    5818              : 
    5819              :     // Mock WAL redo manager that doesn't do much
    5820              :     pub(crate) struct TestRedoManager;
    5821              : 
    5822              :     impl TestRedoManager {
    5823              :         /// # Cancel-Safety
    5824              :         ///
    5825              :         /// This method is cancellation-safe.
    5826         1636 :         pub async fn request_redo(
    5827         1636 :             &self,
    5828         1636 :             key: Key,
    5829         1636 :             lsn: Lsn,
    5830         1636 :             base_img: Option<(Lsn, Bytes)>,
    5831         1636 :             records: Vec<(Lsn, NeonWalRecord)>,
    5832         1636 :             _pg_version: u32,
    5833         1636 :         ) -> Result<Bytes, walredo::Error> {
    5834         2392 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5835         1636 :             if records_neon {
    5836              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5837         1636 :                 let mut page = match (base_img, records.first()) {
    5838         1504 :                     (Some((_lsn, img)), _) => {
    5839         1504 :                         let mut page = BytesMut::new();
    5840         1504 :                         page.extend_from_slice(&img);
    5841         1504 :                         page
    5842              :                     }
    5843          132 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5844              :                     _ => {
    5845            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5846              :                     }
    5847              :                 };
    5848              : 
    5849         4028 :                 for (record_lsn, record) in records {
    5850         2392 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5851              :                 }
    5852         1636 :                 Ok(page.freeze())
    5853              :             } else {
    5854              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5855            0 :                 let s = format!(
    5856            0 :                     "redo for {} to get to {}, with {} and {} records",
    5857            0 :                     key,
    5858            0 :                     lsn,
    5859            0 :                     if base_img.is_some() {
    5860            0 :                         "base image"
    5861              :                     } else {
    5862            0 :                         "no base image"
    5863              :                     },
    5864            0 :                     records.len()
    5865            0 :                 );
    5866            0 :                 println!("{s}");
    5867            0 : 
    5868            0 :                 Ok(test_img(&s))
    5869              :             }
    5870         1636 :         }
    5871              :     }
    5872              : }
    5873              : 
    5874              : #[cfg(test)]
    5875              : mod tests {
    5876              :     use std::collections::{BTreeMap, BTreeSet};
    5877              : 
    5878              :     use super::*;
    5879              :     use crate::keyspace::KeySpaceAccum;
    5880              :     use crate::tenant::harness::*;
    5881              :     use crate::tenant::timeline::CompactFlags;
    5882              :     use crate::DEFAULT_PG_VERSION;
    5883              :     use bytes::{Bytes, BytesMut};
    5884              :     use hex_literal::hex;
    5885              :     use itertools::Itertools;
    5886              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5887              :     use pageserver_api::keyspace::KeySpace;
    5888              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5889              :     use pageserver_api::value::Value;
    5890              :     use pageserver_compaction::helpers::overlaps_with;
    5891              :     use rand::{thread_rng, Rng};
    5892              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5893              :     use tests::storage_layer::ValuesReconstructState;
    5894              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5895              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5896              :     use utils::id::TenantId;
    5897              : 
    5898              :     #[cfg(feature = "testing")]
    5899              :     use models::CompactLsnRange;
    5900              :     #[cfg(feature = "testing")]
    5901              :     use pageserver_api::record::NeonWalRecord;
    5902              :     #[cfg(feature = "testing")]
    5903              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5904              :     #[cfg(feature = "testing")]
    5905              :     use timeline::GcInfo;
    5906              : 
    5907              :     static TEST_KEY: Lazy<Key> =
    5908           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5909              : 
    5910              :     #[tokio::test]
    5911            4 :     async fn test_basic() -> anyhow::Result<()> {
    5912            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5913            4 :         let tline = tenant
    5914            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5915            4 :             .await?;
    5916            4 : 
    5917            4 :         let mut writer = tline.writer().await;
    5918            4 :         writer
    5919            4 :             .put(
    5920            4 :                 *TEST_KEY,
    5921            4 :                 Lsn(0x10),
    5922            4 :                 &Value::Image(test_img("foo at 0x10")),
    5923            4 :                 &ctx,
    5924            4 :             )
    5925            4 :             .await?;
    5926            4 :         writer.finish_write(Lsn(0x10));
    5927            4 :         drop(writer);
    5928            4 : 
    5929            4 :         let mut writer = tline.writer().await;
    5930            4 :         writer
    5931            4 :             .put(
    5932            4 :                 *TEST_KEY,
    5933            4 :                 Lsn(0x20),
    5934            4 :                 &Value::Image(test_img("foo at 0x20")),
    5935            4 :                 &ctx,
    5936            4 :             )
    5937            4 :             .await?;
    5938            4 :         writer.finish_write(Lsn(0x20));
    5939            4 :         drop(writer);
    5940            4 : 
    5941            4 :         assert_eq!(
    5942            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5943            4 :             test_img("foo at 0x10")
    5944            4 :         );
    5945            4 :         assert_eq!(
    5946            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5947            4 :             test_img("foo at 0x10")
    5948            4 :         );
    5949            4 :         assert_eq!(
    5950            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5951            4 :             test_img("foo at 0x20")
    5952            4 :         );
    5953            4 : 
    5954            4 :         Ok(())
    5955            4 :     }
    5956              : 
    5957              :     #[tokio::test]
    5958            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5959            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5960            4 :             .await?
    5961            4 :             .load()
    5962            4 :             .await;
    5963            4 :         let _ = tenant
    5964            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5965            4 :             .await?;
    5966            4 : 
    5967            4 :         match tenant
    5968            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5969            4 :             .await
    5970            4 :         {
    5971            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5972            4 :             Err(e) => assert_eq!(
    5973            4 :                 e.to_string(),
    5974            4 :                 "timeline already exists with different parameters".to_string()
    5975            4 :             ),
    5976            4 :         }
    5977            4 : 
    5978            4 :         Ok(())
    5979            4 :     }
    5980              : 
    5981              :     /// Convenience function to create a page image with given string as the only content
    5982           20 :     pub fn test_value(s: &str) -> Value {
    5983           20 :         let mut buf = BytesMut::new();
    5984           20 :         buf.extend_from_slice(s.as_bytes());
    5985           20 :         Value::Image(buf.freeze())
    5986           20 :     }
    5987              : 
    5988              :     ///
    5989              :     /// Test branch creation
    5990              :     ///
    5991              :     #[tokio::test]
    5992            4 :     async fn test_branch() -> anyhow::Result<()> {
    5993            4 :         use std::str::from_utf8;
    5994            4 : 
    5995            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5996            4 :         let tline = tenant
    5997            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5998            4 :             .await?;
    5999            4 :         let mut writer = tline.writer().await;
    6000            4 : 
    6001            4 :         #[allow(non_snake_case)]
    6002            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6003            4 :         #[allow(non_snake_case)]
    6004            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6005            4 : 
    6006            4 :         // Insert a value on the timeline
    6007            4 :         writer
    6008            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6009            4 :             .await?;
    6010            4 :         writer
    6011            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6012            4 :             .await?;
    6013            4 :         writer.finish_write(Lsn(0x20));
    6014            4 : 
    6015            4 :         writer
    6016            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6017            4 :             .await?;
    6018            4 :         writer.finish_write(Lsn(0x30));
    6019            4 :         writer
    6020            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6021            4 :             .await?;
    6022            4 :         writer.finish_write(Lsn(0x40));
    6023            4 : 
    6024            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6025            4 : 
    6026            4 :         // Branch the history, modify relation differently on the new timeline
    6027            4 :         tenant
    6028            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6029            4 :             .await?;
    6030            4 :         let newtline = tenant
    6031            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6032            4 :             .expect("Should have a local timeline");
    6033            4 :         let mut new_writer = newtline.writer().await;
    6034            4 :         new_writer
    6035            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6036            4 :             .await?;
    6037            4 :         new_writer.finish_write(Lsn(0x40));
    6038            4 : 
    6039            4 :         // Check page contents on both branches
    6040            4 :         assert_eq!(
    6041            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6042            4 :             "foo at 0x40"
    6043            4 :         );
    6044            4 :         assert_eq!(
    6045            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6046            4 :             "bar at 0x40"
    6047            4 :         );
    6048            4 :         assert_eq!(
    6049            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6050            4 :             "foobar at 0x20"
    6051            4 :         );
    6052            4 : 
    6053            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6054            4 : 
    6055            4 :         Ok(())
    6056            4 :     }
    6057              : 
    6058           40 :     async fn make_some_layers(
    6059           40 :         tline: &Timeline,
    6060           40 :         start_lsn: Lsn,
    6061           40 :         ctx: &RequestContext,
    6062           40 :     ) -> anyhow::Result<()> {
    6063           40 :         let mut lsn = start_lsn;
    6064              :         {
    6065           40 :             let mut writer = tline.writer().await;
    6066              :             // Create a relation on the timeline
    6067           40 :             writer
    6068           40 :                 .put(
    6069           40 :                     *TEST_KEY,
    6070           40 :                     lsn,
    6071           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6072           40 :                     ctx,
    6073           40 :                 )
    6074           40 :                 .await?;
    6075           40 :             writer.finish_write(lsn);
    6076           40 :             lsn += 0x10;
    6077           40 :             writer
    6078           40 :                 .put(
    6079           40 :                     *TEST_KEY,
    6080           40 :                     lsn,
    6081           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6082           40 :                     ctx,
    6083           40 :                 )
    6084           40 :                 .await?;
    6085           40 :             writer.finish_write(lsn);
    6086           40 :             lsn += 0x10;
    6087           40 :         }
    6088           40 :         tline.freeze_and_flush().await?;
    6089              :         {
    6090           40 :             let mut writer = tline.writer().await;
    6091           40 :             writer
    6092           40 :                 .put(
    6093           40 :                     *TEST_KEY,
    6094           40 :                     lsn,
    6095           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6096           40 :                     ctx,
    6097           40 :                 )
    6098           40 :                 .await?;
    6099           40 :             writer.finish_write(lsn);
    6100           40 :             lsn += 0x10;
    6101           40 :             writer
    6102           40 :                 .put(
    6103           40 :                     *TEST_KEY,
    6104           40 :                     lsn,
    6105           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6106           40 :                     ctx,
    6107           40 :                 )
    6108           40 :                 .await?;
    6109           40 :             writer.finish_write(lsn);
    6110           40 :         }
    6111           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6112           40 :     }
    6113              : 
    6114              :     #[tokio::test(start_paused = true)]
    6115            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6116            4 :         let (tenant, ctx) =
    6117            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6118            4 :                 .await?
    6119            4 :                 .load()
    6120            4 :                 .await;
    6121            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6122            4 :         // initial transition into AttachedSingle.
    6123            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6124            4 :         tokio::time::resume();
    6125            4 :         let tline = tenant
    6126            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6127            4 :             .await?;
    6128            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6129            4 : 
    6130            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6131            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6132            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6133            4 :         // below should fail.
    6134            4 :         tenant
    6135            4 :             .gc_iteration(
    6136            4 :                 Some(TIMELINE_ID),
    6137            4 :                 0x10,
    6138            4 :                 Duration::ZERO,
    6139            4 :                 &CancellationToken::new(),
    6140            4 :                 &ctx,
    6141            4 :             )
    6142            4 :             .await?;
    6143            4 : 
    6144            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6145            4 :         match tenant
    6146            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6147            4 :             .await
    6148            4 :         {
    6149            4 :             Ok(_) => panic!("branching should have failed"),
    6150            4 :             Err(err) => {
    6151            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6152            4 :                     panic!("wrong error type")
    6153            4 :                 };
    6154            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6155            4 :                 assert!(err
    6156            4 :                     .source()
    6157            4 :                     .unwrap()
    6158            4 :                     .to_string()
    6159            4 :                     .contains("we might've already garbage collected needed data"))
    6160            4 :             }
    6161            4 :         }
    6162            4 : 
    6163            4 :         Ok(())
    6164            4 :     }
    6165              : 
    6166              :     #[tokio::test]
    6167            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6168            4 :         let (tenant, ctx) =
    6169            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6170            4 :                 .await?
    6171            4 :                 .load()
    6172            4 :                 .await;
    6173            4 : 
    6174            4 :         let tline = tenant
    6175            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6176            4 :             .await?;
    6177            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6178            4 :         match tenant
    6179            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6180            4 :             .await
    6181            4 :         {
    6182            4 :             Ok(_) => panic!("branching should have failed"),
    6183            4 :             Err(err) => {
    6184            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6185            4 :                     panic!("wrong error type");
    6186            4 :                 };
    6187            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6188            4 :                 assert!(&err
    6189            4 :                     .source()
    6190            4 :                     .unwrap()
    6191            4 :                     .to_string()
    6192            4 :                     .contains("is earlier than latest GC cutoff"));
    6193            4 :             }
    6194            4 :         }
    6195            4 : 
    6196            4 :         Ok(())
    6197            4 :     }
    6198              : 
    6199              :     /*
    6200              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6201              :     // remove the old value, we'd need to work a little harder
    6202              :     #[tokio::test]
    6203              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6204              :         let repo =
    6205              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6206              :             .load();
    6207              : 
    6208              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6209              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6210              : 
    6211              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6212              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6213              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6214              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6215              :             Ok(_) => panic!("request for page should have failed"),
    6216              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6217              :         }
    6218              :         Ok(())
    6219              :     }
    6220              :      */
    6221              : 
    6222              :     #[tokio::test]
    6223            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6224            4 :         let (tenant, ctx) =
    6225            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6226            4 :                 .await?
    6227            4 :                 .load()
    6228            4 :                 .await;
    6229            4 :         let tline = tenant
    6230            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6231            4 :             .await?;
    6232            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6233            4 : 
    6234            4 :         tenant
    6235            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6236            4 :             .await?;
    6237            4 :         let newtline = tenant
    6238            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6239            4 :             .expect("Should have a local timeline");
    6240            4 : 
    6241            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6242            4 : 
    6243            4 :         tline.set_broken("test".to_owned());
    6244            4 : 
    6245            4 :         tenant
    6246            4 :             .gc_iteration(
    6247            4 :                 Some(TIMELINE_ID),
    6248            4 :                 0x10,
    6249            4 :                 Duration::ZERO,
    6250            4 :                 &CancellationToken::new(),
    6251            4 :                 &ctx,
    6252            4 :             )
    6253            4 :             .await?;
    6254            4 : 
    6255            4 :         // The branchpoints should contain all timelines, even ones marked
    6256            4 :         // as Broken.
    6257            4 :         {
    6258            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6259            4 :             assert_eq!(branchpoints.len(), 1);
    6260            4 :             assert_eq!(
    6261            4 :                 branchpoints[0],
    6262            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6263            4 :             );
    6264            4 :         }
    6265            4 : 
    6266            4 :         // You can read the key from the child branch even though the parent is
    6267            4 :         // Broken, as long as you don't need to access data from the parent.
    6268            4 :         assert_eq!(
    6269            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6270            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6271            4 :         );
    6272            4 : 
    6273            4 :         // This needs to traverse to the parent, and fails.
    6274            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6275            4 :         assert!(
    6276            4 :             err.to_string().starts_with(&format!(
    6277            4 :                 "bad state on timeline {}: Broken",
    6278            4 :                 tline.timeline_id
    6279            4 :             )),
    6280            4 :             "{err}"
    6281            4 :         );
    6282            4 : 
    6283            4 :         Ok(())
    6284            4 :     }
    6285              : 
    6286              :     #[tokio::test]
    6287            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6288            4 :         let (tenant, ctx) =
    6289            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6290            4 :                 .await?
    6291            4 :                 .load()
    6292            4 :                 .await;
    6293            4 :         let tline = tenant
    6294            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6295            4 :             .await?;
    6296            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6297            4 : 
    6298            4 :         tenant
    6299            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6300            4 :             .await?;
    6301            4 :         let newtline = tenant
    6302            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6303            4 :             .expect("Should have a local timeline");
    6304            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6305            4 :         tenant
    6306            4 :             .gc_iteration(
    6307            4 :                 Some(TIMELINE_ID),
    6308            4 :                 0x10,
    6309            4 :                 Duration::ZERO,
    6310            4 :                 &CancellationToken::new(),
    6311            4 :                 &ctx,
    6312            4 :             )
    6313            4 :             .await?;
    6314            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6315            4 : 
    6316            4 :         Ok(())
    6317            4 :     }
    6318              :     #[tokio::test]
    6319            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6320            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6321            4 :             .await?
    6322            4 :             .load()
    6323            4 :             .await;
    6324            4 :         let tline = tenant
    6325            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6326            4 :             .await?;
    6327            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6328            4 : 
    6329            4 :         tenant
    6330            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6331            4 :             .await?;
    6332            4 :         let newtline = tenant
    6333            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6334            4 :             .expect("Should have a local timeline");
    6335            4 : 
    6336            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6337            4 : 
    6338            4 :         // run gc on parent
    6339            4 :         tenant
    6340            4 :             .gc_iteration(
    6341            4 :                 Some(TIMELINE_ID),
    6342            4 :                 0x10,
    6343            4 :                 Duration::ZERO,
    6344            4 :                 &CancellationToken::new(),
    6345            4 :                 &ctx,
    6346            4 :             )
    6347            4 :             .await?;
    6348            4 : 
    6349            4 :         // Check that the data is still accessible on the branch.
    6350            4 :         assert_eq!(
    6351            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6352            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6353            4 :         );
    6354            4 : 
    6355            4 :         Ok(())
    6356            4 :     }
    6357              : 
    6358              :     #[tokio::test]
    6359            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6360            4 :         const TEST_NAME: &str = "timeline_load";
    6361            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6362            4 :         {
    6363            4 :             let (tenant, ctx) = harness.load().await;
    6364            4 :             let tline = tenant
    6365            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6366            4 :                 .await?;
    6367            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6368            4 :             // so that all uploads finish & we can call harness.load() below again
    6369            4 :             tenant
    6370            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6371            4 :                 .instrument(harness.span())
    6372            4 :                 .await
    6373            4 :                 .ok()
    6374            4 :                 .unwrap();
    6375            4 :         }
    6376            4 : 
    6377            4 :         let (tenant, _ctx) = harness.load().await;
    6378            4 :         tenant
    6379            4 :             .get_timeline(TIMELINE_ID, true)
    6380            4 :             .expect("cannot load timeline");
    6381            4 : 
    6382            4 :         Ok(())
    6383            4 :     }
    6384              : 
    6385              :     #[tokio::test]
    6386            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6387            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6388            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6389            4 :         // create two timelines
    6390            4 :         {
    6391            4 :             let (tenant, ctx) = harness.load().await;
    6392            4 :             let tline = tenant
    6393            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6394            4 :                 .await?;
    6395            4 : 
    6396            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6397            4 : 
    6398            4 :             let child_tline = tenant
    6399            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6400            4 :                 .await?;
    6401            4 :             child_tline.set_state(TimelineState::Active);
    6402            4 : 
    6403            4 :             let newtline = tenant
    6404            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6405            4 :                 .expect("Should have a local timeline");
    6406            4 : 
    6407            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6408            4 : 
    6409            4 :             // so that all uploads finish & we can call harness.load() below again
    6410            4 :             tenant
    6411            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6412            4 :                 .instrument(harness.span())
    6413            4 :                 .await
    6414            4 :                 .ok()
    6415            4 :                 .unwrap();
    6416            4 :         }
    6417            4 : 
    6418            4 :         // check that both of them are initially unloaded
    6419            4 :         let (tenant, _ctx) = harness.load().await;
    6420            4 : 
    6421            4 :         // check that both, child and ancestor are loaded
    6422            4 :         let _child_tline = tenant
    6423            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6424            4 :             .expect("cannot get child timeline loaded");
    6425            4 : 
    6426            4 :         let _ancestor_tline = tenant
    6427            4 :             .get_timeline(TIMELINE_ID, true)
    6428            4 :             .expect("cannot get ancestor timeline loaded");
    6429            4 : 
    6430            4 :         Ok(())
    6431            4 :     }
    6432              : 
    6433              :     #[tokio::test]
    6434            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6435            4 :         use storage_layer::AsLayerDesc;
    6436            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6437            4 :             .await?
    6438            4 :             .load()
    6439            4 :             .await;
    6440            4 :         let tline = tenant
    6441            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6442            4 :             .await?;
    6443            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6444            4 : 
    6445            4 :         let layer_map = tline.layers.read().await;
    6446            4 :         let level0_deltas = layer_map
    6447            4 :             .layer_map()?
    6448            4 :             .level0_deltas()
    6449            4 :             .iter()
    6450            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6451            4 :             .collect::<Vec<_>>();
    6452            4 : 
    6453            4 :         assert!(!level0_deltas.is_empty());
    6454            4 : 
    6455           12 :         for delta in level0_deltas {
    6456            4 :             // Ensure we are dumping a delta layer here
    6457            8 :             assert!(delta.layer_desc().is_delta);
    6458            8 :             delta.dump(true, &ctx).await.unwrap();
    6459            4 :         }
    6460            4 : 
    6461            4 :         Ok(())
    6462            4 :     }
    6463              : 
    6464              :     #[tokio::test]
    6465            4 :     async fn test_images() -> anyhow::Result<()> {
    6466            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6467            4 :         let tline = tenant
    6468            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6469            4 :             .await?;
    6470            4 : 
    6471            4 :         let mut writer = tline.writer().await;
    6472            4 :         writer
    6473            4 :             .put(
    6474            4 :                 *TEST_KEY,
    6475            4 :                 Lsn(0x10),
    6476            4 :                 &Value::Image(test_img("foo at 0x10")),
    6477            4 :                 &ctx,
    6478            4 :             )
    6479            4 :             .await?;
    6480            4 :         writer.finish_write(Lsn(0x10));
    6481            4 :         drop(writer);
    6482            4 : 
    6483            4 :         tline.freeze_and_flush().await?;
    6484            4 :         tline
    6485            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6486            4 :             .await?;
    6487            4 : 
    6488            4 :         let mut writer = tline.writer().await;
    6489            4 :         writer
    6490            4 :             .put(
    6491            4 :                 *TEST_KEY,
    6492            4 :                 Lsn(0x20),
    6493            4 :                 &Value::Image(test_img("foo at 0x20")),
    6494            4 :                 &ctx,
    6495            4 :             )
    6496            4 :             .await?;
    6497            4 :         writer.finish_write(Lsn(0x20));
    6498            4 :         drop(writer);
    6499            4 : 
    6500            4 :         tline.freeze_and_flush().await?;
    6501            4 :         tline
    6502            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6503            4 :             .await?;
    6504            4 : 
    6505            4 :         let mut writer = tline.writer().await;
    6506            4 :         writer
    6507            4 :             .put(
    6508            4 :                 *TEST_KEY,
    6509            4 :                 Lsn(0x30),
    6510            4 :                 &Value::Image(test_img("foo at 0x30")),
    6511            4 :                 &ctx,
    6512            4 :             )
    6513            4 :             .await?;
    6514            4 :         writer.finish_write(Lsn(0x30));
    6515            4 :         drop(writer);
    6516            4 : 
    6517            4 :         tline.freeze_and_flush().await?;
    6518            4 :         tline
    6519            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6520            4 :             .await?;
    6521            4 : 
    6522            4 :         let mut writer = tline.writer().await;
    6523            4 :         writer
    6524            4 :             .put(
    6525            4 :                 *TEST_KEY,
    6526            4 :                 Lsn(0x40),
    6527            4 :                 &Value::Image(test_img("foo at 0x40")),
    6528            4 :                 &ctx,
    6529            4 :             )
    6530            4 :             .await?;
    6531            4 :         writer.finish_write(Lsn(0x40));
    6532            4 :         drop(writer);
    6533            4 : 
    6534            4 :         tline.freeze_and_flush().await?;
    6535            4 :         tline
    6536            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6537            4 :             .await?;
    6538            4 : 
    6539            4 :         assert_eq!(
    6540            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6541            4 :             test_img("foo at 0x10")
    6542            4 :         );
    6543            4 :         assert_eq!(
    6544            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6545            4 :             test_img("foo at 0x10")
    6546            4 :         );
    6547            4 :         assert_eq!(
    6548            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6549            4 :             test_img("foo at 0x20")
    6550            4 :         );
    6551            4 :         assert_eq!(
    6552            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6553            4 :             test_img("foo at 0x30")
    6554            4 :         );
    6555            4 :         assert_eq!(
    6556            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6557            4 :             test_img("foo at 0x40")
    6558            4 :         );
    6559            4 : 
    6560            4 :         Ok(())
    6561            4 :     }
    6562              : 
    6563            8 :     async fn bulk_insert_compact_gc(
    6564            8 :         tenant: &Tenant,
    6565            8 :         timeline: &Arc<Timeline>,
    6566            8 :         ctx: &RequestContext,
    6567            8 :         lsn: Lsn,
    6568            8 :         repeat: usize,
    6569            8 :         key_count: usize,
    6570            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6571            8 :         let compact = true;
    6572            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6573            8 :     }
    6574              : 
    6575           16 :     async fn bulk_insert_maybe_compact_gc(
    6576           16 :         tenant: &Tenant,
    6577           16 :         timeline: &Arc<Timeline>,
    6578           16 :         ctx: &RequestContext,
    6579           16 :         mut lsn: Lsn,
    6580           16 :         repeat: usize,
    6581           16 :         key_count: usize,
    6582           16 :         compact: bool,
    6583           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6584           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6585           16 : 
    6586           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6587           16 :         let mut blknum = 0;
    6588           16 : 
    6589           16 :         // Enforce that key range is monotonously increasing
    6590           16 :         let mut keyspace = KeySpaceAccum::new();
    6591           16 : 
    6592           16 :         let cancel = CancellationToken::new();
    6593           16 : 
    6594           16 :         for _ in 0..repeat {
    6595          800 :             for _ in 0..key_count {
    6596      8000000 :                 test_key.field6 = blknum;
    6597      8000000 :                 let mut writer = timeline.writer().await;
    6598      8000000 :                 writer
    6599      8000000 :                     .put(
    6600      8000000 :                         test_key,
    6601      8000000 :                         lsn,
    6602      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6603      8000000 :                         ctx,
    6604      8000000 :                     )
    6605      8000000 :                     .await?;
    6606      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6607      8000000 :                 writer.finish_write(lsn);
    6608      8000000 :                 drop(writer);
    6609      8000000 : 
    6610      8000000 :                 keyspace.add_key(test_key);
    6611      8000000 : 
    6612      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6613      8000000 :                 blknum += 1;
    6614              :             }
    6615              : 
    6616          800 :             timeline.freeze_and_flush().await?;
    6617          800 :             if compact {
    6618              :                 // this requires timeline to be &Arc<Timeline>
    6619          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6620          400 :             }
    6621              : 
    6622              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6623              :             // originally was.
    6624          800 :             let res = tenant
    6625          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6626          800 :                 .await?;
    6627              : 
    6628          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6629              :         }
    6630              : 
    6631           16 :         Ok(inserted)
    6632           16 :     }
    6633              : 
    6634              :     //
    6635              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6636              :     // Repeat 50 times.
    6637              :     //
    6638              :     #[tokio::test]
    6639            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6640            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6641            4 :         let (tenant, ctx) = harness.load().await;
    6642            4 :         let tline = tenant
    6643            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6644            4 :             .await?;
    6645            4 : 
    6646            4 :         let lsn = Lsn(0x10);
    6647            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6648            4 : 
    6649            4 :         Ok(())
    6650            4 :     }
    6651              : 
    6652              :     // Test the vectored get real implementation against a simple sequential implementation.
    6653              :     //
    6654              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6655              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6656              :     // grow to the right on the X axis.
    6657              :     //                       [Delta]
    6658              :     //                 [Delta]
    6659              :     //           [Delta]
    6660              :     //    [Delta]
    6661              :     // ------------ Image ---------------
    6662              :     //
    6663              :     // After layer generation we pick the ranges to query as follows:
    6664              :     // 1. The beginning of each delta layer
    6665              :     // 2. At the seam between two adjacent delta layers
    6666              :     //
    6667              :     // There's one major downside to this test: delta layers only contains images,
    6668              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6669              :     #[tokio::test]
    6670            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6671            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6672            4 :         let (tenant, ctx) = harness.load().await;
    6673            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6674            4 :         let tline = tenant
    6675            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6676            4 :             .await?;
    6677            4 : 
    6678            4 :         let lsn = Lsn(0x10);
    6679            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6680            4 : 
    6681            4 :         let guard = tline.layers.read().await;
    6682            4 :         let lm = guard.layer_map()?;
    6683            4 : 
    6684            4 :         lm.dump(true, &ctx).await?;
    6685            4 : 
    6686            4 :         let mut reads = Vec::new();
    6687            4 :         let mut prev = None;
    6688           24 :         lm.iter_historic_layers().for_each(|desc| {
    6689           24 :             if !desc.is_delta() {
    6690            4 :                 prev = Some(desc.clone());
    6691            4 :                 return;
    6692           20 :             }
    6693           20 : 
    6694           20 :             let start = desc.key_range.start;
    6695           20 :             let end = desc
    6696           20 :                 .key_range
    6697           20 :                 .start
    6698           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6699           20 :             reads.push(KeySpace {
    6700           20 :                 ranges: vec![start..end],
    6701           20 :             });
    6702            4 : 
    6703           20 :             if let Some(prev) = &prev {
    6704           20 :                 if !prev.is_delta() {
    6705           20 :                     return;
    6706            4 :                 }
    6707            0 : 
    6708            0 :                 let first_range = Key {
    6709            0 :                     field6: prev.key_range.end.field6 - 4,
    6710            0 :                     ..prev.key_range.end
    6711            0 :                 }..prev.key_range.end;
    6712            0 : 
    6713            0 :                 let second_range = desc.key_range.start..Key {
    6714            0 :                     field6: desc.key_range.start.field6 + 4,
    6715            0 :                     ..desc.key_range.start
    6716            0 :                 };
    6717            0 : 
    6718            0 :                 reads.push(KeySpace {
    6719            0 :                     ranges: vec![first_range, second_range],
    6720            0 :                 });
    6721            4 :             };
    6722            4 : 
    6723            4 :             prev = Some(desc.clone());
    6724           24 :         });
    6725            4 : 
    6726            4 :         drop(guard);
    6727            4 : 
    6728            4 :         // Pick a big LSN such that we query over all the changes.
    6729            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6730            4 : 
    6731           24 :         for read in reads {
    6732           20 :             info!("Doing vectored read on {:?}", read);
    6733            4 : 
    6734           20 :             let vectored_res = tline
    6735           20 :                 .get_vectored_impl(
    6736           20 :                     read.clone(),
    6737           20 :                     reads_lsn,
    6738           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6739           20 :                     &ctx,
    6740           20 :                 )
    6741           20 :                 .await;
    6742            4 : 
    6743           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6744           20 :             let mut expect_missing = false;
    6745           20 :             let mut key = read.start().unwrap();
    6746          660 :             while key != read.end().unwrap() {
    6747          640 :                 if let Some(lsns) = inserted.get(&key) {
    6748          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6749          640 :                     match expected_lsn {
    6750          640 :                         Some(lsn) => {
    6751          640 :                             expected_lsns.insert(key, *lsn);
    6752          640 :                         }
    6753            4 :                         None => {
    6754            4 :                             expect_missing = true;
    6755            0 :                             break;
    6756            4 :                         }
    6757            4 :                     }
    6758            4 :                 } else {
    6759            4 :                     expect_missing = true;
    6760            0 :                     break;
    6761            4 :                 }
    6762            4 : 
    6763          640 :                 key = key.next();
    6764            4 :             }
    6765            4 : 
    6766           20 :             if expect_missing {
    6767            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6768            4 :             } else {
    6769          640 :                 for (key, image) in vectored_res? {
    6770          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6771          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6772          640 :                     assert_eq!(image?, expected_image);
    6773            4 :                 }
    6774            4 :             }
    6775            4 :         }
    6776            4 : 
    6777            4 :         Ok(())
    6778            4 :     }
    6779              : 
    6780              :     #[tokio::test]
    6781            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6782            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6783            4 : 
    6784            4 :         let (tenant, ctx) = harness.load().await;
    6785            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6786            4 :         let tline = tenant
    6787            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6788            4 :             .await?;
    6789            4 :         let tline = tline.raw_timeline().unwrap();
    6790            4 : 
    6791            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6792            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6793            4 :         modification.set_lsn(Lsn(0x1008))?;
    6794            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6795            4 :         modification.commit(&ctx).await?;
    6796            4 : 
    6797            4 :         let child_timeline_id = TimelineId::generate();
    6798            4 :         tenant
    6799            4 :             .branch_timeline_test(
    6800            4 :                 tline,
    6801            4 :                 child_timeline_id,
    6802            4 :                 Some(tline.get_last_record_lsn()),
    6803            4 :                 &ctx,
    6804            4 :             )
    6805            4 :             .await?;
    6806            4 : 
    6807            4 :         let child_timeline = tenant
    6808            4 :             .get_timeline(child_timeline_id, true)
    6809            4 :             .expect("Should have the branched timeline");
    6810            4 : 
    6811            4 :         let aux_keyspace = KeySpace {
    6812            4 :             ranges: vec![NON_INHERITED_RANGE],
    6813            4 :         };
    6814            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6815            4 : 
    6816            4 :         let vectored_res = child_timeline
    6817            4 :             .get_vectored_impl(
    6818            4 :                 aux_keyspace.clone(),
    6819            4 :                 read_lsn,
    6820            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6821            4 :                 &ctx,
    6822            4 :             )
    6823            4 :             .await;
    6824            4 : 
    6825            4 :         let images = vectored_res?;
    6826            4 :         assert!(images.is_empty());
    6827            4 :         Ok(())
    6828            4 :     }
    6829              : 
    6830              :     // Test that vectored get handles layer gaps correctly
    6831              :     // by advancing into the next ancestor timeline if required.
    6832              :     //
    6833              :     // The test generates timelines that look like the diagram below.
    6834              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6835              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6836              :     //
    6837              :     // ```
    6838              :     //-------------------------------+
    6839              :     //                          ...  |
    6840              :     //               [   L1   ]      |
    6841              :     //     [ / L1   ]                | Child Timeline
    6842              :     // ...                           |
    6843              :     // ------------------------------+
    6844              :     //     [ X L1   ]                | Parent Timeline
    6845              :     // ------------------------------+
    6846              :     // ```
    6847              :     #[tokio::test]
    6848            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6849            4 :         let tenant_conf = TenantConf {
    6850            4 :             // Make compaction deterministic
    6851            4 :             gc_period: Duration::ZERO,
    6852            4 :             compaction_period: Duration::ZERO,
    6853            4 :             // Encourage creation of L1 layers
    6854            4 :             checkpoint_distance: 16 * 1024,
    6855            4 :             compaction_target_size: 8 * 1024,
    6856            4 :             ..TenantConf::default()
    6857            4 :         };
    6858            4 : 
    6859            4 :         let harness = TenantHarness::create_custom(
    6860            4 :             "test_get_vectored_key_gap",
    6861            4 :             tenant_conf,
    6862            4 :             TenantId::generate(),
    6863            4 :             ShardIdentity::unsharded(),
    6864            4 :             Generation::new(0xdeadbeef),
    6865            4 :         )
    6866            4 :         .await?;
    6867            4 :         let (tenant, ctx) = harness.load().await;
    6868            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6869            4 : 
    6870            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6871            4 :         let gap_at_key = current_key.add(100);
    6872            4 :         let mut current_lsn = Lsn(0x10);
    6873            4 : 
    6874            4 :         const KEY_COUNT: usize = 10_000;
    6875            4 : 
    6876            4 :         let timeline_id = TimelineId::generate();
    6877            4 :         let current_timeline = tenant
    6878            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6879            4 :             .await?;
    6880            4 : 
    6881            4 :         current_lsn += 0x100;
    6882            4 : 
    6883            4 :         let mut writer = current_timeline.writer().await;
    6884            4 :         writer
    6885            4 :             .put(
    6886            4 :                 gap_at_key,
    6887            4 :                 current_lsn,
    6888            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6889            4 :                 &ctx,
    6890            4 :             )
    6891            4 :             .await?;
    6892            4 :         writer.finish_write(current_lsn);
    6893            4 :         drop(writer);
    6894            4 : 
    6895            4 :         let mut latest_lsns = HashMap::new();
    6896            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6897            4 : 
    6898            4 :         current_timeline.freeze_and_flush().await?;
    6899            4 : 
    6900            4 :         let child_timeline_id = TimelineId::generate();
    6901            4 : 
    6902            4 :         tenant
    6903            4 :             .branch_timeline_test(
    6904            4 :                 &current_timeline,
    6905            4 :                 child_timeline_id,
    6906            4 :                 Some(current_lsn),
    6907            4 :                 &ctx,
    6908            4 :             )
    6909            4 :             .await?;
    6910            4 :         let child_timeline = tenant
    6911            4 :             .get_timeline(child_timeline_id, true)
    6912            4 :             .expect("Should have the branched timeline");
    6913            4 : 
    6914        40004 :         for i in 0..KEY_COUNT {
    6915        40000 :             if current_key == gap_at_key {
    6916            4 :                 current_key = current_key.next();
    6917            4 :                 continue;
    6918        39996 :             }
    6919        39996 : 
    6920        39996 :             current_lsn += 0x10;
    6921            4 : 
    6922        39996 :             let mut writer = child_timeline.writer().await;
    6923        39996 :             writer
    6924        39996 :                 .put(
    6925        39996 :                     current_key,
    6926        39996 :                     current_lsn,
    6927        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6928        39996 :                     &ctx,
    6929        39996 :                 )
    6930        39996 :                 .await?;
    6931        39996 :             writer.finish_write(current_lsn);
    6932        39996 :             drop(writer);
    6933        39996 : 
    6934        39996 :             latest_lsns.insert(current_key, current_lsn);
    6935        39996 :             current_key = current_key.next();
    6936        39996 : 
    6937        39996 :             // Flush every now and then to encourage layer file creation.
    6938        39996 :             if i % 500 == 0 {
    6939           80 :                 child_timeline.freeze_and_flush().await?;
    6940        39916 :             }
    6941            4 :         }
    6942            4 : 
    6943            4 :         child_timeline.freeze_and_flush().await?;
    6944            4 :         let mut flags = EnumSet::new();
    6945            4 :         flags.insert(CompactFlags::ForceRepartition);
    6946            4 :         child_timeline
    6947            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    6948            4 :             .await?;
    6949            4 : 
    6950            4 :         let key_near_end = {
    6951            4 :             let mut tmp = current_key;
    6952            4 :             tmp.field6 -= 10;
    6953            4 :             tmp
    6954            4 :         };
    6955            4 : 
    6956            4 :         let key_near_gap = {
    6957            4 :             let mut tmp = gap_at_key;
    6958            4 :             tmp.field6 -= 10;
    6959            4 :             tmp
    6960            4 :         };
    6961            4 : 
    6962            4 :         let read = KeySpace {
    6963            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6964            4 :         };
    6965            4 :         let results = child_timeline
    6966            4 :             .get_vectored_impl(
    6967            4 :                 read.clone(),
    6968            4 :                 current_lsn,
    6969            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6970            4 :                 &ctx,
    6971            4 :             )
    6972            4 :             .await?;
    6973            4 : 
    6974           88 :         for (key, img_res) in results {
    6975           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6976           84 :             assert_eq!(img_res?, expected);
    6977            4 :         }
    6978            4 : 
    6979            4 :         Ok(())
    6980            4 :     }
    6981              : 
    6982              :     // Test that vectored get descends into ancestor timelines correctly and
    6983              :     // does not return an image that's newer than requested.
    6984              :     //
    6985              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6986              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6987              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6988              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6989              :     // order to avoid returning an image that's too new. The test below constructs such
    6990              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6991              :     // ```
    6992              :     //    LSN
    6993              :     //     ^
    6994              :     //     |
    6995              :     //     |
    6996              :     // 500 | --------------------------------------> branch point
    6997              :     // 400 |        X
    6998              :     // 300 |        X
    6999              :     // 200 | --------------------------------------> requested lsn
    7000              :     // 100 |        X
    7001              :     //     |---------------------------------------> Key
    7002              :     //              |
    7003              :     //              ------> requested key
    7004              :     //
    7005              :     // Legend:
    7006              :     // * X - page images
    7007              :     // ```
    7008              :     #[tokio::test]
    7009            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7010            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7011            4 :         let (tenant, ctx) = harness.load().await;
    7012            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7013            4 : 
    7014            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7015            4 :         let end_key = start_key.add(1000);
    7016            4 :         let child_gap_at_key = start_key.add(500);
    7017            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7018            4 : 
    7019            4 :         let mut current_lsn = Lsn(0x10);
    7020            4 : 
    7021            4 :         let timeline_id = TimelineId::generate();
    7022            4 :         let parent_timeline = tenant
    7023            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7024            4 :             .await?;
    7025            4 : 
    7026            4 :         current_lsn += 0x100;
    7027            4 : 
    7028           16 :         for _ in 0..3 {
    7029           12 :             let mut key = start_key;
    7030        12012 :             while key < end_key {
    7031        12000 :                 current_lsn += 0x10;
    7032        12000 : 
    7033        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7034            4 : 
    7035        12000 :                 let mut writer = parent_timeline.writer().await;
    7036        12000 :                 writer
    7037        12000 :                     .put(
    7038        12000 :                         key,
    7039        12000 :                         current_lsn,
    7040        12000 :                         &Value::Image(test_img(&image_value)),
    7041        12000 :                         &ctx,
    7042        12000 :                     )
    7043        12000 :                     .await?;
    7044        12000 :                 writer.finish_write(current_lsn);
    7045        12000 : 
    7046        12000 :                 if key == child_gap_at_key {
    7047           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7048        11988 :                 }
    7049            4 : 
    7050        12000 :                 key = key.next();
    7051            4 :             }
    7052            4 : 
    7053           12 :             parent_timeline.freeze_and_flush().await?;
    7054            4 :         }
    7055            4 : 
    7056            4 :         let child_timeline_id = TimelineId::generate();
    7057            4 : 
    7058            4 :         let child_timeline = tenant
    7059            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7060            4 :             .await?;
    7061            4 : 
    7062            4 :         let mut key = start_key;
    7063         4004 :         while key < end_key {
    7064         4000 :             if key == child_gap_at_key {
    7065            4 :                 key = key.next();
    7066            4 :                 continue;
    7067         3996 :             }
    7068         3996 : 
    7069         3996 :             current_lsn += 0x10;
    7070            4 : 
    7071         3996 :             let mut writer = child_timeline.writer().await;
    7072         3996 :             writer
    7073         3996 :                 .put(
    7074         3996 :                     key,
    7075         3996 :                     current_lsn,
    7076         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7077         3996 :                     &ctx,
    7078         3996 :                 )
    7079         3996 :                 .await?;
    7080         3996 :             writer.finish_write(current_lsn);
    7081         3996 : 
    7082         3996 :             key = key.next();
    7083            4 :         }
    7084            4 : 
    7085            4 :         child_timeline.freeze_and_flush().await?;
    7086            4 : 
    7087            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7088            4 :         let mut query_lsns = Vec::new();
    7089           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7090           72 :             for offset in lsn_offsets {
    7091           60 :                 query_lsns.push(Lsn(image_lsn
    7092           60 :                     .0
    7093           60 :                     .checked_add_signed(offset)
    7094           60 :                     .expect("Shouldn't overflow")));
    7095           60 :             }
    7096            4 :         }
    7097            4 : 
    7098           64 :         for query_lsn in query_lsns {
    7099           60 :             let results = child_timeline
    7100           60 :                 .get_vectored_impl(
    7101           60 :                     KeySpace {
    7102           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7103           60 :                     },
    7104           60 :                     query_lsn,
    7105           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7106           60 :                     &ctx,
    7107           60 :                 )
    7108           60 :                 .await;
    7109            4 : 
    7110           60 :             let expected_item = parent_gap_lsns
    7111           60 :                 .iter()
    7112           60 :                 .rev()
    7113          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7114           60 : 
    7115           60 :             info!(
    7116            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7117            4 :                 query_lsn, expected_item
    7118            4 :             );
    7119            4 : 
    7120           60 :             match expected_item {
    7121           52 :                 Some((_, img_value)) => {
    7122           52 :                     let key_results = results.expect("No vectored get error expected");
    7123           52 :                     let key_result = &key_results[&child_gap_at_key];
    7124           52 :                     let returned_img = key_result
    7125           52 :                         .as_ref()
    7126           52 :                         .expect("No page reconstruct error expected");
    7127           52 : 
    7128           52 :                     info!(
    7129            4 :                         "Vectored read at LSN {} returned image {}",
    7130            0 :                         query_lsn,
    7131            0 :                         std::str::from_utf8(returned_img)?
    7132            4 :                     );
    7133           52 :                     assert_eq!(*returned_img, test_img(img_value));
    7134            4 :                 }
    7135            4 :                 None => {
    7136            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7137            4 :                 }
    7138            4 :             }
    7139            4 :         }
    7140            4 : 
    7141            4 :         Ok(())
    7142            4 :     }
    7143              : 
    7144              :     #[tokio::test]
    7145            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    7146            4 :         let names_algorithms = [
    7147            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7148            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7149            4 :         ];
    7150           12 :         for (name, algorithm) in names_algorithms {
    7151            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7152            4 :         }
    7153            4 :         Ok(())
    7154            4 :     }
    7155              : 
    7156            8 :     async fn test_random_updates_algorithm(
    7157            8 :         name: &'static str,
    7158            8 :         compaction_algorithm: CompactionAlgorithm,
    7159            8 :     ) -> anyhow::Result<()> {
    7160            8 :         let mut harness = TenantHarness::create(name).await?;
    7161            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7162            8 :             kind: compaction_algorithm,
    7163            8 :         };
    7164            8 :         let (tenant, ctx) = harness.load().await;
    7165            8 :         let tline = tenant
    7166            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7167            8 :             .await?;
    7168              : 
    7169              :         const NUM_KEYS: usize = 1000;
    7170            8 :         let cancel = CancellationToken::new();
    7171            8 : 
    7172            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7173            8 :         let mut test_key_end = test_key;
    7174            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7175            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7176            8 : 
    7177            8 :         let mut keyspace = KeySpaceAccum::new();
    7178            8 : 
    7179            8 :         // Track when each page was last modified. Used to assert that
    7180            8 :         // a read sees the latest page version.
    7181            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7182            8 : 
    7183            8 :         let mut lsn = Lsn(0x10);
    7184              :         #[allow(clippy::needless_range_loop)]
    7185         8008 :         for blknum in 0..NUM_KEYS {
    7186         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7187         8000 :             test_key.field6 = blknum as u32;
    7188         8000 :             let mut writer = tline.writer().await;
    7189         8000 :             writer
    7190         8000 :                 .put(
    7191         8000 :                     test_key,
    7192         8000 :                     lsn,
    7193         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7194         8000 :                     &ctx,
    7195         8000 :                 )
    7196         8000 :                 .await?;
    7197         8000 :             writer.finish_write(lsn);
    7198         8000 :             updated[blknum] = lsn;
    7199         8000 :             drop(writer);
    7200         8000 : 
    7201         8000 :             keyspace.add_key(test_key);
    7202              :         }
    7203              : 
    7204          408 :         for _ in 0..50 {
    7205       400400 :             for _ in 0..NUM_KEYS {
    7206       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7207       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7208       400000 :                 test_key.field6 = blknum as u32;
    7209       400000 :                 let mut writer = tline.writer().await;
    7210       400000 :                 writer
    7211       400000 :                     .put(
    7212       400000 :                         test_key,
    7213       400000 :                         lsn,
    7214       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7215       400000 :                         &ctx,
    7216       400000 :                     )
    7217       400000 :                     .await?;
    7218       400000 :                 writer.finish_write(lsn);
    7219       400000 :                 drop(writer);
    7220       400000 :                 updated[blknum] = lsn;
    7221              :             }
    7222              : 
    7223              :             // Read all the blocks
    7224       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7225       400000 :                 test_key.field6 = blknum as u32;
    7226       400000 :                 assert_eq!(
    7227       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7228       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7229              :                 );
    7230              :             }
    7231              : 
    7232              :             // Perform a cycle of flush, and GC
    7233          400 :             tline.freeze_and_flush().await?;
    7234          400 :             tenant
    7235          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7236          400 :                 .await?;
    7237              :         }
    7238              : 
    7239            8 :         Ok(())
    7240            8 :     }
    7241              : 
    7242              :     #[tokio::test]
    7243            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7244            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7245            4 :             .await?
    7246            4 :             .load()
    7247            4 :             .await;
    7248            4 :         let mut tline = tenant
    7249            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7250            4 :             .await?;
    7251            4 : 
    7252            4 :         const NUM_KEYS: usize = 1000;
    7253            4 : 
    7254            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7255            4 : 
    7256            4 :         let mut keyspace = KeySpaceAccum::new();
    7257            4 : 
    7258            4 :         let cancel = CancellationToken::new();
    7259            4 : 
    7260            4 :         // Track when each page was last modified. Used to assert that
    7261            4 :         // a read sees the latest page version.
    7262            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7263            4 : 
    7264            4 :         let mut lsn = Lsn(0x10);
    7265            4 :         #[allow(clippy::needless_range_loop)]
    7266         4004 :         for blknum in 0..NUM_KEYS {
    7267         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7268         4000 :             test_key.field6 = blknum as u32;
    7269         4000 :             let mut writer = tline.writer().await;
    7270         4000 :             writer
    7271         4000 :                 .put(
    7272         4000 :                     test_key,
    7273         4000 :                     lsn,
    7274         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7275         4000 :                     &ctx,
    7276         4000 :                 )
    7277         4000 :                 .await?;
    7278         4000 :             writer.finish_write(lsn);
    7279         4000 :             updated[blknum] = lsn;
    7280         4000 :             drop(writer);
    7281         4000 : 
    7282         4000 :             keyspace.add_key(test_key);
    7283            4 :         }
    7284            4 : 
    7285          204 :         for _ in 0..50 {
    7286          200 :             let new_tline_id = TimelineId::generate();
    7287          200 :             tenant
    7288          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7289          200 :                 .await?;
    7290          200 :             tline = tenant
    7291          200 :                 .get_timeline(new_tline_id, true)
    7292          200 :                 .expect("Should have the branched timeline");
    7293            4 : 
    7294       200200 :             for _ in 0..NUM_KEYS {
    7295       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7296       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7297       200000 :                 test_key.field6 = blknum as u32;
    7298       200000 :                 let mut writer = tline.writer().await;
    7299       200000 :                 writer
    7300       200000 :                     .put(
    7301       200000 :                         test_key,
    7302       200000 :                         lsn,
    7303       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7304       200000 :                         &ctx,
    7305       200000 :                     )
    7306       200000 :                     .await?;
    7307       200000 :                 println!("updating {} at {}", blknum, lsn);
    7308       200000 :                 writer.finish_write(lsn);
    7309       200000 :                 drop(writer);
    7310       200000 :                 updated[blknum] = lsn;
    7311            4 :             }
    7312            4 : 
    7313            4 :             // Read all the blocks
    7314       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7315       200000 :                 test_key.field6 = blknum as u32;
    7316       200000 :                 assert_eq!(
    7317       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7318       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7319            4 :                 );
    7320            4 :             }
    7321            4 : 
    7322            4 :             // Perform a cycle of flush, compact, and GC
    7323          200 :             tline.freeze_and_flush().await?;
    7324          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7325          200 :             tenant
    7326          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7327          200 :                 .await?;
    7328            4 :         }
    7329            4 : 
    7330            4 :         Ok(())
    7331            4 :     }
    7332              : 
    7333              :     #[tokio::test]
    7334            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7335            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7336            4 :             .await?
    7337            4 :             .load()
    7338            4 :             .await;
    7339            4 :         let mut tline = tenant
    7340            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7341            4 :             .await?;
    7342            4 : 
    7343            4 :         const NUM_KEYS: usize = 100;
    7344            4 :         const NUM_TLINES: usize = 50;
    7345            4 : 
    7346            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7347            4 :         // Track page mutation lsns across different timelines.
    7348            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7349            4 : 
    7350            4 :         let mut lsn = Lsn(0x10);
    7351            4 : 
    7352            4 :         #[allow(clippy::needless_range_loop)]
    7353          204 :         for idx in 0..NUM_TLINES {
    7354          200 :             let new_tline_id = TimelineId::generate();
    7355          200 :             tenant
    7356          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7357          200 :                 .await?;
    7358          200 :             tline = tenant
    7359          200 :                 .get_timeline(new_tline_id, true)
    7360          200 :                 .expect("Should have the branched timeline");
    7361            4 : 
    7362        20200 :             for _ in 0..NUM_KEYS {
    7363        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7364        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7365        20000 :                 test_key.field6 = blknum as u32;
    7366        20000 :                 let mut writer = tline.writer().await;
    7367        20000 :                 writer
    7368        20000 :                     .put(
    7369        20000 :                         test_key,
    7370        20000 :                         lsn,
    7371        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7372        20000 :                         &ctx,
    7373        20000 :                     )
    7374        20000 :                     .await?;
    7375        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7376        20000 :                 writer.finish_write(lsn);
    7377        20000 :                 drop(writer);
    7378        20000 :                 updated[idx][blknum] = lsn;
    7379            4 :             }
    7380            4 :         }
    7381            4 : 
    7382            4 :         // Read pages from leaf timeline across all ancestors.
    7383          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7384        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7385            4 :                 // Skip empty mutations.
    7386        20000 :                 if lsn.0 == 0 {
    7387         7343 :                     continue;
    7388        12657 :                 }
    7389        12657 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7390        12657 :                 test_key.field6 = blknum as u32;
    7391        12657 :                 assert_eq!(
    7392        12657 :                     tline.get(test_key, *lsn, &ctx).await?,
    7393        12657 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7394            4 :                 );
    7395            4 :             }
    7396            4 :         }
    7397            4 :         Ok(())
    7398            4 :     }
    7399              : 
    7400              :     #[tokio::test]
    7401            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7402            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7403            4 :             .await?
    7404            4 :             .load()
    7405            4 :             .await;
    7406            4 : 
    7407            4 :         let initdb_lsn = Lsn(0x20);
    7408            4 :         let utline = tenant
    7409            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7410            4 :             .await?;
    7411            4 :         let tline = utline.raw_timeline().unwrap();
    7412            4 : 
    7413            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7414            4 :         tline.maybe_spawn_flush_loop();
    7415            4 : 
    7416            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7417            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7418            4 :         // Except if you `put` at `initdb_lsn`.
    7419            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7420            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7421            4 :         // Let's make sure the test timeline can handle that case.
    7422            4 :         {
    7423            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7424            4 :             assert_eq!(
    7425            4 :                 timeline::FlushLoopState::Running {
    7426            4 :                     expect_initdb_optimization: false,
    7427            4 :                     initdb_optimization_count: 0,
    7428            4 :                 },
    7429            4 :                 *state
    7430            4 :             );
    7431            4 :             *state = timeline::FlushLoopState::Running {
    7432            4 :                 expect_initdb_optimization: true,
    7433            4 :                 initdb_optimization_count: 0,
    7434            4 :             };
    7435            4 :         }
    7436            4 : 
    7437            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7438            4 :         // As explained above, the optimization requires some keys to be present.
    7439            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7440            4 :         // This is what `create_test_timeline` does, by the way.
    7441            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7442            4 :         modification
    7443            4 :             .init_empty_test_timeline()
    7444            4 :             .context("init_empty_test_timeline")?;
    7445            4 :         modification
    7446            4 :             .commit(&ctx)
    7447            4 :             .await
    7448            4 :             .context("commit init_empty_test_timeline modification")?;
    7449            4 : 
    7450            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7451            4 :         tline.freeze_and_flush().await?;
    7452            4 : 
    7453            4 :         // assert freeze_and_flush exercised the initdb optimization
    7454            4 :         {
    7455            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7456            4 :             let timeline::FlushLoopState::Running {
    7457            4 :                 expect_initdb_optimization,
    7458            4 :                 initdb_optimization_count,
    7459            4 :             } = *state
    7460            4 :             else {
    7461            4 :                 panic!("unexpected state: {:?}", *state);
    7462            4 :             };
    7463            4 :             assert!(expect_initdb_optimization);
    7464            4 :             assert!(initdb_optimization_count > 0);
    7465            4 :         }
    7466            4 :         Ok(())
    7467            4 :     }
    7468              : 
    7469              :     #[tokio::test]
    7470            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7471            4 :         let name = "test_create_guard_crash";
    7472            4 :         let harness = TenantHarness::create(name).await?;
    7473            4 :         {
    7474            4 :             let (tenant, ctx) = harness.load().await;
    7475            4 :             let tline = tenant
    7476            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7477            4 :                 .await?;
    7478            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7479            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7480            4 :             raw_tline
    7481            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7482            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))
    7483            4 :                 .await;
    7484            4 :             std::mem::forget(tline);
    7485            4 :         }
    7486            4 : 
    7487            4 :         let (tenant, _) = harness.load().await;
    7488            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7489            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7490            4 :             Err(e) => {
    7491            4 :                 assert_eq!(
    7492            4 :                     e,
    7493            4 :                     GetTimelineError::NotFound {
    7494            4 :                         tenant_id: tenant.tenant_shard_id,
    7495            4 :                         timeline_id: TIMELINE_ID,
    7496            4 :                     }
    7497            4 :                 )
    7498            4 :             }
    7499            4 :         }
    7500            4 : 
    7501            4 :         assert!(!harness
    7502            4 :             .conf
    7503            4 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7504            4 :             .exists());
    7505            4 : 
    7506            4 :         Ok(())
    7507            4 :     }
    7508              : 
    7509              :     #[tokio::test]
    7510            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7511            4 :         let names_algorithms = [
    7512            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7513            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7514            4 :         ];
    7515           12 :         for (name, algorithm) in names_algorithms {
    7516            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7517            4 :         }
    7518            4 :         Ok(())
    7519            4 :     }
    7520              : 
    7521            8 :     async fn test_read_at_max_lsn_algorithm(
    7522            8 :         name: &'static str,
    7523            8 :         compaction_algorithm: CompactionAlgorithm,
    7524            8 :     ) -> anyhow::Result<()> {
    7525            8 :         let mut harness = TenantHarness::create(name).await?;
    7526            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7527            8 :             kind: compaction_algorithm,
    7528            8 :         };
    7529            8 :         let (tenant, ctx) = harness.load().await;
    7530            8 :         let tline = tenant
    7531            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7532            8 :             .await?;
    7533              : 
    7534            8 :         let lsn = Lsn(0x10);
    7535            8 :         let compact = false;
    7536            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7537              : 
    7538            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7539            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7540              : 
    7541            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7542            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7543              : 
    7544            8 :         Ok(())
    7545            8 :     }
    7546              : 
    7547              :     #[tokio::test]
    7548            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7549            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7550            4 :         let (tenant, ctx) = harness.load().await;
    7551            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7552            4 :         let tline = tenant
    7553            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7554            4 :             .await?;
    7555            4 : 
    7556            4 :         const NUM_KEYS: usize = 1000;
    7557            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7558            4 : 
    7559            4 :         let cancel = CancellationToken::new();
    7560            4 : 
    7561            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7562            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7563            4 :         let mut test_key = base_key;
    7564            4 : 
    7565            4 :         // Track when each page was last modified. Used to assert that
    7566            4 :         // a read sees the latest page version.
    7567            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7568            4 : 
    7569            4 :         let mut lsn = Lsn(0x10);
    7570            4 :         #[allow(clippy::needless_range_loop)]
    7571         4004 :         for blknum in 0..NUM_KEYS {
    7572         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7573         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7574         4000 :             let mut writer = tline.writer().await;
    7575         4000 :             writer
    7576         4000 :                 .put(
    7577         4000 :                     test_key,
    7578         4000 :                     lsn,
    7579         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7580         4000 :                     &ctx,
    7581         4000 :                 )
    7582         4000 :                 .await?;
    7583         4000 :             writer.finish_write(lsn);
    7584         4000 :             updated[blknum] = lsn;
    7585         4000 :             drop(writer);
    7586            4 :         }
    7587            4 : 
    7588            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7589            4 : 
    7590           48 :         for iter in 0..=10 {
    7591            4 :             // Read all the blocks
    7592        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7593        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7594        44000 :                 assert_eq!(
    7595        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7596        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7597            4 :                 );
    7598            4 :             }
    7599            4 : 
    7600           44 :             let mut cnt = 0;
    7601        44000 :             for (key, value) in tline
    7602           44 :                 .get_vectored_impl(
    7603           44 :                     keyspace.clone(),
    7604           44 :                     lsn,
    7605           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7606           44 :                     &ctx,
    7607           44 :                 )
    7608           44 :                 .await?
    7609            4 :             {
    7610        44000 :                 let blknum = key.field6 as usize;
    7611        44000 :                 let value = value?;
    7612        44000 :                 assert!(blknum % STEP == 0);
    7613        44000 :                 let blknum = blknum / STEP;
    7614        44000 :                 assert_eq!(
    7615        44000 :                     value,
    7616        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7617        44000 :                 );
    7618        44000 :                 cnt += 1;
    7619            4 :             }
    7620            4 : 
    7621           44 :             assert_eq!(cnt, NUM_KEYS);
    7622            4 : 
    7623        44044 :             for _ in 0..NUM_KEYS {
    7624        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7625        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7626        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7627        44000 :                 let mut writer = tline.writer().await;
    7628        44000 :                 writer
    7629        44000 :                     .put(
    7630        44000 :                         test_key,
    7631        44000 :                         lsn,
    7632        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7633        44000 :                         &ctx,
    7634        44000 :                     )
    7635        44000 :                     .await?;
    7636        44000 :                 writer.finish_write(lsn);
    7637        44000 :                 drop(writer);
    7638        44000 :                 updated[blknum] = lsn;
    7639            4 :             }
    7640            4 : 
    7641            4 :             // Perform two cycles of flush, compact, and GC
    7642          132 :             for round in 0..2 {
    7643           88 :                 tline.freeze_and_flush().await?;
    7644           88 :                 tline
    7645           88 :                     .compact(
    7646           88 :                         &cancel,
    7647           88 :                         if iter % 5 == 0 && round == 0 {
    7648           12 :                             let mut flags = EnumSet::new();
    7649           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7650           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7651           12 :                             flags
    7652            4 :                         } else {
    7653           76 :                             EnumSet::empty()
    7654            4 :                         },
    7655           88 :                         &ctx,
    7656           88 :                     )
    7657           88 :                     .await?;
    7658           88 :                 tenant
    7659           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7660           88 :                     .await?;
    7661            4 :             }
    7662            4 :         }
    7663            4 : 
    7664            4 :         Ok(())
    7665            4 :     }
    7666              : 
    7667              :     #[tokio::test]
    7668            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7669            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7670            4 :         let (tenant, ctx) = harness.load().await;
    7671            4 :         let tline = tenant
    7672            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7673            4 :             .await?;
    7674            4 : 
    7675            4 :         let cancel = CancellationToken::new();
    7676            4 : 
    7677            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7678            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7679            4 :         let test_key = base_key;
    7680            4 :         let mut lsn = Lsn(0x10);
    7681            4 : 
    7682           84 :         for _ in 0..20 {
    7683           80 :             lsn = Lsn(lsn.0 + 0x10);
    7684           80 :             let mut writer = tline.writer().await;
    7685           80 :             writer
    7686           80 :                 .put(
    7687           80 :                     test_key,
    7688           80 :                     lsn,
    7689           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7690           80 :                     &ctx,
    7691           80 :                 )
    7692           80 :                 .await?;
    7693           80 :             writer.finish_write(lsn);
    7694           80 :             drop(writer);
    7695           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7696            4 :         }
    7697            4 : 
    7698            4 :         let before_num_l0_delta_files =
    7699            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7700            4 : 
    7701            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7702            4 : 
    7703            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7704            4 : 
    7705            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}");
    7706            4 : 
    7707            4 :         assert_eq!(
    7708            4 :             tline.get(test_key, lsn, &ctx).await?,
    7709            4 :             test_img(&format!("{} at {}", 0, lsn))
    7710            4 :         );
    7711            4 : 
    7712            4 :         Ok(())
    7713            4 :     }
    7714              : 
    7715              :     #[tokio::test]
    7716            4 :     async fn test_aux_file_e2e() {
    7717            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7718            4 : 
    7719            4 :         let (tenant, ctx) = harness.load().await;
    7720            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7721            4 : 
    7722            4 :         let mut lsn = Lsn(0x08);
    7723            4 : 
    7724            4 :         let tline: Arc<Timeline> = tenant
    7725            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7726            4 :             .await
    7727            4 :             .unwrap();
    7728            4 : 
    7729            4 :         {
    7730            4 :             lsn += 8;
    7731            4 :             let mut modification = tline.begin_modification(lsn);
    7732            4 :             modification
    7733            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7734            4 :                 .await
    7735            4 :                 .unwrap();
    7736            4 :             modification.commit(&ctx).await.unwrap();
    7737            4 :         }
    7738            4 : 
    7739            4 :         // we can read everything from the storage
    7740            4 :         let files = tline
    7741            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7742            4 :             .await
    7743            4 :             .unwrap();
    7744            4 :         assert_eq!(
    7745            4 :             files.get("pg_logical/mappings/test1"),
    7746            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7747            4 :         );
    7748            4 : 
    7749            4 :         {
    7750            4 :             lsn += 8;
    7751            4 :             let mut modification = tline.begin_modification(lsn);
    7752            4 :             modification
    7753            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7754            4 :                 .await
    7755            4 :                 .unwrap();
    7756            4 :             modification.commit(&ctx).await.unwrap();
    7757            4 :         }
    7758            4 : 
    7759            4 :         let files = tline
    7760            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7761            4 :             .await
    7762            4 :             .unwrap();
    7763            4 :         assert_eq!(
    7764            4 :             files.get("pg_logical/mappings/test2"),
    7765            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7766            4 :         );
    7767            4 : 
    7768            4 :         let child = tenant
    7769            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7770            4 :             .await
    7771            4 :             .unwrap();
    7772            4 : 
    7773            4 :         let files = child
    7774            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7775            4 :             .await
    7776            4 :             .unwrap();
    7777            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7778            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7779            4 :     }
    7780              : 
    7781              :     #[tokio::test]
    7782            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7783            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7784            4 :         let (tenant, ctx) = harness.load().await;
    7785            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7786            4 :         let tline = tenant
    7787            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7788            4 :             .await?;
    7789            4 : 
    7790            4 :         const NUM_KEYS: usize = 1000;
    7791            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7792            4 : 
    7793            4 :         let cancel = CancellationToken::new();
    7794            4 : 
    7795            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7796            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7797            4 :         let mut test_key = base_key;
    7798            4 :         let mut lsn = Lsn(0x10);
    7799            4 : 
    7800           16 :         async fn scan_with_statistics(
    7801           16 :             tline: &Timeline,
    7802           16 :             keyspace: &KeySpace,
    7803           16 :             lsn: Lsn,
    7804           16 :             ctx: &RequestContext,
    7805           16 :             io_concurrency: IoConcurrency,
    7806           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7807           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7808           16 :             let res = tline
    7809           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7810           16 :                 .await?;
    7811           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7812           16 :         }
    7813            4 : 
    7814            4 :         #[allow(clippy::needless_range_loop)]
    7815         4004 :         for blknum in 0..NUM_KEYS {
    7816         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7817         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7818         4000 :             let mut writer = tline.writer().await;
    7819         4000 :             writer
    7820         4000 :                 .put(
    7821         4000 :                     test_key,
    7822         4000 :                     lsn,
    7823         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7824         4000 :                     &ctx,
    7825         4000 :                 )
    7826         4000 :                 .await?;
    7827         4000 :             writer.finish_write(lsn);
    7828         4000 :             drop(writer);
    7829            4 :         }
    7830            4 : 
    7831            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7832            4 : 
    7833           44 :         for iter in 1..=10 {
    7834        40040 :             for _ in 0..NUM_KEYS {
    7835        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7836        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7837        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7838        40000 :                 let mut writer = tline.writer().await;
    7839        40000 :                 writer
    7840        40000 :                     .put(
    7841        40000 :                         test_key,
    7842        40000 :                         lsn,
    7843        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7844        40000 :                         &ctx,
    7845        40000 :                     )
    7846        40000 :                     .await?;
    7847        40000 :                 writer.finish_write(lsn);
    7848        40000 :                 drop(writer);
    7849            4 :             }
    7850            4 : 
    7851           40 :             tline.freeze_and_flush().await?;
    7852            4 : 
    7853           40 :             if iter % 5 == 0 {
    7854            8 :                 let (_, before_delta_file_accessed) =
    7855            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7856            8 :                         .await?;
    7857            8 :                 tline
    7858            8 :                     .compact(
    7859            8 :                         &cancel,
    7860            8 :                         {
    7861            8 :                             let mut flags = EnumSet::new();
    7862            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7863            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7864            8 :                             flags
    7865            8 :                         },
    7866            8 :                         &ctx,
    7867            8 :                     )
    7868            8 :                     .await?;
    7869            8 :                 let (_, after_delta_file_accessed) =
    7870            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7871            8 :                         .await?;
    7872            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}");
    7873            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.
    7874            8 :                 assert!(
    7875            8 :                     after_delta_file_accessed <= 2,
    7876            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7877            4 :                 );
    7878           32 :             }
    7879            4 :         }
    7880            4 : 
    7881            4 :         Ok(())
    7882            4 :     }
    7883              : 
    7884              :     #[tokio::test]
    7885            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7886            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7887            4 :         let (tenant, ctx) = harness.load().await;
    7888            4 : 
    7889            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7890            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7891            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7892            4 : 
    7893            4 :         let tline = tenant
    7894            4 :             .create_test_timeline_with_layers(
    7895            4 :                 TIMELINE_ID,
    7896            4 :                 Lsn(0x10),
    7897            4 :                 DEFAULT_PG_VERSION,
    7898            4 :                 &ctx,
    7899            4 :                 Vec::new(), // delta layers
    7900            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7901            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
    7902            4 :             )
    7903            4 :             .await?;
    7904            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7905            4 : 
    7906            4 :         let child = tenant
    7907            4 :             .branch_timeline_test_with_layers(
    7908            4 :                 &tline,
    7909            4 :                 NEW_TIMELINE_ID,
    7910            4 :                 Some(Lsn(0x20)),
    7911            4 :                 &ctx,
    7912            4 :                 Vec::new(), // delta layers
    7913            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7914            4 :                 Lsn(0x30),
    7915            4 :             )
    7916            4 :             .await
    7917            4 :             .unwrap();
    7918            4 : 
    7919            4 :         let lsn = Lsn(0x30);
    7920            4 : 
    7921            4 :         // test vectored get on parent timeline
    7922            4 :         assert_eq!(
    7923            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7924            4 :             Some(test_img("data key 1"))
    7925            4 :         );
    7926            4 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7927            4 :             .await
    7928            4 :             .unwrap_err()
    7929            4 :             .is_missing_key_error());
    7930            4 :         assert!(
    7931            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7932            4 :                 .await
    7933            4 :                 .unwrap_err()
    7934            4 :                 .is_missing_key_error()
    7935            4 :         );
    7936            4 : 
    7937            4 :         // test vectored get on child timeline
    7938            4 :         assert_eq!(
    7939            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7940            4 :             Some(test_img("data key 1"))
    7941            4 :         );
    7942            4 :         assert_eq!(
    7943            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7944            4 :             Some(test_img("data key 2"))
    7945            4 :         );
    7946            4 :         assert!(
    7947            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7948            4 :                 .await
    7949            4 :                 .unwrap_err()
    7950            4 :                 .is_missing_key_error()
    7951            4 :         );
    7952            4 : 
    7953            4 :         Ok(())
    7954            4 :     }
    7955              : 
    7956              :     #[tokio::test]
    7957            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7958            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7959            4 :         let (tenant, ctx) = harness.load().await;
    7960            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7961            4 : 
    7962            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7963            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7964            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7965            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7966            4 : 
    7967            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    7968            4 :         let base_inherited_key_child =
    7969            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    7970            4 :         let base_inherited_key_nonexist =
    7971            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    7972            4 :         let base_inherited_key_overwrite =
    7973            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    7974            4 : 
    7975            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7976            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    7977            4 : 
    7978            4 :         let tline = tenant
    7979            4 :             .create_test_timeline_with_layers(
    7980            4 :                 TIMELINE_ID,
    7981            4 :                 Lsn(0x10),
    7982            4 :                 DEFAULT_PG_VERSION,
    7983            4 :                 &ctx,
    7984            4 :                 Vec::new(), // delta layers
    7985            4 :                 vec![(
    7986            4 :                     Lsn(0x20),
    7987            4 :                     vec![
    7988            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    7989            4 :                         (
    7990            4 :                             base_inherited_key_overwrite,
    7991            4 :                             test_img("metadata key overwrite 1a"),
    7992            4 :                         ),
    7993            4 :                         (base_key, test_img("metadata key 1")),
    7994            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7995            4 :                     ],
    7996            4 :                 )], // image layers
    7997            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
    7998            4 :             )
    7999            4 :             .await?;
    8000            4 : 
    8001            4 :         let child = tenant
    8002            4 :             .branch_timeline_test_with_layers(
    8003            4 :                 &tline,
    8004            4 :                 NEW_TIMELINE_ID,
    8005            4 :                 Some(Lsn(0x20)),
    8006            4 :                 &ctx,
    8007            4 :                 Vec::new(), // delta layers
    8008            4 :                 vec![(
    8009            4 :                     Lsn(0x30),
    8010            4 :                     vec![
    8011            4 :                         (
    8012            4 :                             base_inherited_key_child,
    8013            4 :                             test_img("metadata inherited key 2"),
    8014            4 :                         ),
    8015            4 :                         (
    8016            4 :                             base_inherited_key_overwrite,
    8017            4 :                             test_img("metadata key overwrite 2a"),
    8018            4 :                         ),
    8019            4 :                         (base_key_child, test_img("metadata key 2")),
    8020            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8021            4 :                     ],
    8022            4 :                 )], // image layers
    8023            4 :                 Lsn(0x30),
    8024            4 :             )
    8025            4 :             .await
    8026            4 :             .unwrap();
    8027            4 : 
    8028            4 :         let lsn = Lsn(0x30);
    8029            4 : 
    8030            4 :         // test vectored get on parent timeline
    8031            4 :         assert_eq!(
    8032            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8033            4 :             Some(test_img("metadata key 1"))
    8034            4 :         );
    8035            4 :         assert_eq!(
    8036            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8037            4 :             None
    8038            4 :         );
    8039            4 :         assert_eq!(
    8040            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8041            4 :             None
    8042            4 :         );
    8043            4 :         assert_eq!(
    8044            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8045            4 :             Some(test_img("metadata key overwrite 1b"))
    8046            4 :         );
    8047            4 :         assert_eq!(
    8048            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8049            4 :             Some(test_img("metadata inherited key 1"))
    8050            4 :         );
    8051            4 :         assert_eq!(
    8052            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8053            4 :             None
    8054            4 :         );
    8055            4 :         assert_eq!(
    8056            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8057            4 :             None
    8058            4 :         );
    8059            4 :         assert_eq!(
    8060            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8061            4 :             Some(test_img("metadata key overwrite 1a"))
    8062            4 :         );
    8063            4 : 
    8064            4 :         // test vectored get on child timeline
    8065            4 :         assert_eq!(
    8066            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8067            4 :             None
    8068            4 :         );
    8069            4 :         assert_eq!(
    8070            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8071            4 :             Some(test_img("metadata key 2"))
    8072            4 :         );
    8073            4 :         assert_eq!(
    8074            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8075            4 :             None
    8076            4 :         );
    8077            4 :         assert_eq!(
    8078            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8079            4 :             Some(test_img("metadata inherited key 1"))
    8080            4 :         );
    8081            4 :         assert_eq!(
    8082            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8083            4 :             Some(test_img("metadata inherited key 2"))
    8084            4 :         );
    8085            4 :         assert_eq!(
    8086            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8087            4 :             None
    8088            4 :         );
    8089            4 :         assert_eq!(
    8090            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8091            4 :             Some(test_img("metadata key overwrite 2b"))
    8092            4 :         );
    8093            4 :         assert_eq!(
    8094            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8095            4 :             Some(test_img("metadata key overwrite 2a"))
    8096            4 :         );
    8097            4 : 
    8098            4 :         // test vectored scan on parent timeline
    8099            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8100            4 :         let res = tline
    8101            4 :             .get_vectored_impl(
    8102            4 :                 KeySpace::single(Key::metadata_key_range()),
    8103            4 :                 lsn,
    8104            4 :                 &mut reconstruct_state,
    8105            4 :                 &ctx,
    8106            4 :             )
    8107            4 :             .await?;
    8108            4 : 
    8109            4 :         assert_eq!(
    8110            4 :             res.into_iter()
    8111           16 :                 .map(|(k, v)| (k, v.unwrap()))
    8112            4 :                 .collect::<Vec<_>>(),
    8113            4 :             vec![
    8114            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8115            4 :                 (
    8116            4 :                     base_inherited_key_overwrite,
    8117            4 :                     test_img("metadata key overwrite 1a")
    8118            4 :                 ),
    8119            4 :                 (base_key, test_img("metadata key 1")),
    8120            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8121            4 :             ]
    8122            4 :         );
    8123            4 : 
    8124            4 :         // test vectored scan on child timeline
    8125            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8126            4 :         let res = child
    8127            4 :             .get_vectored_impl(
    8128            4 :                 KeySpace::single(Key::metadata_key_range()),
    8129            4 :                 lsn,
    8130            4 :                 &mut reconstruct_state,
    8131            4 :                 &ctx,
    8132            4 :             )
    8133            4 :             .await?;
    8134            4 : 
    8135            4 :         assert_eq!(
    8136            4 :             res.into_iter()
    8137           20 :                 .map(|(k, v)| (k, v.unwrap()))
    8138            4 :                 .collect::<Vec<_>>(),
    8139            4 :             vec![
    8140            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8141            4 :                 (
    8142            4 :                     base_inherited_key_child,
    8143            4 :                     test_img("metadata inherited key 2")
    8144            4 :                 ),
    8145            4 :                 (
    8146            4 :                     base_inherited_key_overwrite,
    8147            4 :                     test_img("metadata key overwrite 2a")
    8148            4 :                 ),
    8149            4 :                 (base_key_child, test_img("metadata key 2")),
    8150            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8151            4 :             ]
    8152            4 :         );
    8153            4 : 
    8154            4 :         Ok(())
    8155            4 :     }
    8156              : 
    8157          112 :     async fn get_vectored_impl_wrapper(
    8158          112 :         tline: &Arc<Timeline>,
    8159          112 :         key: Key,
    8160          112 :         lsn: Lsn,
    8161          112 :         ctx: &RequestContext,
    8162          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8163          112 :         let io_concurrency =
    8164          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8165          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8166          112 :         let mut res = tline
    8167          112 :             .get_vectored_impl(
    8168          112 :                 KeySpace::single(key..key.next()),
    8169          112 :                 lsn,
    8170          112 :                 &mut reconstruct_state,
    8171          112 :                 ctx,
    8172          112 :             )
    8173          112 :             .await?;
    8174          100 :         Ok(res.pop_last().map(|(k, v)| {
    8175           64 :             assert_eq!(k, key);
    8176           64 :             v.unwrap()
    8177          100 :         }))
    8178          112 :     }
    8179              : 
    8180              :     #[tokio::test]
    8181            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8182            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8183            4 :         let (tenant, ctx) = harness.load().await;
    8184            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8185            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8186            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8187            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8188            4 : 
    8189            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8190            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8191            4 :         // Lsn 0x20 key1+key2 tomestones
    8192            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8193            4 :         let tline = tenant
    8194            4 :             .create_test_timeline_with_layers(
    8195            4 :                 TIMELINE_ID,
    8196            4 :                 Lsn(0x10),
    8197            4 :                 DEFAULT_PG_VERSION,
    8198            4 :                 &ctx,
    8199            4 :                 // delta layers
    8200            4 :                 vec![
    8201            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8202            4 :                         Lsn(0x10)..Lsn(0x20),
    8203            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8204            4 :                     ),
    8205            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8206            4 :                         Lsn(0x20)..Lsn(0x30),
    8207            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8208            4 :                     ),
    8209            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8210            4 :                         Lsn(0x20)..Lsn(0x30),
    8211            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8212            4 :                     ),
    8213            4 :                 ],
    8214            4 :                 // image layers
    8215            4 :                 vec![
    8216            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8217            4 :                     (
    8218            4 :                         Lsn(0x30),
    8219            4 :                         vec![
    8220            4 :                             (key0, test_img("metadata key 0")),
    8221            4 :                             (key3, test_img("metadata key 3")),
    8222            4 :                         ],
    8223            4 :                     ),
    8224            4 :                 ],
    8225            4 :                 Lsn(0x30),
    8226            4 :             )
    8227            4 :             .await?;
    8228            4 : 
    8229            4 :         let lsn = Lsn(0x30);
    8230            4 :         let old_lsn = Lsn(0x20);
    8231            4 : 
    8232            4 :         assert_eq!(
    8233            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8234            4 :             Some(test_img("metadata key 0"))
    8235            4 :         );
    8236            4 :         assert_eq!(
    8237            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8238            4 :             None,
    8239            4 :         );
    8240            4 :         assert_eq!(
    8241            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8242            4 :             None,
    8243            4 :         );
    8244            4 :         assert_eq!(
    8245            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8246            4 :             Some(Bytes::new()),
    8247            4 :         );
    8248            4 :         assert_eq!(
    8249            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8250            4 :             Some(Bytes::new()),
    8251            4 :         );
    8252            4 :         assert_eq!(
    8253            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8254            4 :             Some(test_img("metadata key 3"))
    8255            4 :         );
    8256            4 : 
    8257            4 :         Ok(())
    8258            4 :     }
    8259              : 
    8260              :     #[tokio::test]
    8261            4 :     async fn test_metadata_tombstone_image_creation() {
    8262            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8263            4 :             .await
    8264            4 :             .unwrap();
    8265            4 :         let (tenant, ctx) = harness.load().await;
    8266            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8267            4 : 
    8268            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8269            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8270            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8271            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8272            4 : 
    8273            4 :         let tline = tenant
    8274            4 :             .create_test_timeline_with_layers(
    8275            4 :                 TIMELINE_ID,
    8276            4 :                 Lsn(0x10),
    8277            4 :                 DEFAULT_PG_VERSION,
    8278            4 :                 &ctx,
    8279            4 :                 // delta layers
    8280            4 :                 vec![
    8281            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8282            4 :                         Lsn(0x10)..Lsn(0x20),
    8283            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8284            4 :                     ),
    8285            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8286            4 :                         Lsn(0x20)..Lsn(0x30),
    8287            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8288            4 :                     ),
    8289            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8290            4 :                         Lsn(0x20)..Lsn(0x30),
    8291            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8292            4 :                     ),
    8293            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8294            4 :                         Lsn(0x30)..Lsn(0x40),
    8295            4 :                         vec![
    8296            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8297            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8298            4 :                         ],
    8299            4 :                     ),
    8300            4 :                 ],
    8301            4 :                 // image layers
    8302            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8303            4 :                 Lsn(0x40),
    8304            4 :             )
    8305            4 :             .await
    8306            4 :             .unwrap();
    8307            4 : 
    8308            4 :         let cancel = CancellationToken::new();
    8309            4 : 
    8310            4 :         tline
    8311            4 :             .compact(
    8312            4 :                 &cancel,
    8313            4 :                 {
    8314            4 :                     let mut flags = EnumSet::new();
    8315            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8316            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8317            4 :                     flags
    8318            4 :                 },
    8319            4 :                 &ctx,
    8320            4 :             )
    8321            4 :             .await
    8322            4 :             .unwrap();
    8323            4 : 
    8324            4 :         // Image layers are created at last_record_lsn
    8325            4 :         let images = tline
    8326            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8327            4 :             .await
    8328            4 :             .unwrap()
    8329            4 :             .into_iter()
    8330           36 :             .filter(|(k, _)| k.is_metadata_key())
    8331            4 :             .collect::<Vec<_>>();
    8332            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8333            4 :     }
    8334              : 
    8335              :     #[tokio::test]
    8336            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8337            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8338            4 :             .await
    8339            4 :             .unwrap();
    8340            4 :         let (tenant, ctx) = harness.load().await;
    8341            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8342            4 : 
    8343            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8344            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8345            4 : 
    8346            4 :         let tline = tenant
    8347            4 :             .create_test_timeline_with_layers(
    8348            4 :                 TIMELINE_ID,
    8349            4 :                 Lsn(0x10),
    8350            4 :                 DEFAULT_PG_VERSION,
    8351            4 :                 &ctx,
    8352            4 :                 // delta layers
    8353            4 :                 vec![
    8354            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8355            4 :                         Lsn(0x10)..Lsn(0x20),
    8356            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8357            4 :                     ),
    8358            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8359            4 :                         Lsn(0x20)..Lsn(0x30),
    8360            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8361            4 :                     ),
    8362            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8363            4 :                         Lsn(0x20)..Lsn(0x30),
    8364            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8365            4 :                     ),
    8366            4 :                 ],
    8367            4 :                 // image layers
    8368            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8369            4 :                 Lsn(0x30),
    8370            4 :             )
    8371            4 :             .await
    8372            4 :             .unwrap();
    8373            4 : 
    8374            4 :         let cancel = CancellationToken::new();
    8375            4 : 
    8376            4 :         tline
    8377            4 :             .compact(
    8378            4 :                 &cancel,
    8379            4 :                 {
    8380            4 :                     let mut flags = EnumSet::new();
    8381            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8382            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8383            4 :                     flags
    8384            4 :                 },
    8385            4 :                 &ctx,
    8386            4 :             )
    8387            4 :             .await
    8388            4 :             .unwrap();
    8389            4 : 
    8390            4 :         // Image layers are created at last_record_lsn
    8391            4 :         let images = tline
    8392            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8393            4 :             .await
    8394            4 :             .unwrap()
    8395            4 :             .into_iter()
    8396           28 :             .filter(|(k, _)| k.is_metadata_key())
    8397            4 :             .collect::<Vec<_>>();
    8398            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8399            4 :     }
    8400              : 
    8401              :     #[tokio::test]
    8402            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8403            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8404            4 :         let (tenant, ctx) = harness.load().await;
    8405            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8406            4 : 
    8407          204 :         fn get_key(id: u32) -> Key {
    8408          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8409          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8410          204 :             key.field6 = id;
    8411          204 :             key
    8412          204 :         }
    8413            4 : 
    8414            4 :         // We create
    8415            4 :         // - one bottom-most image layer,
    8416            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8417            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8418            4 :         // - a delta layer D3 above the horizon.
    8419            4 :         //
    8420            4 :         //                             | D3 |
    8421            4 :         //  | D1 |
    8422            4 :         // -|    |-- gc horizon -----------------
    8423            4 :         //  |    |                | D2 |
    8424            4 :         // --------- img layer ------------------
    8425            4 :         //
    8426            4 :         // What we should expact from this compaction is:
    8427            4 :         //                             | D3 |
    8428            4 :         //  | Part of D1 |
    8429            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8430            4 : 
    8431            4 :         // img layer at 0x10
    8432            4 :         let img_layer = (0..10)
    8433           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8434            4 :             .collect_vec();
    8435            4 : 
    8436            4 :         let delta1 = vec![
    8437            4 :             (
    8438            4 :                 get_key(1),
    8439            4 :                 Lsn(0x20),
    8440            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8441            4 :             ),
    8442            4 :             (
    8443            4 :                 get_key(2),
    8444            4 :                 Lsn(0x30),
    8445            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8446            4 :             ),
    8447            4 :             (
    8448            4 :                 get_key(3),
    8449            4 :                 Lsn(0x40),
    8450            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8451            4 :             ),
    8452            4 :         ];
    8453            4 :         let delta2 = vec![
    8454            4 :             (
    8455            4 :                 get_key(5),
    8456            4 :                 Lsn(0x20),
    8457            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8458            4 :             ),
    8459            4 :             (
    8460            4 :                 get_key(6),
    8461            4 :                 Lsn(0x20),
    8462            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8463            4 :             ),
    8464            4 :         ];
    8465            4 :         let delta3 = vec![
    8466            4 :             (
    8467            4 :                 get_key(8),
    8468            4 :                 Lsn(0x48),
    8469            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8470            4 :             ),
    8471            4 :             (
    8472            4 :                 get_key(9),
    8473            4 :                 Lsn(0x48),
    8474            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8475            4 :             ),
    8476            4 :         ];
    8477            4 : 
    8478            4 :         let tline = tenant
    8479            4 :             .create_test_timeline_with_layers(
    8480            4 :                 TIMELINE_ID,
    8481            4 :                 Lsn(0x10),
    8482            4 :                 DEFAULT_PG_VERSION,
    8483            4 :                 &ctx,
    8484            4 :                 vec![
    8485            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8486            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8487            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8488            4 :                 ], // delta layers
    8489            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8490            4 :                 Lsn(0x50),
    8491            4 :             )
    8492            4 :             .await?;
    8493            4 :         {
    8494            4 :             tline
    8495            4 :                 .applied_gc_cutoff_lsn
    8496            4 :                 .lock_for_write()
    8497            4 :                 .store_and_unlock(Lsn(0x30))
    8498            4 :                 .wait()
    8499            4 :                 .await;
    8500            4 :             // Update GC info
    8501            4 :             let mut guard = tline.gc_info.write().unwrap();
    8502            4 :             guard.cutoffs.time = Lsn(0x30);
    8503            4 :             guard.cutoffs.space = Lsn(0x30);
    8504            4 :         }
    8505            4 : 
    8506            4 :         let expected_result = [
    8507            4 :             Bytes::from_static(b"value 0@0x10"),
    8508            4 :             Bytes::from_static(b"value 1@0x20"),
    8509            4 :             Bytes::from_static(b"value 2@0x30"),
    8510            4 :             Bytes::from_static(b"value 3@0x40"),
    8511            4 :             Bytes::from_static(b"value 4@0x10"),
    8512            4 :             Bytes::from_static(b"value 5@0x20"),
    8513            4 :             Bytes::from_static(b"value 6@0x20"),
    8514            4 :             Bytes::from_static(b"value 7@0x10"),
    8515            4 :             Bytes::from_static(b"value 8@0x48"),
    8516            4 :             Bytes::from_static(b"value 9@0x48"),
    8517            4 :         ];
    8518            4 : 
    8519           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8520           40 :             assert_eq!(
    8521           40 :                 tline
    8522           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8523           40 :                     .await
    8524           40 :                     .unwrap(),
    8525            4 :                 expected
    8526            4 :             );
    8527            4 :         }
    8528            4 : 
    8529            4 :         let cancel = CancellationToken::new();
    8530            4 :         tline
    8531            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8532            4 :             .await
    8533            4 :             .unwrap();
    8534            4 : 
    8535           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8536           40 :             assert_eq!(
    8537           40 :                 tline
    8538           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8539           40 :                     .await
    8540           40 :                     .unwrap(),
    8541            4 :                 expected
    8542            4 :             );
    8543            4 :         }
    8544            4 : 
    8545            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8546            4 :         let image_at_gc_horizon = tline
    8547            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8548            4 :             .await
    8549            4 :             .unwrap()
    8550            4 :             .into_iter()
    8551           68 :             .filter(|(k, _)| k.is_metadata_key())
    8552            4 :             .collect::<Vec<_>>();
    8553            4 : 
    8554            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8555            4 :         let expected_result = [
    8556            4 :             Bytes::from_static(b"value 0@0x10"),
    8557            4 :             Bytes::from_static(b"value 1@0x20"),
    8558            4 :             Bytes::from_static(b"value 2@0x30"),
    8559            4 :             Bytes::from_static(b"value 3@0x10"),
    8560            4 :             Bytes::from_static(b"value 4@0x10"),
    8561            4 :             Bytes::from_static(b"value 5@0x20"),
    8562            4 :             Bytes::from_static(b"value 6@0x20"),
    8563            4 :             Bytes::from_static(b"value 7@0x10"),
    8564            4 :             Bytes::from_static(b"value 8@0x10"),
    8565            4 :             Bytes::from_static(b"value 9@0x10"),
    8566            4 :         ];
    8567           44 :         for idx in 0..10 {
    8568           40 :             assert_eq!(
    8569           40 :                 image_at_gc_horizon[idx],
    8570           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8571           40 :             );
    8572            4 :         }
    8573            4 : 
    8574            4 :         // Check if old layers are removed / new layers have the expected LSN
    8575            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8576            4 :         assert_eq!(
    8577            4 :             all_layers,
    8578            4 :             vec![
    8579            4 :                 // Image layer at GC horizon
    8580            4 :                 PersistentLayerKey {
    8581            4 :                     key_range: Key::MIN..Key::MAX,
    8582            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8583            4 :                     is_delta: false
    8584            4 :                 },
    8585            4 :                 // The delta layer below the horizon
    8586            4 :                 PersistentLayerKey {
    8587            4 :                     key_range: get_key(3)..get_key(4),
    8588            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8589            4 :                     is_delta: true
    8590            4 :                 },
    8591            4 :                 // The delta3 layer that should not be picked for the compaction
    8592            4 :                 PersistentLayerKey {
    8593            4 :                     key_range: get_key(8)..get_key(10),
    8594            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8595            4 :                     is_delta: true
    8596            4 :                 }
    8597            4 :             ]
    8598            4 :         );
    8599            4 : 
    8600            4 :         // increase GC horizon and compact again
    8601            4 :         {
    8602            4 :             tline
    8603            4 :                 .applied_gc_cutoff_lsn
    8604            4 :                 .lock_for_write()
    8605            4 :                 .store_and_unlock(Lsn(0x40))
    8606            4 :                 .wait()
    8607            4 :                 .await;
    8608            4 :             // Update GC info
    8609            4 :             let mut guard = tline.gc_info.write().unwrap();
    8610            4 :             guard.cutoffs.time = Lsn(0x40);
    8611            4 :             guard.cutoffs.space = Lsn(0x40);
    8612            4 :         }
    8613            4 :         tline
    8614            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8615            4 :             .await
    8616            4 :             .unwrap();
    8617            4 : 
    8618            4 :         Ok(())
    8619            4 :     }
    8620              : 
    8621              :     #[cfg(feature = "testing")]
    8622              :     #[tokio::test]
    8623            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8624            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8625            4 :         let (tenant, ctx) = harness.load().await;
    8626            4 : 
    8627           48 :         fn get_key(id: u32) -> Key {
    8628           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8629           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8630           48 :             key.field6 = id;
    8631           48 :             key
    8632           48 :         }
    8633            4 : 
    8634            4 :         let delta1 = vec![
    8635            4 :             (
    8636            4 :                 get_key(1),
    8637            4 :                 Lsn(0x20),
    8638            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8639            4 :             ),
    8640            4 :             (
    8641            4 :                 get_key(1),
    8642            4 :                 Lsn(0x30),
    8643            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8644            4 :             ),
    8645            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8646            4 :             (
    8647            4 :                 get_key(2),
    8648            4 :                 Lsn(0x20),
    8649            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8650            4 :             ),
    8651            4 :             (
    8652            4 :                 get_key(2),
    8653            4 :                 Lsn(0x30),
    8654            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8655            4 :             ),
    8656            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8657            4 :             (
    8658            4 :                 get_key(3),
    8659            4 :                 Lsn(0x20),
    8660            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8661            4 :             ),
    8662            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8663            4 :             (
    8664            4 :                 get_key(4),
    8665            4 :                 Lsn(0x20),
    8666            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8667            4 :             ),
    8668            4 :         ];
    8669            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8670            4 : 
    8671            4 :         let tline = tenant
    8672            4 :             .create_test_timeline_with_layers(
    8673            4 :                 TIMELINE_ID,
    8674            4 :                 Lsn(0x10),
    8675            4 :                 DEFAULT_PG_VERSION,
    8676            4 :                 &ctx,
    8677            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8678            4 :                     Lsn(0x10)..Lsn(0x40),
    8679            4 :                     delta1,
    8680            4 :                 )], // delta layers
    8681            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8682            4 :                 Lsn(0x50),
    8683            4 :             )
    8684            4 :             .await?;
    8685            4 : 
    8686            4 :         assert_eq!(
    8687            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8688            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8689            4 :         );
    8690            4 :         assert_eq!(
    8691            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8692            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8693            4 :         );
    8694            4 : 
    8695            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8696            4 : 
    8697            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8698            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8699            4 : 
    8700            4 :         Ok(())
    8701            4 :     }
    8702              : 
    8703              :     #[tokio::test(start_paused = true)]
    8704            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8705            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8706            4 :             .await
    8707            4 :             .unwrap()
    8708            4 :             .load()
    8709            4 :             .await;
    8710            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8711            4 :         // initial transition into AttachedSingle.
    8712            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8713            4 :         tokio::time::resume();
    8714            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8715            4 : 
    8716            4 :         let end_lsn = Lsn(0x100);
    8717            4 :         let image_layers = (0x20..=0x90)
    8718            4 :             .step_by(0x10)
    8719           32 :             .map(|n| {
    8720           32 :                 (
    8721           32 :                     Lsn(n),
    8722           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8723           32 :                 )
    8724           32 :             })
    8725            4 :             .collect();
    8726            4 : 
    8727            4 :         let timeline = tenant
    8728            4 :             .create_test_timeline_with_layers(
    8729            4 :                 TIMELINE_ID,
    8730            4 :                 Lsn(0x10),
    8731            4 :                 DEFAULT_PG_VERSION,
    8732            4 :                 &ctx,
    8733            4 :                 Vec::new(),
    8734            4 :                 image_layers,
    8735            4 :                 end_lsn,
    8736            4 :             )
    8737            4 :             .await?;
    8738            4 : 
    8739            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8740            4 :         let mut leases = Vec::new();
    8741           12 :         leased_lsns.iter().for_each(|n| {
    8742           12 :             leases.push(
    8743           12 :                 timeline
    8744           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8745           12 :                     .expect("lease request should succeed"),
    8746           12 :             );
    8747           12 :         });
    8748            4 : 
    8749            4 :         let updated_lease_0 = timeline
    8750            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8751            4 :             .expect("lease renewal should succeed");
    8752            4 :         assert_eq!(
    8753            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8754            4 :             " Renewing with shorter lease should not change the lease."
    8755            4 :         );
    8756            4 : 
    8757            4 :         let updated_lease_1 = timeline
    8758            4 :             .renew_lsn_lease(
    8759            4 :                 Lsn(leased_lsns[1]),
    8760            4 :                 timeline.get_lsn_lease_length() * 2,
    8761            4 :                 &ctx,
    8762            4 :             )
    8763            4 :             .expect("lease renewal should succeed");
    8764            4 :         assert!(
    8765            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8766            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8767            4 :         );
    8768            4 : 
    8769            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8770            4 :         info!(
    8771            4 :             "applied_gc_cutoff_lsn: {}",
    8772            0 :             *timeline.get_applied_gc_cutoff_lsn()
    8773            4 :         );
    8774            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8775            4 : 
    8776            4 :         let res = tenant
    8777            4 :             .gc_iteration(
    8778            4 :                 Some(TIMELINE_ID),
    8779            4 :                 0,
    8780            4 :                 Duration::ZERO,
    8781            4 :                 &CancellationToken::new(),
    8782            4 :                 &ctx,
    8783            4 :             )
    8784            4 :             .await
    8785            4 :             .unwrap();
    8786            4 : 
    8787            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8788            4 :         // 0/10: initdb layer
    8789            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8790            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8791            4 :         // Keeping 0/90 b/c it is the latest layer.
    8792            4 :         assert_eq!(res.layers_not_updated, 1);
    8793            4 :         // Removed 0/80.
    8794            4 :         assert_eq!(res.layers_removed, 1);
    8795            4 : 
    8796            4 :         // Make lease on a already GC-ed LSN.
    8797            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8798            4 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    8799            4 :         timeline
    8800            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8801            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8802            4 : 
    8803            4 :         // Should still be able to renew a currently valid lease
    8804            4 :         // Assumption: original lease to is still valid for 0/50.
    8805            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8806            4 :         timeline
    8807            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8808            4 :             .expect("lease renewal with validation should succeed");
    8809            4 : 
    8810            4 :         Ok(())
    8811            4 :     }
    8812              : 
    8813              :     #[cfg(feature = "testing")]
    8814              :     #[tokio::test]
    8815            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8816            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8817            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8818            4 :             false,
    8819            4 :         )
    8820            4 :         .await
    8821            4 :     }
    8822              : 
    8823              :     #[cfg(feature = "testing")]
    8824              :     #[tokio::test]
    8825            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8826            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8827            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8828            4 :             true,
    8829            4 :         )
    8830            4 :         .await
    8831            4 :     }
    8832              : 
    8833              :     #[cfg(feature = "testing")]
    8834            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8835            8 :         test_name: &'static str,
    8836            8 :         use_delta_bottom_layer: bool,
    8837            8 :     ) -> anyhow::Result<()> {
    8838            8 :         let harness = TenantHarness::create(test_name).await?;
    8839            8 :         let (tenant, ctx) = harness.load().await;
    8840              : 
    8841          552 :         fn get_key(id: u32) -> Key {
    8842          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8843          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8844          552 :             key.field6 = id;
    8845          552 :             key
    8846          552 :         }
    8847              : 
    8848              :         // We create
    8849              :         // - one bottom-most image layer,
    8850              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8851              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8852              :         // - a delta layer D3 above the horizon.
    8853              :         //
    8854              :         //                             | D3 |
    8855              :         //  | D1 |
    8856              :         // -|    |-- gc horizon -----------------
    8857              :         //  |    |                | D2 |
    8858              :         // --------- img layer ------------------
    8859              :         //
    8860              :         // What we should expact from this compaction is:
    8861              :         //                             | D3 |
    8862              :         //  | Part of D1 |
    8863              :         // --------- img layer with D1+D2 at GC horizon------------------
    8864              : 
    8865              :         // img layer at 0x10
    8866            8 :         let img_layer = (0..10)
    8867           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8868            8 :             .collect_vec();
    8869            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8870            8 :         let delta4 = (0..10)
    8871           80 :             .map(|id| {
    8872           80 :                 (
    8873           80 :                     get_key(id),
    8874           80 :                     Lsn(0x08),
    8875           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8876           80 :                 )
    8877           80 :             })
    8878            8 :             .collect_vec();
    8879            8 : 
    8880            8 :         let delta1 = vec![
    8881            8 :             (
    8882            8 :                 get_key(1),
    8883            8 :                 Lsn(0x20),
    8884            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8885            8 :             ),
    8886            8 :             (
    8887            8 :                 get_key(2),
    8888            8 :                 Lsn(0x30),
    8889            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8890            8 :             ),
    8891            8 :             (
    8892            8 :                 get_key(3),
    8893            8 :                 Lsn(0x28),
    8894            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8895            8 :             ),
    8896            8 :             (
    8897            8 :                 get_key(3),
    8898            8 :                 Lsn(0x30),
    8899            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8900            8 :             ),
    8901            8 :             (
    8902            8 :                 get_key(3),
    8903            8 :                 Lsn(0x40),
    8904            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8905            8 :             ),
    8906            8 :         ];
    8907            8 :         let delta2 = vec![
    8908            8 :             (
    8909            8 :                 get_key(5),
    8910            8 :                 Lsn(0x20),
    8911            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8912            8 :             ),
    8913            8 :             (
    8914            8 :                 get_key(6),
    8915            8 :                 Lsn(0x20),
    8916            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8917            8 :             ),
    8918            8 :         ];
    8919            8 :         let delta3 = vec![
    8920            8 :             (
    8921            8 :                 get_key(8),
    8922            8 :                 Lsn(0x48),
    8923            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8924            8 :             ),
    8925            8 :             (
    8926            8 :                 get_key(9),
    8927            8 :                 Lsn(0x48),
    8928            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8929            8 :             ),
    8930            8 :         ];
    8931              : 
    8932            8 :         let tline = if use_delta_bottom_layer {
    8933            4 :             tenant
    8934            4 :                 .create_test_timeline_with_layers(
    8935            4 :                     TIMELINE_ID,
    8936            4 :                     Lsn(0x08),
    8937            4 :                     DEFAULT_PG_VERSION,
    8938            4 :                     &ctx,
    8939            4 :                     vec![
    8940            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8941            4 :                             Lsn(0x08)..Lsn(0x10),
    8942            4 :                             delta4,
    8943            4 :                         ),
    8944            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8945            4 :                             Lsn(0x20)..Lsn(0x48),
    8946            4 :                             delta1,
    8947            4 :                         ),
    8948            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8949            4 :                             Lsn(0x20)..Lsn(0x48),
    8950            4 :                             delta2,
    8951            4 :                         ),
    8952            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8953            4 :                             Lsn(0x48)..Lsn(0x50),
    8954            4 :                             delta3,
    8955            4 :                         ),
    8956            4 :                     ], // delta layers
    8957            4 :                     vec![], // image layers
    8958            4 :                     Lsn(0x50),
    8959            4 :                 )
    8960            4 :                 .await?
    8961              :         } else {
    8962            4 :             tenant
    8963            4 :                 .create_test_timeline_with_layers(
    8964            4 :                     TIMELINE_ID,
    8965            4 :                     Lsn(0x10),
    8966            4 :                     DEFAULT_PG_VERSION,
    8967            4 :                     &ctx,
    8968            4 :                     vec![
    8969            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8970            4 :                             Lsn(0x10)..Lsn(0x48),
    8971            4 :                             delta1,
    8972            4 :                         ),
    8973            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8974            4 :                             Lsn(0x10)..Lsn(0x48),
    8975            4 :                             delta2,
    8976            4 :                         ),
    8977            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8978            4 :                             Lsn(0x48)..Lsn(0x50),
    8979            4 :                             delta3,
    8980            4 :                         ),
    8981            4 :                     ], // delta layers
    8982            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8983            4 :                     Lsn(0x50),
    8984            4 :                 )
    8985            4 :                 .await?
    8986              :         };
    8987              :         {
    8988            8 :             tline
    8989            8 :                 .applied_gc_cutoff_lsn
    8990            8 :                 .lock_for_write()
    8991            8 :                 .store_and_unlock(Lsn(0x30))
    8992            8 :                 .wait()
    8993            8 :                 .await;
    8994              :             // Update GC info
    8995            8 :             let mut guard = tline.gc_info.write().unwrap();
    8996            8 :             *guard = GcInfo {
    8997            8 :                 retain_lsns: vec![],
    8998            8 :                 cutoffs: GcCutoffs {
    8999            8 :                     time: Lsn(0x30),
    9000            8 :                     space: Lsn(0x30),
    9001            8 :                 },
    9002            8 :                 leases: Default::default(),
    9003            8 :                 within_ancestor_pitr: false,
    9004            8 :             };
    9005            8 :         }
    9006            8 : 
    9007            8 :         let expected_result = [
    9008            8 :             Bytes::from_static(b"value 0@0x10"),
    9009            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9010            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9011            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9012            8 :             Bytes::from_static(b"value 4@0x10"),
    9013            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9014            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9015            8 :             Bytes::from_static(b"value 7@0x10"),
    9016            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9017            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9018            8 :         ];
    9019            8 : 
    9020            8 :         let expected_result_at_gc_horizon = [
    9021            8 :             Bytes::from_static(b"value 0@0x10"),
    9022            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9023            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9024            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9025            8 :             Bytes::from_static(b"value 4@0x10"),
    9026            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9027            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9028            8 :             Bytes::from_static(b"value 7@0x10"),
    9029            8 :             Bytes::from_static(b"value 8@0x10"),
    9030            8 :             Bytes::from_static(b"value 9@0x10"),
    9031            8 :         ];
    9032              : 
    9033           88 :         for idx in 0..10 {
    9034           80 :             assert_eq!(
    9035           80 :                 tline
    9036           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9037           80 :                     .await
    9038           80 :                     .unwrap(),
    9039           80 :                 &expected_result[idx]
    9040              :             );
    9041           80 :             assert_eq!(
    9042           80 :                 tline
    9043           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9044           80 :                     .await
    9045           80 :                     .unwrap(),
    9046           80 :                 &expected_result_at_gc_horizon[idx]
    9047              :             );
    9048              :         }
    9049              : 
    9050            8 :         let cancel = CancellationToken::new();
    9051            8 :         tline
    9052            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9053            8 :             .await
    9054            8 :             .unwrap();
    9055              : 
    9056           88 :         for idx in 0..10 {
    9057           80 :             assert_eq!(
    9058           80 :                 tline
    9059           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9060           80 :                     .await
    9061           80 :                     .unwrap(),
    9062           80 :                 &expected_result[idx]
    9063              :             );
    9064           80 :             assert_eq!(
    9065           80 :                 tline
    9066           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9067           80 :                     .await
    9068           80 :                     .unwrap(),
    9069           80 :                 &expected_result_at_gc_horizon[idx]
    9070              :             );
    9071              :         }
    9072              : 
    9073              :         // increase GC horizon and compact again
    9074              :         {
    9075            8 :             tline
    9076            8 :                 .applied_gc_cutoff_lsn
    9077            8 :                 .lock_for_write()
    9078            8 :                 .store_and_unlock(Lsn(0x40))
    9079            8 :                 .wait()
    9080            8 :                 .await;
    9081              :             // Update GC info
    9082            8 :             let mut guard = tline.gc_info.write().unwrap();
    9083            8 :             guard.cutoffs.time = Lsn(0x40);
    9084            8 :             guard.cutoffs.space = Lsn(0x40);
    9085            8 :         }
    9086            8 :         tline
    9087            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9088            8 :             .await
    9089            8 :             .unwrap();
    9090            8 : 
    9091            8 :         Ok(())
    9092            8 :     }
    9093              : 
    9094              :     #[cfg(feature = "testing")]
    9095              :     #[tokio::test]
    9096            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9097            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9098            4 :         let (tenant, ctx) = harness.load().await;
    9099            4 :         let tline = tenant
    9100            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9101            4 :             .await?;
    9102            4 :         tline.force_advance_lsn(Lsn(0x70));
    9103            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9104            4 :         let history = vec![
    9105            4 :             (
    9106            4 :                 key,
    9107            4 :                 Lsn(0x10),
    9108            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9109            4 :             ),
    9110            4 :             (
    9111            4 :                 key,
    9112            4 :                 Lsn(0x20),
    9113            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9114            4 :             ),
    9115            4 :             (
    9116            4 :                 key,
    9117            4 :                 Lsn(0x30),
    9118            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9119            4 :             ),
    9120            4 :             (
    9121            4 :                 key,
    9122            4 :                 Lsn(0x40),
    9123            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9124            4 :             ),
    9125            4 :             (
    9126            4 :                 key,
    9127            4 :                 Lsn(0x50),
    9128            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9129            4 :             ),
    9130            4 :             (
    9131            4 :                 key,
    9132            4 :                 Lsn(0x60),
    9133            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9134            4 :             ),
    9135            4 :             (
    9136            4 :                 key,
    9137            4 :                 Lsn(0x70),
    9138            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9139            4 :             ),
    9140            4 :             (
    9141            4 :                 key,
    9142            4 :                 Lsn(0x80),
    9143            4 :                 Value::Image(Bytes::copy_from_slice(
    9144            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9145            4 :                 )),
    9146            4 :             ),
    9147            4 :             (
    9148            4 :                 key,
    9149            4 :                 Lsn(0x90),
    9150            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9151            4 :             ),
    9152            4 :         ];
    9153            4 :         let res = tline
    9154            4 :             .generate_key_retention(
    9155            4 :                 key,
    9156            4 :                 &history,
    9157            4 :                 Lsn(0x60),
    9158            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9159            4 :                 3,
    9160            4 :                 None,
    9161            4 :             )
    9162            4 :             .await
    9163            4 :             .unwrap();
    9164            4 :         let expected_res = KeyHistoryRetention {
    9165            4 :             below_horizon: vec![
    9166            4 :                 (
    9167            4 :                     Lsn(0x20),
    9168            4 :                     KeyLogAtLsn(vec![(
    9169            4 :                         Lsn(0x20),
    9170            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9171            4 :                     )]),
    9172            4 :                 ),
    9173            4 :                 (
    9174            4 :                     Lsn(0x40),
    9175            4 :                     KeyLogAtLsn(vec![
    9176            4 :                         (
    9177            4 :                             Lsn(0x30),
    9178            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9179            4 :                         ),
    9180            4 :                         (
    9181            4 :                             Lsn(0x40),
    9182            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9183            4 :                         ),
    9184            4 :                     ]),
    9185            4 :                 ),
    9186            4 :                 (
    9187            4 :                     Lsn(0x50),
    9188            4 :                     KeyLogAtLsn(vec![(
    9189            4 :                         Lsn(0x50),
    9190            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9191            4 :                     )]),
    9192            4 :                 ),
    9193            4 :                 (
    9194            4 :                     Lsn(0x60),
    9195            4 :                     KeyLogAtLsn(vec![(
    9196            4 :                         Lsn(0x60),
    9197            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9198            4 :                     )]),
    9199            4 :                 ),
    9200            4 :             ],
    9201            4 :             above_horizon: KeyLogAtLsn(vec![
    9202            4 :                 (
    9203            4 :                     Lsn(0x70),
    9204            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9205            4 :                 ),
    9206            4 :                 (
    9207            4 :                     Lsn(0x80),
    9208            4 :                     Value::Image(Bytes::copy_from_slice(
    9209            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9210            4 :                     )),
    9211            4 :                 ),
    9212            4 :                 (
    9213            4 :                     Lsn(0x90),
    9214            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9215            4 :                 ),
    9216            4 :             ]),
    9217            4 :         };
    9218            4 :         assert_eq!(res, expected_res);
    9219            4 : 
    9220            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9221            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9222            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9223            4 :         // For example, we have
    9224            4 :         // ```plain
    9225            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9226            4 :         // ```
    9227            4 :         // Now the GC horizon moves up, and we have
    9228            4 :         // ```plain
    9229            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9230            4 :         // ```
    9231            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9232            4 :         // We will end up with
    9233            4 :         // ```plain
    9234            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9235            4 :         // ```
    9236            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9237            4 :         // We should be able to handle this partial history and drop everything before the
    9238            4 :         // gc_horizon image.
    9239            4 : 
    9240            4 :         let history = vec![
    9241            4 :             (
    9242            4 :                 key,
    9243            4 :                 Lsn(0x20),
    9244            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9245            4 :             ),
    9246            4 :             (
    9247            4 :                 key,
    9248            4 :                 Lsn(0x30),
    9249            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9250            4 :             ),
    9251            4 :             (
    9252            4 :                 key,
    9253            4 :                 Lsn(0x40),
    9254            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9255            4 :             ),
    9256            4 :             (
    9257            4 :                 key,
    9258            4 :                 Lsn(0x50),
    9259            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9260            4 :             ),
    9261            4 :             (
    9262            4 :                 key,
    9263            4 :                 Lsn(0x60),
    9264            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9265            4 :             ),
    9266            4 :             (
    9267            4 :                 key,
    9268            4 :                 Lsn(0x70),
    9269            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9270            4 :             ),
    9271            4 :             (
    9272            4 :                 key,
    9273            4 :                 Lsn(0x80),
    9274            4 :                 Value::Image(Bytes::copy_from_slice(
    9275            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9276            4 :                 )),
    9277            4 :             ),
    9278            4 :             (
    9279            4 :                 key,
    9280            4 :                 Lsn(0x90),
    9281            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9282            4 :             ),
    9283            4 :         ];
    9284            4 :         let res = tline
    9285            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9286            4 :             .await
    9287            4 :             .unwrap();
    9288            4 :         let expected_res = KeyHistoryRetention {
    9289            4 :             below_horizon: vec![
    9290            4 :                 (
    9291            4 :                     Lsn(0x40),
    9292            4 :                     KeyLogAtLsn(vec![(
    9293            4 :                         Lsn(0x40),
    9294            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9295            4 :                     )]),
    9296            4 :                 ),
    9297            4 :                 (
    9298            4 :                     Lsn(0x50),
    9299            4 :                     KeyLogAtLsn(vec![(
    9300            4 :                         Lsn(0x50),
    9301            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9302            4 :                     )]),
    9303            4 :                 ),
    9304            4 :                 (
    9305            4 :                     Lsn(0x60),
    9306            4 :                     KeyLogAtLsn(vec![(
    9307            4 :                         Lsn(0x60),
    9308            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9309            4 :                     )]),
    9310            4 :                 ),
    9311            4 :             ],
    9312            4 :             above_horizon: KeyLogAtLsn(vec![
    9313            4 :                 (
    9314            4 :                     Lsn(0x70),
    9315            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9316            4 :                 ),
    9317            4 :                 (
    9318            4 :                     Lsn(0x80),
    9319            4 :                     Value::Image(Bytes::copy_from_slice(
    9320            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9321            4 :                     )),
    9322            4 :                 ),
    9323            4 :                 (
    9324            4 :                     Lsn(0x90),
    9325            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9326            4 :                 ),
    9327            4 :             ]),
    9328            4 :         };
    9329            4 :         assert_eq!(res, expected_res);
    9330            4 : 
    9331            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9332            4 :         // the ancestor image in the test case.
    9333            4 : 
    9334            4 :         let history = vec![
    9335            4 :             (
    9336            4 :                 key,
    9337            4 :                 Lsn(0x20),
    9338            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9339            4 :             ),
    9340            4 :             (
    9341            4 :                 key,
    9342            4 :                 Lsn(0x30),
    9343            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9344            4 :             ),
    9345            4 :             (
    9346            4 :                 key,
    9347            4 :                 Lsn(0x40),
    9348            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9349            4 :             ),
    9350            4 :             (
    9351            4 :                 key,
    9352            4 :                 Lsn(0x70),
    9353            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9354            4 :             ),
    9355            4 :         ];
    9356            4 :         let res = tline
    9357            4 :             .generate_key_retention(
    9358            4 :                 key,
    9359            4 :                 &history,
    9360            4 :                 Lsn(0x60),
    9361            4 :                 &[],
    9362            4 :                 3,
    9363            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9364            4 :             )
    9365            4 :             .await
    9366            4 :             .unwrap();
    9367            4 :         let expected_res = KeyHistoryRetention {
    9368            4 :             below_horizon: vec![(
    9369            4 :                 Lsn(0x60),
    9370            4 :                 KeyLogAtLsn(vec![(
    9371            4 :                     Lsn(0x60),
    9372            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9373            4 :                 )]),
    9374            4 :             )],
    9375            4 :             above_horizon: KeyLogAtLsn(vec![(
    9376            4 :                 Lsn(0x70),
    9377            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9378            4 :             )]),
    9379            4 :         };
    9380            4 :         assert_eq!(res, expected_res);
    9381            4 : 
    9382            4 :         let history = vec![
    9383            4 :             (
    9384            4 :                 key,
    9385            4 :                 Lsn(0x20),
    9386            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9387            4 :             ),
    9388            4 :             (
    9389            4 :                 key,
    9390            4 :                 Lsn(0x40),
    9391            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9392            4 :             ),
    9393            4 :             (
    9394            4 :                 key,
    9395            4 :                 Lsn(0x60),
    9396            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9397            4 :             ),
    9398            4 :             (
    9399            4 :                 key,
    9400            4 :                 Lsn(0x70),
    9401            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9402            4 :             ),
    9403            4 :         ];
    9404            4 :         let res = tline
    9405            4 :             .generate_key_retention(
    9406            4 :                 key,
    9407            4 :                 &history,
    9408            4 :                 Lsn(0x60),
    9409            4 :                 &[Lsn(0x30)],
    9410            4 :                 3,
    9411            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9412            4 :             )
    9413            4 :             .await
    9414            4 :             .unwrap();
    9415            4 :         let expected_res = KeyHistoryRetention {
    9416            4 :             below_horizon: vec![
    9417            4 :                 (
    9418            4 :                     Lsn(0x30),
    9419            4 :                     KeyLogAtLsn(vec![(
    9420            4 :                         Lsn(0x20),
    9421            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9422            4 :                     )]),
    9423            4 :                 ),
    9424            4 :                 (
    9425            4 :                     Lsn(0x60),
    9426            4 :                     KeyLogAtLsn(vec![(
    9427            4 :                         Lsn(0x60),
    9428            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9429            4 :                     )]),
    9430            4 :                 ),
    9431            4 :             ],
    9432            4 :             above_horizon: KeyLogAtLsn(vec![(
    9433            4 :                 Lsn(0x70),
    9434            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9435            4 :             )]),
    9436            4 :         };
    9437            4 :         assert_eq!(res, expected_res);
    9438            4 : 
    9439            4 :         Ok(())
    9440            4 :     }
    9441              : 
    9442              :     #[cfg(feature = "testing")]
    9443              :     #[tokio::test]
    9444            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9445            4 :         let harness =
    9446            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9447            4 :         let (tenant, ctx) = harness.load().await;
    9448            4 : 
    9449         1036 :         fn get_key(id: u32) -> Key {
    9450         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9451         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9452         1036 :             key.field6 = id;
    9453         1036 :             key
    9454         1036 :         }
    9455            4 : 
    9456            4 :         let img_layer = (0..10)
    9457           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9458            4 :             .collect_vec();
    9459            4 : 
    9460            4 :         let delta1 = vec![
    9461            4 :             (
    9462            4 :                 get_key(1),
    9463            4 :                 Lsn(0x20),
    9464            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9465            4 :             ),
    9466            4 :             (
    9467            4 :                 get_key(2),
    9468            4 :                 Lsn(0x30),
    9469            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9470            4 :             ),
    9471            4 :             (
    9472            4 :                 get_key(3),
    9473            4 :                 Lsn(0x28),
    9474            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9475            4 :             ),
    9476            4 :             (
    9477            4 :                 get_key(3),
    9478            4 :                 Lsn(0x30),
    9479            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9480            4 :             ),
    9481            4 :             (
    9482            4 :                 get_key(3),
    9483            4 :                 Lsn(0x40),
    9484            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9485            4 :             ),
    9486            4 :         ];
    9487            4 :         let delta2 = vec![
    9488            4 :             (
    9489            4 :                 get_key(5),
    9490            4 :                 Lsn(0x20),
    9491            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9492            4 :             ),
    9493            4 :             (
    9494            4 :                 get_key(6),
    9495            4 :                 Lsn(0x20),
    9496            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9497            4 :             ),
    9498            4 :         ];
    9499            4 :         let delta3 = vec![
    9500            4 :             (
    9501            4 :                 get_key(8),
    9502            4 :                 Lsn(0x48),
    9503            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9504            4 :             ),
    9505            4 :             (
    9506            4 :                 get_key(9),
    9507            4 :                 Lsn(0x48),
    9508            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9509            4 :             ),
    9510            4 :         ];
    9511            4 : 
    9512            4 :         let tline = tenant
    9513            4 :             .create_test_timeline_with_layers(
    9514            4 :                 TIMELINE_ID,
    9515            4 :                 Lsn(0x10),
    9516            4 :                 DEFAULT_PG_VERSION,
    9517            4 :                 &ctx,
    9518            4 :                 vec![
    9519            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9520            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9521            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9522            4 :                 ], // delta layers
    9523            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9524            4 :                 Lsn(0x50),
    9525            4 :             )
    9526            4 :             .await?;
    9527            4 :         {
    9528            4 :             tline
    9529            4 :                 .applied_gc_cutoff_lsn
    9530            4 :                 .lock_for_write()
    9531            4 :                 .store_and_unlock(Lsn(0x30))
    9532            4 :                 .wait()
    9533            4 :                 .await;
    9534            4 :             // Update GC info
    9535            4 :             let mut guard = tline.gc_info.write().unwrap();
    9536            4 :             *guard = GcInfo {
    9537            4 :                 retain_lsns: vec![
    9538            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9539            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9540            4 :                 ],
    9541            4 :                 cutoffs: GcCutoffs {
    9542            4 :                     time: Lsn(0x30),
    9543            4 :                     space: Lsn(0x30),
    9544            4 :                 },
    9545            4 :                 leases: Default::default(),
    9546            4 :                 within_ancestor_pitr: false,
    9547            4 :             };
    9548            4 :         }
    9549            4 : 
    9550            4 :         let expected_result = [
    9551            4 :             Bytes::from_static(b"value 0@0x10"),
    9552            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9553            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9554            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9555            4 :             Bytes::from_static(b"value 4@0x10"),
    9556            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9557            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9558            4 :             Bytes::from_static(b"value 7@0x10"),
    9559            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9560            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9561            4 :         ];
    9562            4 : 
    9563            4 :         let expected_result_at_gc_horizon = [
    9564            4 :             Bytes::from_static(b"value 0@0x10"),
    9565            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9566            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9567            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9568            4 :             Bytes::from_static(b"value 4@0x10"),
    9569            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9570            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9571            4 :             Bytes::from_static(b"value 7@0x10"),
    9572            4 :             Bytes::from_static(b"value 8@0x10"),
    9573            4 :             Bytes::from_static(b"value 9@0x10"),
    9574            4 :         ];
    9575            4 : 
    9576            4 :         let expected_result_at_lsn_20 = [
    9577            4 :             Bytes::from_static(b"value 0@0x10"),
    9578            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9579            4 :             Bytes::from_static(b"value 2@0x10"),
    9580            4 :             Bytes::from_static(b"value 3@0x10"),
    9581            4 :             Bytes::from_static(b"value 4@0x10"),
    9582            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9583            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9584            4 :             Bytes::from_static(b"value 7@0x10"),
    9585            4 :             Bytes::from_static(b"value 8@0x10"),
    9586            4 :             Bytes::from_static(b"value 9@0x10"),
    9587            4 :         ];
    9588            4 : 
    9589            4 :         let expected_result_at_lsn_10 = [
    9590            4 :             Bytes::from_static(b"value 0@0x10"),
    9591            4 :             Bytes::from_static(b"value 1@0x10"),
    9592            4 :             Bytes::from_static(b"value 2@0x10"),
    9593            4 :             Bytes::from_static(b"value 3@0x10"),
    9594            4 :             Bytes::from_static(b"value 4@0x10"),
    9595            4 :             Bytes::from_static(b"value 5@0x10"),
    9596            4 :             Bytes::from_static(b"value 6@0x10"),
    9597            4 :             Bytes::from_static(b"value 7@0x10"),
    9598            4 :             Bytes::from_static(b"value 8@0x10"),
    9599            4 :             Bytes::from_static(b"value 9@0x10"),
    9600            4 :         ];
    9601            4 : 
    9602           24 :         let verify_result = || async {
    9603           24 :             let gc_horizon = {
    9604           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9605           24 :                 gc_info.cutoffs.time
    9606            4 :             };
    9607          264 :             for idx in 0..10 {
    9608          240 :                 assert_eq!(
    9609          240 :                     tline
    9610          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9611          240 :                         .await
    9612          240 :                         .unwrap(),
    9613          240 :                     &expected_result[idx]
    9614            4 :                 );
    9615          240 :                 assert_eq!(
    9616          240 :                     tline
    9617          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9618          240 :                         .await
    9619          240 :                         .unwrap(),
    9620          240 :                     &expected_result_at_gc_horizon[idx]
    9621            4 :                 );
    9622          240 :                 assert_eq!(
    9623          240 :                     tline
    9624          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9625          240 :                         .await
    9626          240 :                         .unwrap(),
    9627          240 :                     &expected_result_at_lsn_20[idx]
    9628            4 :                 );
    9629          240 :                 assert_eq!(
    9630          240 :                     tline
    9631          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9632          240 :                         .await
    9633          240 :                         .unwrap(),
    9634          240 :                     &expected_result_at_lsn_10[idx]
    9635            4 :                 );
    9636            4 :             }
    9637           48 :         };
    9638            4 : 
    9639            4 :         verify_result().await;
    9640            4 : 
    9641            4 :         let cancel = CancellationToken::new();
    9642            4 :         let mut dryrun_flags = EnumSet::new();
    9643            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9644            4 : 
    9645            4 :         tline
    9646            4 :             .compact_with_gc(
    9647            4 :                 &cancel,
    9648            4 :                 CompactOptions {
    9649            4 :                     flags: dryrun_flags,
    9650            4 :                     ..Default::default()
    9651            4 :                 },
    9652            4 :                 &ctx,
    9653            4 :             )
    9654            4 :             .await
    9655            4 :             .unwrap();
    9656            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
    9657            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9658            4 :         verify_result().await;
    9659            4 : 
    9660            4 :         tline
    9661            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9662            4 :             .await
    9663            4 :             .unwrap();
    9664            4 :         verify_result().await;
    9665            4 : 
    9666            4 :         // compact again
    9667            4 :         tline
    9668            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9669            4 :             .await
    9670            4 :             .unwrap();
    9671            4 :         verify_result().await;
    9672            4 : 
    9673            4 :         // increase GC horizon and compact again
    9674            4 :         {
    9675            4 :             tline
    9676            4 :                 .applied_gc_cutoff_lsn
    9677            4 :                 .lock_for_write()
    9678            4 :                 .store_and_unlock(Lsn(0x38))
    9679            4 :                 .wait()
    9680            4 :                 .await;
    9681            4 :             // Update GC info
    9682            4 :             let mut guard = tline.gc_info.write().unwrap();
    9683            4 :             guard.cutoffs.time = Lsn(0x38);
    9684            4 :             guard.cutoffs.space = Lsn(0x38);
    9685            4 :         }
    9686            4 :         tline
    9687            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9688            4 :             .await
    9689            4 :             .unwrap();
    9690            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9691            4 : 
    9692            4 :         // not increasing the GC horizon and compact again
    9693            4 :         tline
    9694            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9695            4 :             .await
    9696            4 :             .unwrap();
    9697            4 :         verify_result().await;
    9698            4 : 
    9699            4 :         Ok(())
    9700            4 :     }
    9701              : 
    9702              :     #[cfg(feature = "testing")]
    9703              :     #[tokio::test]
    9704            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9705            4 :     {
    9706            4 :         let harness =
    9707            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9708            4 :                 .await?;
    9709            4 :         let (tenant, ctx) = harness.load().await;
    9710            4 : 
    9711          704 :         fn get_key(id: u32) -> Key {
    9712          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9713          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9714          704 :             key.field6 = id;
    9715          704 :             key
    9716          704 :         }
    9717            4 : 
    9718            4 :         let img_layer = (0..10)
    9719           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9720            4 :             .collect_vec();
    9721            4 : 
    9722            4 :         let delta1 = vec![
    9723            4 :             (
    9724            4 :                 get_key(1),
    9725            4 :                 Lsn(0x20),
    9726            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9727            4 :             ),
    9728            4 :             (
    9729            4 :                 get_key(1),
    9730            4 :                 Lsn(0x28),
    9731            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9732            4 :             ),
    9733            4 :         ];
    9734            4 :         let delta2 = vec![
    9735            4 :             (
    9736            4 :                 get_key(1),
    9737            4 :                 Lsn(0x30),
    9738            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9739            4 :             ),
    9740            4 :             (
    9741            4 :                 get_key(1),
    9742            4 :                 Lsn(0x38),
    9743            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9744            4 :             ),
    9745            4 :         ];
    9746            4 :         let delta3 = vec![
    9747            4 :             (
    9748            4 :                 get_key(8),
    9749            4 :                 Lsn(0x48),
    9750            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9751            4 :             ),
    9752            4 :             (
    9753            4 :                 get_key(9),
    9754            4 :                 Lsn(0x48),
    9755            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9756            4 :             ),
    9757            4 :         ];
    9758            4 : 
    9759            4 :         let tline = tenant
    9760            4 :             .create_test_timeline_with_layers(
    9761            4 :                 TIMELINE_ID,
    9762            4 :                 Lsn(0x10),
    9763            4 :                 DEFAULT_PG_VERSION,
    9764            4 :                 &ctx,
    9765            4 :                 vec![
    9766            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9767            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9768            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9769            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9770            4 :                 ], // delta layers
    9771            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9772            4 :                 Lsn(0x50),
    9773            4 :             )
    9774            4 :             .await?;
    9775            4 :         {
    9776            4 :             tline
    9777            4 :                 .applied_gc_cutoff_lsn
    9778            4 :                 .lock_for_write()
    9779            4 :                 .store_and_unlock(Lsn(0x30))
    9780            4 :                 .wait()
    9781            4 :                 .await;
    9782            4 :             // Update GC info
    9783            4 :             let mut guard = tline.gc_info.write().unwrap();
    9784            4 :             *guard = GcInfo {
    9785            4 :                 retain_lsns: vec![
    9786            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9787            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9788            4 :                 ],
    9789            4 :                 cutoffs: GcCutoffs {
    9790            4 :                     time: Lsn(0x30),
    9791            4 :                     space: Lsn(0x30),
    9792            4 :                 },
    9793            4 :                 leases: Default::default(),
    9794            4 :                 within_ancestor_pitr: false,
    9795            4 :             };
    9796            4 :         }
    9797            4 : 
    9798            4 :         let expected_result = [
    9799            4 :             Bytes::from_static(b"value 0@0x10"),
    9800            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9801            4 :             Bytes::from_static(b"value 2@0x10"),
    9802            4 :             Bytes::from_static(b"value 3@0x10"),
    9803            4 :             Bytes::from_static(b"value 4@0x10"),
    9804            4 :             Bytes::from_static(b"value 5@0x10"),
    9805            4 :             Bytes::from_static(b"value 6@0x10"),
    9806            4 :             Bytes::from_static(b"value 7@0x10"),
    9807            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9808            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9809            4 :         ];
    9810            4 : 
    9811            4 :         let expected_result_at_gc_horizon = [
    9812            4 :             Bytes::from_static(b"value 0@0x10"),
    9813            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9814            4 :             Bytes::from_static(b"value 2@0x10"),
    9815            4 :             Bytes::from_static(b"value 3@0x10"),
    9816            4 :             Bytes::from_static(b"value 4@0x10"),
    9817            4 :             Bytes::from_static(b"value 5@0x10"),
    9818            4 :             Bytes::from_static(b"value 6@0x10"),
    9819            4 :             Bytes::from_static(b"value 7@0x10"),
    9820            4 :             Bytes::from_static(b"value 8@0x10"),
    9821            4 :             Bytes::from_static(b"value 9@0x10"),
    9822            4 :         ];
    9823            4 : 
    9824            4 :         let expected_result_at_lsn_20 = [
    9825            4 :             Bytes::from_static(b"value 0@0x10"),
    9826            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9827            4 :             Bytes::from_static(b"value 2@0x10"),
    9828            4 :             Bytes::from_static(b"value 3@0x10"),
    9829            4 :             Bytes::from_static(b"value 4@0x10"),
    9830            4 :             Bytes::from_static(b"value 5@0x10"),
    9831            4 :             Bytes::from_static(b"value 6@0x10"),
    9832            4 :             Bytes::from_static(b"value 7@0x10"),
    9833            4 :             Bytes::from_static(b"value 8@0x10"),
    9834            4 :             Bytes::from_static(b"value 9@0x10"),
    9835            4 :         ];
    9836            4 : 
    9837            4 :         let expected_result_at_lsn_10 = [
    9838            4 :             Bytes::from_static(b"value 0@0x10"),
    9839            4 :             Bytes::from_static(b"value 1@0x10"),
    9840            4 :             Bytes::from_static(b"value 2@0x10"),
    9841            4 :             Bytes::from_static(b"value 3@0x10"),
    9842            4 :             Bytes::from_static(b"value 4@0x10"),
    9843            4 :             Bytes::from_static(b"value 5@0x10"),
    9844            4 :             Bytes::from_static(b"value 6@0x10"),
    9845            4 :             Bytes::from_static(b"value 7@0x10"),
    9846            4 :             Bytes::from_static(b"value 8@0x10"),
    9847            4 :             Bytes::from_static(b"value 9@0x10"),
    9848            4 :         ];
    9849            4 : 
    9850           16 :         let verify_result = || async {
    9851           16 :             let gc_horizon = {
    9852           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9853           16 :                 gc_info.cutoffs.time
    9854            4 :             };
    9855          176 :             for idx in 0..10 {
    9856          160 :                 assert_eq!(
    9857          160 :                     tline
    9858          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9859          160 :                         .await
    9860          160 :                         .unwrap(),
    9861          160 :                     &expected_result[idx]
    9862            4 :                 );
    9863          160 :                 assert_eq!(
    9864          160 :                     tline
    9865          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9866          160 :                         .await
    9867          160 :                         .unwrap(),
    9868          160 :                     &expected_result_at_gc_horizon[idx]
    9869            4 :                 );
    9870          160 :                 assert_eq!(
    9871          160 :                     tline
    9872          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9873          160 :                         .await
    9874          160 :                         .unwrap(),
    9875          160 :                     &expected_result_at_lsn_20[idx]
    9876            4 :                 );
    9877          160 :                 assert_eq!(
    9878          160 :                     tline
    9879          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9880          160 :                         .await
    9881          160 :                         .unwrap(),
    9882          160 :                     &expected_result_at_lsn_10[idx]
    9883            4 :                 );
    9884            4 :             }
    9885           32 :         };
    9886            4 : 
    9887            4 :         verify_result().await;
    9888            4 : 
    9889            4 :         let cancel = CancellationToken::new();
    9890            4 :         let mut dryrun_flags = EnumSet::new();
    9891            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9892            4 : 
    9893            4 :         tline
    9894            4 :             .compact_with_gc(
    9895            4 :                 &cancel,
    9896            4 :                 CompactOptions {
    9897            4 :                     flags: dryrun_flags,
    9898            4 :                     ..Default::default()
    9899            4 :                 },
    9900            4 :                 &ctx,
    9901            4 :             )
    9902            4 :             .await
    9903            4 :             .unwrap();
    9904            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
    9905            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9906            4 :         verify_result().await;
    9907            4 : 
    9908            4 :         tline
    9909            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9910            4 :             .await
    9911            4 :             .unwrap();
    9912            4 :         verify_result().await;
    9913            4 : 
    9914            4 :         // compact again
    9915            4 :         tline
    9916            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9917            4 :             .await
    9918            4 :             .unwrap();
    9919            4 :         verify_result().await;
    9920            4 : 
    9921            4 :         Ok(())
    9922            4 :     }
    9923              : 
    9924              :     #[cfg(feature = "testing")]
    9925              :     #[tokio::test]
    9926            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9927            4 :         use models::CompactLsnRange;
    9928            4 : 
    9929            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9930            4 :         let (tenant, ctx) = harness.load().await;
    9931            4 : 
    9932          332 :         fn get_key(id: u32) -> Key {
    9933          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9934          332 :             key.field6 = id;
    9935          332 :             key
    9936          332 :         }
    9937            4 : 
    9938            4 :         let img_layer = (0..10)
    9939           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9940            4 :             .collect_vec();
    9941            4 : 
    9942            4 :         let delta1 = vec![
    9943            4 :             (
    9944            4 :                 get_key(1),
    9945            4 :                 Lsn(0x20),
    9946            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9947            4 :             ),
    9948            4 :             (
    9949            4 :                 get_key(2),
    9950            4 :                 Lsn(0x30),
    9951            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9952            4 :             ),
    9953            4 :             (
    9954            4 :                 get_key(3),
    9955            4 :                 Lsn(0x28),
    9956            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9957            4 :             ),
    9958            4 :             (
    9959            4 :                 get_key(3),
    9960            4 :                 Lsn(0x30),
    9961            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9962            4 :             ),
    9963            4 :             (
    9964            4 :                 get_key(3),
    9965            4 :                 Lsn(0x40),
    9966            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9967            4 :             ),
    9968            4 :         ];
    9969            4 :         let delta2 = vec![
    9970            4 :             (
    9971            4 :                 get_key(5),
    9972            4 :                 Lsn(0x20),
    9973            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9974            4 :             ),
    9975            4 :             (
    9976            4 :                 get_key(6),
    9977            4 :                 Lsn(0x20),
    9978            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9979            4 :             ),
    9980            4 :         ];
    9981            4 :         let delta3 = vec![
    9982            4 :             (
    9983            4 :                 get_key(8),
    9984            4 :                 Lsn(0x48),
    9985            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9986            4 :             ),
    9987            4 :             (
    9988            4 :                 get_key(9),
    9989            4 :                 Lsn(0x48),
    9990            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9991            4 :             ),
    9992            4 :         ];
    9993            4 : 
    9994            4 :         let parent_tline = tenant
    9995            4 :             .create_test_timeline_with_layers(
    9996            4 :                 TIMELINE_ID,
    9997            4 :                 Lsn(0x10),
    9998            4 :                 DEFAULT_PG_VERSION,
    9999            4 :                 &ctx,
   10000            4 :                 vec![],                       // delta layers
   10001            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10002            4 :                 Lsn(0x18),
   10003            4 :             )
   10004            4 :             .await?;
   10005            4 : 
   10006            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10007            4 : 
   10008            4 :         let branch_tline = tenant
   10009            4 :             .branch_timeline_test_with_layers(
   10010            4 :                 &parent_tline,
   10011            4 :                 NEW_TIMELINE_ID,
   10012            4 :                 Some(Lsn(0x18)),
   10013            4 :                 &ctx,
   10014            4 :                 vec![
   10015            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10016            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10017            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10018            4 :                 ], // delta layers
   10019            4 :                 vec![], // image layers
   10020            4 :                 Lsn(0x50),
   10021            4 :             )
   10022            4 :             .await?;
   10023            4 : 
   10024            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10025            4 : 
   10026            4 :         {
   10027            4 :             parent_tline
   10028            4 :                 .applied_gc_cutoff_lsn
   10029            4 :                 .lock_for_write()
   10030            4 :                 .store_and_unlock(Lsn(0x10))
   10031            4 :                 .wait()
   10032            4 :                 .await;
   10033            4 :             // Update GC info
   10034            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10035            4 :             *guard = GcInfo {
   10036            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10037            4 :                 cutoffs: GcCutoffs {
   10038            4 :                     time: Lsn(0x10),
   10039            4 :                     space: Lsn(0x10),
   10040            4 :                 },
   10041            4 :                 leases: Default::default(),
   10042            4 :                 within_ancestor_pitr: false,
   10043            4 :             };
   10044            4 :         }
   10045            4 : 
   10046            4 :         {
   10047            4 :             branch_tline
   10048            4 :                 .applied_gc_cutoff_lsn
   10049            4 :                 .lock_for_write()
   10050            4 :                 .store_and_unlock(Lsn(0x50))
   10051            4 :                 .wait()
   10052            4 :                 .await;
   10053            4 :             // Update GC info
   10054            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10055            4 :             *guard = GcInfo {
   10056            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10057            4 :                 cutoffs: GcCutoffs {
   10058            4 :                     time: Lsn(0x50),
   10059            4 :                     space: Lsn(0x50),
   10060            4 :                 },
   10061            4 :                 leases: Default::default(),
   10062            4 :                 within_ancestor_pitr: false,
   10063            4 :             };
   10064            4 :         }
   10065            4 : 
   10066            4 :         let expected_result_at_gc_horizon = [
   10067            4 :             Bytes::from_static(b"value 0@0x10"),
   10068            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10069            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10070            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10071            4 :             Bytes::from_static(b"value 4@0x10"),
   10072            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10073            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10074            4 :             Bytes::from_static(b"value 7@0x10"),
   10075            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10076            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10077            4 :         ];
   10078            4 : 
   10079            4 :         let expected_result_at_lsn_40 = [
   10080            4 :             Bytes::from_static(b"value 0@0x10"),
   10081            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10082            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10083            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10084            4 :             Bytes::from_static(b"value 4@0x10"),
   10085            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10086            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10087            4 :             Bytes::from_static(b"value 7@0x10"),
   10088            4 :             Bytes::from_static(b"value 8@0x10"),
   10089            4 :             Bytes::from_static(b"value 9@0x10"),
   10090            4 :         ];
   10091            4 : 
   10092           12 :         let verify_result = || async {
   10093          132 :             for idx in 0..10 {
   10094          120 :                 assert_eq!(
   10095          120 :                     branch_tline
   10096          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10097          120 :                         .await
   10098          120 :                         .unwrap(),
   10099          120 :                     &expected_result_at_gc_horizon[idx]
   10100            4 :                 );
   10101          120 :                 assert_eq!(
   10102          120 :                     branch_tline
   10103          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10104          120 :                         .await
   10105          120 :                         .unwrap(),
   10106          120 :                     &expected_result_at_lsn_40[idx]
   10107            4 :                 );
   10108            4 :             }
   10109           24 :         };
   10110            4 : 
   10111            4 :         verify_result().await;
   10112            4 : 
   10113            4 :         let cancel = CancellationToken::new();
   10114            4 :         branch_tline
   10115            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10116            4 :             .await
   10117            4 :             .unwrap();
   10118            4 : 
   10119            4 :         verify_result().await;
   10120            4 : 
   10121            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10122            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10123            4 :         branch_tline
   10124            4 :             .compact_with_gc(
   10125            4 :                 &cancel,
   10126            4 :                 CompactOptions {
   10127            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10128            4 :                     ..Default::default()
   10129            4 :                 },
   10130            4 :                 &ctx,
   10131            4 :             )
   10132            4 :             .await
   10133            4 :             .unwrap();
   10134            4 : 
   10135            4 :         verify_result().await;
   10136            4 : 
   10137            4 :         Ok(())
   10138            4 :     }
   10139              : 
   10140              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10141              :     // Create an image arrangement where we have to read at different LSN ranges
   10142              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10143              :     // a delta layer. Like so:
   10144              :     //
   10145              :     //     A      B
   10146              :     // +----------------+ -> delta_layer
   10147              :     // |                |                           ^ lsn
   10148              :     // |       =========|-> nested_image_layer      |
   10149              :     // |       C        |                           |
   10150              :     // +----------------+                           |
   10151              :     // ======== -> baseline_image_layer             +-------> key
   10152              :     //
   10153              :     //
   10154              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10155              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10156              :     #[cfg(feature = "testing")]
   10157              :     #[tokio::test]
   10158            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10159            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10160            4 :         let (tenant, ctx) = harness.load().await;
   10161            4 : 
   10162            4 :         let will_init_keys = [2, 6];
   10163           88 :         fn get_key(id: u32) -> Key {
   10164           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10165           88 :             key.field6 = id;
   10166           88 :             key
   10167           88 :         }
   10168            4 : 
   10169            4 :         let mut expected_key_values = HashMap::new();
   10170            4 : 
   10171            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10172            4 :         let mut baseline_img_layer = Vec::new();
   10173           24 :         for i in 0..5 {
   10174           20 :             let key = get_key(i);
   10175           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10176           20 : 
   10177           20 :             let removed = expected_key_values.insert(key, value.clone());
   10178           20 :             assert!(removed.is_none());
   10179            4 : 
   10180           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10181            4 :         }
   10182            4 : 
   10183            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10184            4 :         let mut nested_img_layer = Vec::new();
   10185           24 :         for i in 5..10 {
   10186           20 :             let key = get_key(i);
   10187           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10188           20 : 
   10189           20 :             let removed = expected_key_values.insert(key, value.clone());
   10190           20 :             assert!(removed.is_none());
   10191            4 : 
   10192           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10193            4 :         }
   10194            4 : 
   10195            4 :         let mut delta_layer_spec = Vec::default();
   10196            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10197            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10198            4 : 
   10199           44 :         for i in 0..10 {
   10200           40 :             let key = get_key(i);
   10201           40 :             let key_in_nested = nested_img_layer
   10202           40 :                 .iter()
   10203          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10204           40 :             let lsn = {
   10205           40 :                 if key_in_nested {
   10206           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10207            4 :                 } else {
   10208           20 :                     delta_layer_start_lsn
   10209            4 :                 }
   10210            4 :             };
   10211            4 : 
   10212           40 :             let will_init = will_init_keys.contains(&i);
   10213           40 :             if will_init {
   10214            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10215            8 : 
   10216            8 :                 expected_key_values.insert(key, "".to_string());
   10217           32 :             } else {
   10218           32 :                 let delta = format!("@{lsn}");
   10219           32 :                 delta_layer_spec.push((
   10220           32 :                     key,
   10221           32 :                     lsn,
   10222           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10223           32 :                 ));
   10224           32 : 
   10225           32 :                 expected_key_values
   10226           32 :                     .get_mut(&key)
   10227           32 :                     .expect("An image exists for each key")
   10228           32 :                     .push_str(delta.as_str());
   10229           32 :             }
   10230           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10231            4 :         }
   10232            4 : 
   10233            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10234            4 : 
   10235            4 :         assert!(
   10236            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10237            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10238            4 :         );
   10239            4 : 
   10240            4 :         let tline = tenant
   10241            4 :             .create_test_timeline_with_layers(
   10242            4 :                 TIMELINE_ID,
   10243            4 :                 baseline_image_layer_lsn,
   10244            4 :                 DEFAULT_PG_VERSION,
   10245            4 :                 &ctx,
   10246            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10247            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10248            4 :                     delta_layer_spec,
   10249            4 :                 )], // delta layers
   10250            4 :                 vec![
   10251            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10252            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10253            4 :                 ], // image layers
   10254            4 :                 delta_layer_end_lsn,
   10255            4 :             )
   10256            4 :             .await?;
   10257            4 : 
   10258            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10259            4 :         let results = tline
   10260            4 :             .get_vectored(
   10261            4 :                 keyspace,
   10262            4 :                 delta_layer_end_lsn,
   10263            4 :                 IoConcurrency::sequential(),
   10264            4 :                 &ctx,
   10265            4 :             )
   10266            4 :             .await
   10267            4 :             .expect("No vectored errors");
   10268           44 :         for (key, res) in results {
   10269           40 :             let value = res.expect("No key errors");
   10270           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10271           40 :             assert_eq!(value, Bytes::from(expected_value));
   10272            4 :         }
   10273            4 : 
   10274            4 :         Ok(())
   10275            4 :     }
   10276              : 
   10277          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10278          428 :         (
   10279          428 :             k1.is_delta,
   10280          428 :             k1.key_range.start,
   10281          428 :             k1.key_range.end,
   10282          428 :             k1.lsn_range.start,
   10283          428 :             k1.lsn_range.end,
   10284          428 :         )
   10285          428 :             .cmp(&(
   10286          428 :                 k2.is_delta,
   10287          428 :                 k2.key_range.start,
   10288          428 :                 k2.key_range.end,
   10289          428 :                 k2.lsn_range.start,
   10290          428 :                 k2.lsn_range.end,
   10291          428 :             ))
   10292          428 :     }
   10293              : 
   10294           48 :     async fn inspect_and_sort(
   10295           48 :         tline: &Arc<Timeline>,
   10296           48 :         filter: Option<std::ops::Range<Key>>,
   10297           48 :     ) -> Vec<PersistentLayerKey> {
   10298           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10299           48 :         if let Some(filter) = filter {
   10300          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10301           44 :         }
   10302           48 :         all_layers.sort_by(sort_layer_key);
   10303           48 :         all_layers
   10304           48 :     }
   10305              : 
   10306              :     #[cfg(feature = "testing")]
   10307           44 :     fn check_layer_map_key_eq(
   10308           44 :         mut left: Vec<PersistentLayerKey>,
   10309           44 :         mut right: Vec<PersistentLayerKey>,
   10310           44 :     ) {
   10311           44 :         left.sort_by(sort_layer_key);
   10312           44 :         right.sort_by(sort_layer_key);
   10313           44 :         if left != right {
   10314            0 :             eprintln!("---LEFT---");
   10315            0 :             for left in left.iter() {
   10316            0 :                 eprintln!("{}", left);
   10317            0 :             }
   10318            0 :             eprintln!("---RIGHT---");
   10319            0 :             for right in right.iter() {
   10320            0 :                 eprintln!("{}", right);
   10321            0 :             }
   10322            0 :             assert_eq!(left, right);
   10323           44 :         }
   10324           44 :     }
   10325              : 
   10326              :     #[cfg(feature = "testing")]
   10327              :     #[tokio::test]
   10328            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10329            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10330            4 :         let (tenant, ctx) = harness.load().await;
   10331            4 : 
   10332          364 :         fn get_key(id: u32) -> Key {
   10333          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10334          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10335          364 :             key.field6 = id;
   10336          364 :             key
   10337          364 :         }
   10338            4 : 
   10339            4 :         // img layer at 0x10
   10340            4 :         let img_layer = (0..10)
   10341           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10342            4 :             .collect_vec();
   10343            4 : 
   10344            4 :         let delta1 = vec![
   10345            4 :             (
   10346            4 :                 get_key(1),
   10347            4 :                 Lsn(0x20),
   10348            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10349            4 :             ),
   10350            4 :             (
   10351            4 :                 get_key(2),
   10352            4 :                 Lsn(0x30),
   10353            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10354            4 :             ),
   10355            4 :             (
   10356            4 :                 get_key(3),
   10357            4 :                 Lsn(0x40),
   10358            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10359            4 :             ),
   10360            4 :         ];
   10361            4 :         let delta2 = vec![
   10362            4 :             (
   10363            4 :                 get_key(5),
   10364            4 :                 Lsn(0x20),
   10365            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10366            4 :             ),
   10367            4 :             (
   10368            4 :                 get_key(6),
   10369            4 :                 Lsn(0x20),
   10370            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10371            4 :             ),
   10372            4 :         ];
   10373            4 :         let delta3 = vec![
   10374            4 :             (
   10375            4 :                 get_key(8),
   10376            4 :                 Lsn(0x48),
   10377            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10378            4 :             ),
   10379            4 :             (
   10380            4 :                 get_key(9),
   10381            4 :                 Lsn(0x48),
   10382            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10383            4 :             ),
   10384            4 :         ];
   10385            4 : 
   10386            4 :         let tline = tenant
   10387            4 :             .create_test_timeline_with_layers(
   10388            4 :                 TIMELINE_ID,
   10389            4 :                 Lsn(0x10),
   10390            4 :                 DEFAULT_PG_VERSION,
   10391            4 :                 &ctx,
   10392            4 :                 vec![
   10393            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10394            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10395            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10396            4 :                 ], // delta layers
   10397            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10398            4 :                 Lsn(0x50),
   10399            4 :             )
   10400            4 :             .await?;
   10401            4 : 
   10402            4 :         {
   10403            4 :             tline
   10404            4 :                 .applied_gc_cutoff_lsn
   10405            4 :                 .lock_for_write()
   10406            4 :                 .store_and_unlock(Lsn(0x30))
   10407            4 :                 .wait()
   10408            4 :                 .await;
   10409            4 :             // Update GC info
   10410            4 :             let mut guard = tline.gc_info.write().unwrap();
   10411            4 :             *guard = GcInfo {
   10412            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10413            4 :                 cutoffs: GcCutoffs {
   10414            4 :                     time: Lsn(0x30),
   10415            4 :                     space: Lsn(0x30),
   10416            4 :                 },
   10417            4 :                 leases: Default::default(),
   10418            4 :                 within_ancestor_pitr: false,
   10419            4 :             };
   10420            4 :         }
   10421            4 : 
   10422            4 :         let cancel = CancellationToken::new();
   10423            4 : 
   10424            4 :         // Do a partial compaction on key range 0..2
   10425            4 :         tline
   10426            4 :             .compact_with_gc(
   10427            4 :                 &cancel,
   10428            4 :                 CompactOptions {
   10429            4 :                     flags: EnumSet::new(),
   10430            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10431            4 :                     ..Default::default()
   10432            4 :                 },
   10433            4 :                 &ctx,
   10434            4 :             )
   10435            4 :             .await
   10436            4 :             .unwrap();
   10437            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10438            4 :         check_layer_map_key_eq(
   10439            4 :             all_layers,
   10440            4 :             vec![
   10441            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10442            4 :                 PersistentLayerKey {
   10443            4 :                     key_range: get_key(0)..get_key(2),
   10444            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10445            4 :                     is_delta: false,
   10446            4 :                 },
   10447            4 :                 PersistentLayerKey {
   10448            4 :                     key_range: get_key(0)..get_key(10),
   10449            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10450            4 :                     is_delta: false,
   10451            4 :                 },
   10452            4 :                 // delta1 is split and the second part is rewritten
   10453            4 :                 PersistentLayerKey {
   10454            4 :                     key_range: get_key(2)..get_key(4),
   10455            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10456            4 :                     is_delta: true,
   10457            4 :                 },
   10458            4 :                 PersistentLayerKey {
   10459            4 :                     key_range: get_key(5)..get_key(7),
   10460            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10461            4 :                     is_delta: true,
   10462            4 :                 },
   10463            4 :                 PersistentLayerKey {
   10464            4 :                     key_range: get_key(8)..get_key(10),
   10465            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10466            4 :                     is_delta: true,
   10467            4 :                 },
   10468            4 :             ],
   10469            4 :         );
   10470            4 : 
   10471            4 :         // Do a partial compaction on key range 2..4
   10472            4 :         tline
   10473            4 :             .compact_with_gc(
   10474            4 :                 &cancel,
   10475            4 :                 CompactOptions {
   10476            4 :                     flags: EnumSet::new(),
   10477            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10478            4 :                     ..Default::default()
   10479            4 :                 },
   10480            4 :                 &ctx,
   10481            4 :             )
   10482            4 :             .await
   10483            4 :             .unwrap();
   10484            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10485            4 :         check_layer_map_key_eq(
   10486            4 :             all_layers,
   10487            4 :             vec![
   10488            4 :                 PersistentLayerKey {
   10489            4 :                     key_range: get_key(0)..get_key(2),
   10490            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10491            4 :                     is_delta: false,
   10492            4 :                 },
   10493            4 :                 PersistentLayerKey {
   10494            4 :                     key_range: get_key(0)..get_key(10),
   10495            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10496            4 :                     is_delta: false,
   10497            4 :                 },
   10498            4 :                 // image layer generated for the compaction range 2-4
   10499            4 :                 PersistentLayerKey {
   10500            4 :                     key_range: get_key(2)..get_key(4),
   10501            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10502            4 :                     is_delta: false,
   10503            4 :                 },
   10504            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10505            4 :                 PersistentLayerKey {
   10506            4 :                     key_range: get_key(2)..get_key(4),
   10507            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10508            4 :                     is_delta: true,
   10509            4 :                 },
   10510            4 :                 PersistentLayerKey {
   10511            4 :                     key_range: get_key(5)..get_key(7),
   10512            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10513            4 :                     is_delta: true,
   10514            4 :                 },
   10515            4 :                 PersistentLayerKey {
   10516            4 :                     key_range: get_key(8)..get_key(10),
   10517            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10518            4 :                     is_delta: true,
   10519            4 :                 },
   10520            4 :             ],
   10521            4 :         );
   10522            4 : 
   10523            4 :         // Do a partial compaction on key range 4..9
   10524            4 :         tline
   10525            4 :             .compact_with_gc(
   10526            4 :                 &cancel,
   10527            4 :                 CompactOptions {
   10528            4 :                     flags: EnumSet::new(),
   10529            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10530            4 :                     ..Default::default()
   10531            4 :                 },
   10532            4 :                 &ctx,
   10533            4 :             )
   10534            4 :             .await
   10535            4 :             .unwrap();
   10536            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10537            4 :         check_layer_map_key_eq(
   10538            4 :             all_layers,
   10539            4 :             vec![
   10540            4 :                 PersistentLayerKey {
   10541            4 :                     key_range: get_key(0)..get_key(2),
   10542            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10543            4 :                     is_delta: false,
   10544            4 :                 },
   10545            4 :                 PersistentLayerKey {
   10546            4 :                     key_range: get_key(0)..get_key(10),
   10547            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10548            4 :                     is_delta: false,
   10549            4 :                 },
   10550            4 :                 PersistentLayerKey {
   10551            4 :                     key_range: get_key(2)..get_key(4),
   10552            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10553            4 :                     is_delta: false,
   10554            4 :                 },
   10555            4 :                 PersistentLayerKey {
   10556            4 :                     key_range: get_key(2)..get_key(4),
   10557            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10558            4 :                     is_delta: true,
   10559            4 :                 },
   10560            4 :                 // image layer generated for this compaction range
   10561            4 :                 PersistentLayerKey {
   10562            4 :                     key_range: get_key(4)..get_key(9),
   10563            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10564            4 :                     is_delta: false,
   10565            4 :                 },
   10566            4 :                 PersistentLayerKey {
   10567            4 :                     key_range: get_key(8)..get_key(10),
   10568            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10569            4 :                     is_delta: true,
   10570            4 :                 },
   10571            4 :             ],
   10572            4 :         );
   10573            4 : 
   10574            4 :         // Do a partial compaction on key range 9..10
   10575            4 :         tline
   10576            4 :             .compact_with_gc(
   10577            4 :                 &cancel,
   10578            4 :                 CompactOptions {
   10579            4 :                     flags: EnumSet::new(),
   10580            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10581            4 :                     ..Default::default()
   10582            4 :                 },
   10583            4 :                 &ctx,
   10584            4 :             )
   10585            4 :             .await
   10586            4 :             .unwrap();
   10587            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10588            4 :         check_layer_map_key_eq(
   10589            4 :             all_layers,
   10590            4 :             vec![
   10591            4 :                 PersistentLayerKey {
   10592            4 :                     key_range: get_key(0)..get_key(2),
   10593            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10594            4 :                     is_delta: false,
   10595            4 :                 },
   10596            4 :                 PersistentLayerKey {
   10597            4 :                     key_range: get_key(0)..get_key(10),
   10598            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10599            4 :                     is_delta: false,
   10600            4 :                 },
   10601            4 :                 PersistentLayerKey {
   10602            4 :                     key_range: get_key(2)..get_key(4),
   10603            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10604            4 :                     is_delta: false,
   10605            4 :                 },
   10606            4 :                 PersistentLayerKey {
   10607            4 :                     key_range: get_key(2)..get_key(4),
   10608            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10609            4 :                     is_delta: true,
   10610            4 :                 },
   10611            4 :                 PersistentLayerKey {
   10612            4 :                     key_range: get_key(4)..get_key(9),
   10613            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10614            4 :                     is_delta: false,
   10615            4 :                 },
   10616            4 :                 // image layer generated for the compaction range
   10617            4 :                 PersistentLayerKey {
   10618            4 :                     key_range: get_key(9)..get_key(10),
   10619            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10620            4 :                     is_delta: false,
   10621            4 :                 },
   10622            4 :                 PersistentLayerKey {
   10623            4 :                     key_range: get_key(8)..get_key(10),
   10624            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10625            4 :                     is_delta: true,
   10626            4 :                 },
   10627            4 :             ],
   10628            4 :         );
   10629            4 : 
   10630            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10631            4 :         tline
   10632            4 :             .compact_with_gc(
   10633            4 :                 &cancel,
   10634            4 :                 CompactOptions {
   10635            4 :                     flags: EnumSet::new(),
   10636            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10637            4 :                     ..Default::default()
   10638            4 :                 },
   10639            4 :                 &ctx,
   10640            4 :             )
   10641            4 :             .await
   10642            4 :             .unwrap();
   10643            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10644            4 :         check_layer_map_key_eq(
   10645            4 :             all_layers,
   10646            4 :             vec![
   10647            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10648            4 :                 PersistentLayerKey {
   10649            4 :                     key_range: get_key(0)..get_key(10),
   10650            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10651            4 :                     is_delta: false,
   10652            4 :                 },
   10653            4 :                 PersistentLayerKey {
   10654            4 :                     key_range: get_key(2)..get_key(4),
   10655            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10656            4 :                     is_delta: true,
   10657            4 :                 },
   10658            4 :                 PersistentLayerKey {
   10659            4 :                     key_range: get_key(8)..get_key(10),
   10660            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10661            4 :                     is_delta: true,
   10662            4 :                 },
   10663            4 :             ],
   10664            4 :         );
   10665            4 :         Ok(())
   10666            4 :     }
   10667              : 
   10668              :     #[cfg(feature = "testing")]
   10669              :     #[tokio::test]
   10670            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10671            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10672            4 :             .await
   10673            4 :             .unwrap();
   10674            4 :         let (tenant, ctx) = harness.load().await;
   10675            4 :         let tline_parent = tenant
   10676            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10677            4 :             .await
   10678            4 :             .unwrap();
   10679            4 :         let tline_child = tenant
   10680            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10681            4 :             .await
   10682            4 :             .unwrap();
   10683            4 :         {
   10684            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10685            4 :             assert_eq!(
   10686            4 :                 gc_info_parent.retain_lsns,
   10687            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10688            4 :             );
   10689            4 :         }
   10690            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10691            4 :         tline_child
   10692            4 :             .remote_client
   10693            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10694            4 :             .unwrap();
   10695            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10696            4 :         offload_timeline(&tenant, &tline_child)
   10697            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10698            4 :             .await.unwrap();
   10699            4 :         let child_timeline_id = tline_child.timeline_id;
   10700            4 :         Arc::try_unwrap(tline_child).unwrap();
   10701            4 : 
   10702            4 :         {
   10703            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10704            4 :             assert_eq!(
   10705            4 :                 gc_info_parent.retain_lsns,
   10706            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10707            4 :             );
   10708            4 :         }
   10709            4 : 
   10710            4 :         tenant
   10711            4 :             .get_offloaded_timeline(child_timeline_id)
   10712            4 :             .unwrap()
   10713            4 :             .defuse_for_tenant_drop();
   10714            4 : 
   10715            4 :         Ok(())
   10716            4 :     }
   10717              : 
   10718              :     #[cfg(feature = "testing")]
   10719              :     #[tokio::test]
   10720            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10721            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10722            4 :         let (tenant, ctx) = harness.load().await;
   10723            4 : 
   10724          592 :         fn get_key(id: u32) -> Key {
   10725          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10726          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10727          592 :             key.field6 = id;
   10728          592 :             key
   10729          592 :         }
   10730            4 : 
   10731            4 :         let img_layer = (0..10)
   10732           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10733            4 :             .collect_vec();
   10734            4 : 
   10735            4 :         let delta1 = vec![(
   10736            4 :             get_key(1),
   10737            4 :             Lsn(0x20),
   10738            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10739            4 :         )];
   10740            4 :         let delta4 = vec![(
   10741            4 :             get_key(1),
   10742            4 :             Lsn(0x28),
   10743            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10744            4 :         )];
   10745            4 :         let delta2 = vec![
   10746            4 :             (
   10747            4 :                 get_key(1),
   10748            4 :                 Lsn(0x30),
   10749            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10750            4 :             ),
   10751            4 :             (
   10752            4 :                 get_key(1),
   10753            4 :                 Lsn(0x38),
   10754            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10755            4 :             ),
   10756            4 :         ];
   10757            4 :         let delta3 = vec![
   10758            4 :             (
   10759            4 :                 get_key(8),
   10760            4 :                 Lsn(0x48),
   10761            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10762            4 :             ),
   10763            4 :             (
   10764            4 :                 get_key(9),
   10765            4 :                 Lsn(0x48),
   10766            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10767            4 :             ),
   10768            4 :         ];
   10769            4 : 
   10770            4 :         let tline = tenant
   10771            4 :             .create_test_timeline_with_layers(
   10772            4 :                 TIMELINE_ID,
   10773            4 :                 Lsn(0x10),
   10774            4 :                 DEFAULT_PG_VERSION,
   10775            4 :                 &ctx,
   10776            4 :                 vec![
   10777            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10778            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10779            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10780            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10781            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10782            4 :                 ], // delta layers
   10783            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10784            4 :                 Lsn(0x50),
   10785            4 :             )
   10786            4 :             .await?;
   10787            4 :         {
   10788            4 :             tline
   10789            4 :                 .applied_gc_cutoff_lsn
   10790            4 :                 .lock_for_write()
   10791            4 :                 .store_and_unlock(Lsn(0x30))
   10792            4 :                 .wait()
   10793            4 :                 .await;
   10794            4 :             // Update GC info
   10795            4 :             let mut guard = tline.gc_info.write().unwrap();
   10796            4 :             *guard = GcInfo {
   10797            4 :                 retain_lsns: vec![
   10798            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10799            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10800            4 :                 ],
   10801            4 :                 cutoffs: GcCutoffs {
   10802            4 :                     time: Lsn(0x30),
   10803            4 :                     space: Lsn(0x30),
   10804            4 :                 },
   10805            4 :                 leases: Default::default(),
   10806            4 :                 within_ancestor_pitr: false,
   10807            4 :             };
   10808            4 :         }
   10809            4 : 
   10810            4 :         let expected_result = [
   10811            4 :             Bytes::from_static(b"value 0@0x10"),
   10812            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10813            4 :             Bytes::from_static(b"value 2@0x10"),
   10814            4 :             Bytes::from_static(b"value 3@0x10"),
   10815            4 :             Bytes::from_static(b"value 4@0x10"),
   10816            4 :             Bytes::from_static(b"value 5@0x10"),
   10817            4 :             Bytes::from_static(b"value 6@0x10"),
   10818            4 :             Bytes::from_static(b"value 7@0x10"),
   10819            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10820            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10821            4 :         ];
   10822            4 : 
   10823            4 :         let expected_result_at_gc_horizon = [
   10824            4 :             Bytes::from_static(b"value 0@0x10"),
   10825            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10826            4 :             Bytes::from_static(b"value 2@0x10"),
   10827            4 :             Bytes::from_static(b"value 3@0x10"),
   10828            4 :             Bytes::from_static(b"value 4@0x10"),
   10829            4 :             Bytes::from_static(b"value 5@0x10"),
   10830            4 :             Bytes::from_static(b"value 6@0x10"),
   10831            4 :             Bytes::from_static(b"value 7@0x10"),
   10832            4 :             Bytes::from_static(b"value 8@0x10"),
   10833            4 :             Bytes::from_static(b"value 9@0x10"),
   10834            4 :         ];
   10835            4 : 
   10836            4 :         let expected_result_at_lsn_20 = [
   10837            4 :             Bytes::from_static(b"value 0@0x10"),
   10838            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10839            4 :             Bytes::from_static(b"value 2@0x10"),
   10840            4 :             Bytes::from_static(b"value 3@0x10"),
   10841            4 :             Bytes::from_static(b"value 4@0x10"),
   10842            4 :             Bytes::from_static(b"value 5@0x10"),
   10843            4 :             Bytes::from_static(b"value 6@0x10"),
   10844            4 :             Bytes::from_static(b"value 7@0x10"),
   10845            4 :             Bytes::from_static(b"value 8@0x10"),
   10846            4 :             Bytes::from_static(b"value 9@0x10"),
   10847            4 :         ];
   10848            4 : 
   10849            4 :         let expected_result_at_lsn_10 = [
   10850            4 :             Bytes::from_static(b"value 0@0x10"),
   10851            4 :             Bytes::from_static(b"value 1@0x10"),
   10852            4 :             Bytes::from_static(b"value 2@0x10"),
   10853            4 :             Bytes::from_static(b"value 3@0x10"),
   10854            4 :             Bytes::from_static(b"value 4@0x10"),
   10855            4 :             Bytes::from_static(b"value 5@0x10"),
   10856            4 :             Bytes::from_static(b"value 6@0x10"),
   10857            4 :             Bytes::from_static(b"value 7@0x10"),
   10858            4 :             Bytes::from_static(b"value 8@0x10"),
   10859            4 :             Bytes::from_static(b"value 9@0x10"),
   10860            4 :         ];
   10861            4 : 
   10862           12 :         let verify_result = || async {
   10863           12 :             let gc_horizon = {
   10864           12 :                 let gc_info = tline.gc_info.read().unwrap();
   10865           12 :                 gc_info.cutoffs.time
   10866            4 :             };
   10867          132 :             for idx in 0..10 {
   10868          120 :                 assert_eq!(
   10869          120 :                     tline
   10870          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10871          120 :                         .await
   10872          120 :                         .unwrap(),
   10873          120 :                     &expected_result[idx]
   10874            4 :                 );
   10875          120 :                 assert_eq!(
   10876          120 :                     tline
   10877          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10878          120 :                         .await
   10879          120 :                         .unwrap(),
   10880          120 :                     &expected_result_at_gc_horizon[idx]
   10881            4 :                 );
   10882          120 :                 assert_eq!(
   10883          120 :                     tline
   10884          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10885          120 :                         .await
   10886          120 :                         .unwrap(),
   10887          120 :                     &expected_result_at_lsn_20[idx]
   10888            4 :                 );
   10889          120 :                 assert_eq!(
   10890          120 :                     tline
   10891          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10892          120 :                         .await
   10893          120 :                         .unwrap(),
   10894          120 :                     &expected_result_at_lsn_10[idx]
   10895            4 :                 );
   10896            4 :             }
   10897           24 :         };
   10898            4 : 
   10899            4 :         verify_result().await;
   10900            4 : 
   10901            4 :         let cancel = CancellationToken::new();
   10902            4 :         tline
   10903            4 :             .compact_with_gc(
   10904            4 :                 &cancel,
   10905            4 :                 CompactOptions {
   10906            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10907            4 :                     ..Default::default()
   10908            4 :                 },
   10909            4 :                 &ctx,
   10910            4 :             )
   10911            4 :             .await
   10912            4 :             .unwrap();
   10913            4 :         verify_result().await;
   10914            4 : 
   10915            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10916            4 :         check_layer_map_key_eq(
   10917            4 :             all_layers,
   10918            4 :             vec![
   10919            4 :                 // The original image layer, not compacted
   10920            4 :                 PersistentLayerKey {
   10921            4 :                     key_range: get_key(0)..get_key(10),
   10922            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10923            4 :                     is_delta: false,
   10924            4 :                 },
   10925            4 :                 // Delta layer below the specified above_lsn not compacted
   10926            4 :                 PersistentLayerKey {
   10927            4 :                     key_range: get_key(1)..get_key(2),
   10928            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10929            4 :                     is_delta: true,
   10930            4 :                 },
   10931            4 :                 // Delta layer compacted above the LSN
   10932            4 :                 PersistentLayerKey {
   10933            4 :                     key_range: get_key(1)..get_key(10),
   10934            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10935            4 :                     is_delta: true,
   10936            4 :                 },
   10937            4 :             ],
   10938            4 :         );
   10939            4 : 
   10940            4 :         // compact again
   10941            4 :         tline
   10942            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10943            4 :             .await
   10944            4 :             .unwrap();
   10945            4 :         verify_result().await;
   10946            4 : 
   10947            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10948            4 :         check_layer_map_key_eq(
   10949            4 :             all_layers,
   10950            4 :             vec![
   10951            4 :                 // The compacted image layer (full key range)
   10952            4 :                 PersistentLayerKey {
   10953            4 :                     key_range: Key::MIN..Key::MAX,
   10954            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10955            4 :                     is_delta: false,
   10956            4 :                 },
   10957            4 :                 // All other data in the delta layer
   10958            4 :                 PersistentLayerKey {
   10959            4 :                     key_range: get_key(1)..get_key(10),
   10960            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10961            4 :                     is_delta: true,
   10962            4 :                 },
   10963            4 :             ],
   10964            4 :         );
   10965            4 : 
   10966            4 :         Ok(())
   10967            4 :     }
   10968              : 
   10969              :     #[cfg(feature = "testing")]
   10970              :     #[tokio::test]
   10971            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   10972            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   10973            4 :         let (tenant, ctx) = harness.load().await;
   10974            4 : 
   10975         1016 :         fn get_key(id: u32) -> Key {
   10976         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10977         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10978         1016 :             key.field6 = id;
   10979         1016 :             key
   10980         1016 :         }
   10981            4 : 
   10982            4 :         let img_layer = (0..10)
   10983           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10984            4 :             .collect_vec();
   10985            4 : 
   10986            4 :         let delta1 = vec![(
   10987            4 :             get_key(1),
   10988            4 :             Lsn(0x20),
   10989            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10990            4 :         )];
   10991            4 :         let delta4 = vec![(
   10992            4 :             get_key(1),
   10993            4 :             Lsn(0x28),
   10994            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10995            4 :         )];
   10996            4 :         let delta2 = vec![
   10997            4 :             (
   10998            4 :                 get_key(1),
   10999            4 :                 Lsn(0x30),
   11000            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11001            4 :             ),
   11002            4 :             (
   11003            4 :                 get_key(1),
   11004            4 :                 Lsn(0x38),
   11005            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11006            4 :             ),
   11007            4 :         ];
   11008            4 :         let delta3 = vec![
   11009            4 :             (
   11010            4 :                 get_key(8),
   11011            4 :                 Lsn(0x48),
   11012            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11013            4 :             ),
   11014            4 :             (
   11015            4 :                 get_key(9),
   11016            4 :                 Lsn(0x48),
   11017            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11018            4 :             ),
   11019            4 :         ];
   11020            4 : 
   11021            4 :         let tline = tenant
   11022            4 :             .create_test_timeline_with_layers(
   11023            4 :                 TIMELINE_ID,
   11024            4 :                 Lsn(0x10),
   11025            4 :                 DEFAULT_PG_VERSION,
   11026            4 :                 &ctx,
   11027            4 :                 vec![
   11028            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11029            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11030            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11031            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11032            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11033            4 :                 ], // delta layers
   11034            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11035            4 :                 Lsn(0x50),
   11036            4 :             )
   11037            4 :             .await?;
   11038            4 :         {
   11039            4 :             tline
   11040            4 :                 .applied_gc_cutoff_lsn
   11041            4 :                 .lock_for_write()
   11042            4 :                 .store_and_unlock(Lsn(0x30))
   11043            4 :                 .wait()
   11044            4 :                 .await;
   11045            4 :             // Update GC info
   11046            4 :             let mut guard = tline.gc_info.write().unwrap();
   11047            4 :             *guard = GcInfo {
   11048            4 :                 retain_lsns: vec![
   11049            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11050            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11051            4 :                 ],
   11052            4 :                 cutoffs: GcCutoffs {
   11053            4 :                     time: Lsn(0x30),
   11054            4 :                     space: Lsn(0x30),
   11055            4 :                 },
   11056            4 :                 leases: Default::default(),
   11057            4 :                 within_ancestor_pitr: false,
   11058            4 :             };
   11059            4 :         }
   11060            4 : 
   11061            4 :         let expected_result = [
   11062            4 :             Bytes::from_static(b"value 0@0x10"),
   11063            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11064            4 :             Bytes::from_static(b"value 2@0x10"),
   11065            4 :             Bytes::from_static(b"value 3@0x10"),
   11066            4 :             Bytes::from_static(b"value 4@0x10"),
   11067            4 :             Bytes::from_static(b"value 5@0x10"),
   11068            4 :             Bytes::from_static(b"value 6@0x10"),
   11069            4 :             Bytes::from_static(b"value 7@0x10"),
   11070            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11071            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11072            4 :         ];
   11073            4 : 
   11074            4 :         let expected_result_at_gc_horizon = [
   11075            4 :             Bytes::from_static(b"value 0@0x10"),
   11076            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11077            4 :             Bytes::from_static(b"value 2@0x10"),
   11078            4 :             Bytes::from_static(b"value 3@0x10"),
   11079            4 :             Bytes::from_static(b"value 4@0x10"),
   11080            4 :             Bytes::from_static(b"value 5@0x10"),
   11081            4 :             Bytes::from_static(b"value 6@0x10"),
   11082            4 :             Bytes::from_static(b"value 7@0x10"),
   11083            4 :             Bytes::from_static(b"value 8@0x10"),
   11084            4 :             Bytes::from_static(b"value 9@0x10"),
   11085            4 :         ];
   11086            4 : 
   11087            4 :         let expected_result_at_lsn_20 = [
   11088            4 :             Bytes::from_static(b"value 0@0x10"),
   11089            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11090            4 :             Bytes::from_static(b"value 2@0x10"),
   11091            4 :             Bytes::from_static(b"value 3@0x10"),
   11092            4 :             Bytes::from_static(b"value 4@0x10"),
   11093            4 :             Bytes::from_static(b"value 5@0x10"),
   11094            4 :             Bytes::from_static(b"value 6@0x10"),
   11095            4 :             Bytes::from_static(b"value 7@0x10"),
   11096            4 :             Bytes::from_static(b"value 8@0x10"),
   11097            4 :             Bytes::from_static(b"value 9@0x10"),
   11098            4 :         ];
   11099            4 : 
   11100            4 :         let expected_result_at_lsn_10 = [
   11101            4 :             Bytes::from_static(b"value 0@0x10"),
   11102            4 :             Bytes::from_static(b"value 1@0x10"),
   11103            4 :             Bytes::from_static(b"value 2@0x10"),
   11104            4 :             Bytes::from_static(b"value 3@0x10"),
   11105            4 :             Bytes::from_static(b"value 4@0x10"),
   11106            4 :             Bytes::from_static(b"value 5@0x10"),
   11107            4 :             Bytes::from_static(b"value 6@0x10"),
   11108            4 :             Bytes::from_static(b"value 7@0x10"),
   11109            4 :             Bytes::from_static(b"value 8@0x10"),
   11110            4 :             Bytes::from_static(b"value 9@0x10"),
   11111            4 :         ];
   11112            4 : 
   11113           20 :         let verify_result = || async {
   11114           20 :             let gc_horizon = {
   11115           20 :                 let gc_info = tline.gc_info.read().unwrap();
   11116           20 :                 gc_info.cutoffs.time
   11117            4 :             };
   11118          220 :             for idx in 0..10 {
   11119          200 :                 assert_eq!(
   11120          200 :                     tline
   11121          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11122          200 :                         .await
   11123          200 :                         .unwrap(),
   11124          200 :                     &expected_result[idx]
   11125            4 :                 );
   11126          200 :                 assert_eq!(
   11127          200 :                     tline
   11128          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11129          200 :                         .await
   11130          200 :                         .unwrap(),
   11131          200 :                     &expected_result_at_gc_horizon[idx]
   11132            4 :                 );
   11133          200 :                 assert_eq!(
   11134          200 :                     tline
   11135          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11136          200 :                         .await
   11137          200 :                         .unwrap(),
   11138          200 :                     &expected_result_at_lsn_20[idx]
   11139            4 :                 );
   11140          200 :                 assert_eq!(
   11141          200 :                     tline
   11142          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11143          200 :                         .await
   11144          200 :                         .unwrap(),
   11145          200 :                     &expected_result_at_lsn_10[idx]
   11146            4 :                 );
   11147            4 :             }
   11148           40 :         };
   11149            4 : 
   11150            4 :         verify_result().await;
   11151            4 : 
   11152            4 :         let cancel = CancellationToken::new();
   11153            4 : 
   11154            4 :         tline
   11155            4 :             .compact_with_gc(
   11156            4 :                 &cancel,
   11157            4 :                 CompactOptions {
   11158            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11159            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11160            4 :                     ..Default::default()
   11161            4 :                 },
   11162            4 :                 &ctx,
   11163            4 :             )
   11164            4 :             .await
   11165            4 :             .unwrap();
   11166            4 :         verify_result().await;
   11167            4 : 
   11168            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11169            4 :         check_layer_map_key_eq(
   11170            4 :             all_layers,
   11171            4 :             vec![
   11172            4 :                 // The original image layer, not compacted
   11173            4 :                 PersistentLayerKey {
   11174            4 :                     key_range: get_key(0)..get_key(10),
   11175            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11176            4 :                     is_delta: false,
   11177            4 :                 },
   11178            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11179            4 :                 // the layer 0x28-0x30 into one.
   11180            4 :                 PersistentLayerKey {
   11181            4 :                     key_range: get_key(1)..get_key(2),
   11182            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11183            4 :                     is_delta: true,
   11184            4 :                 },
   11185            4 :                 // Above the upper bound and untouched
   11186            4 :                 PersistentLayerKey {
   11187            4 :                     key_range: get_key(1)..get_key(2),
   11188            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11189            4 :                     is_delta: true,
   11190            4 :                 },
   11191            4 :                 // This layer is untouched
   11192            4 :                 PersistentLayerKey {
   11193            4 :                     key_range: get_key(8)..get_key(10),
   11194            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11195            4 :                     is_delta: true,
   11196            4 :                 },
   11197            4 :             ],
   11198            4 :         );
   11199            4 : 
   11200            4 :         tline
   11201            4 :             .compact_with_gc(
   11202            4 :                 &cancel,
   11203            4 :                 CompactOptions {
   11204            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11205            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11206            4 :                     ..Default::default()
   11207            4 :                 },
   11208            4 :                 &ctx,
   11209            4 :             )
   11210            4 :             .await
   11211            4 :             .unwrap();
   11212            4 :         verify_result().await;
   11213            4 : 
   11214            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11215            4 :         check_layer_map_key_eq(
   11216            4 :             all_layers,
   11217            4 :             vec![
   11218            4 :                 // The original image layer, not compacted
   11219            4 :                 PersistentLayerKey {
   11220            4 :                     key_range: get_key(0)..get_key(10),
   11221            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11222            4 :                     is_delta: false,
   11223            4 :                 },
   11224            4 :                 // Not in the compaction key range, uncompacted
   11225            4 :                 PersistentLayerKey {
   11226            4 :                     key_range: get_key(1)..get_key(2),
   11227            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11228            4 :                     is_delta: true,
   11229            4 :                 },
   11230            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11231            4 :                 PersistentLayerKey {
   11232            4 :                     key_range: get_key(1)..get_key(2),
   11233            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11234            4 :                     is_delta: true,
   11235            4 :                 },
   11236            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11237            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11238            4 :                 // becomes 0x50.
   11239            4 :                 PersistentLayerKey {
   11240            4 :                     key_range: get_key(8)..get_key(10),
   11241            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11242            4 :                     is_delta: true,
   11243            4 :                 },
   11244            4 :             ],
   11245            4 :         );
   11246            4 : 
   11247            4 :         // compact again
   11248            4 :         tline
   11249            4 :             .compact_with_gc(
   11250            4 :                 &cancel,
   11251            4 :                 CompactOptions {
   11252            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11253            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11254            4 :                     ..Default::default()
   11255            4 :                 },
   11256            4 :                 &ctx,
   11257            4 :             )
   11258            4 :             .await
   11259            4 :             .unwrap();
   11260            4 :         verify_result().await;
   11261            4 : 
   11262            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11263            4 :         check_layer_map_key_eq(
   11264            4 :             all_layers,
   11265            4 :             vec![
   11266            4 :                 // The original image layer, not compacted
   11267            4 :                 PersistentLayerKey {
   11268            4 :                     key_range: get_key(0)..get_key(10),
   11269            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11270            4 :                     is_delta: false,
   11271            4 :                 },
   11272            4 :                 // The range gets compacted
   11273            4 :                 PersistentLayerKey {
   11274            4 :                     key_range: get_key(1)..get_key(2),
   11275            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11276            4 :                     is_delta: true,
   11277            4 :                 },
   11278            4 :                 // Not touched during this iteration of compaction
   11279            4 :                 PersistentLayerKey {
   11280            4 :                     key_range: get_key(8)..get_key(10),
   11281            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11282            4 :                     is_delta: true,
   11283            4 :                 },
   11284            4 :             ],
   11285            4 :         );
   11286            4 : 
   11287            4 :         // final full compaction
   11288            4 :         tline
   11289            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11290            4 :             .await
   11291            4 :             .unwrap();
   11292            4 :         verify_result().await;
   11293            4 : 
   11294            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11295            4 :         check_layer_map_key_eq(
   11296            4 :             all_layers,
   11297            4 :             vec![
   11298            4 :                 // The compacted image layer (full key range)
   11299            4 :                 PersistentLayerKey {
   11300            4 :                     key_range: Key::MIN..Key::MAX,
   11301            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11302            4 :                     is_delta: false,
   11303            4 :                 },
   11304            4 :                 // All other data in the delta layer
   11305            4 :                 PersistentLayerKey {
   11306            4 :                     key_range: get_key(1)..get_key(10),
   11307            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11308            4 :                     is_delta: true,
   11309            4 :                 },
   11310            4 :             ],
   11311            4 :         );
   11312            4 : 
   11313            4 :         Ok(())
   11314            4 :     }
   11315              : }
        

Generated by: LCOV version 2.1-beta