LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: d427f6f28cacba33c85e3c88c25b596f8e14b0f1.info Lines: 76.3 % 8558 6532
Test Date: 2025-02-15 14:15:22 Functions: 59.4 % 448 266

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

Generated by: LCOV version 2.1-beta