LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 71d97c4519b9017c5903db4dfe4edf4a84645500.info Lines: 75.7 % 8344 6314
Test Date: 2024-12-19 16:48:20 Functions: 60.0 % 438 263

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use anyhow::{bail, Context};
      16              : use arc_swap::ArcSwap;
      17              : use camino::Utf8Path;
      18              : use camino::Utf8PathBuf;
      19              : use chrono::NaiveDateTime;
      20              : use enumset::EnumSet;
      21              : use futures::stream::FuturesUnordered;
      22              : use futures::StreamExt;
      23              : use pageserver_api::models;
      24              : use pageserver_api::models::LsnLease;
      25              : use pageserver_api::models::TimelineArchivalState;
      26              : use pageserver_api::models::TimelineState;
      27              : use pageserver_api::models::TopTenantShardItem;
      28              : use pageserver_api::models::WalRedoManagerStatus;
      29              : use pageserver_api::shard::ShardIdentity;
      30              : use pageserver_api::shard::ShardStripeSize;
      31              : use pageserver_api::shard::TenantShardId;
      32              : use remote_storage::DownloadError;
      33              : use remote_storage::GenericRemoteStorage;
      34              : use remote_storage::TimeoutOrCancel;
      35              : use remote_timeline_client::manifest::{
      36              :     OffloadedTimelineManifest, TenantManifest, LATEST_TENANT_MANIFEST_VERSION,
      37              : };
      38              : use remote_timeline_client::UploadQueueNotReadyError;
      39              : use std::collections::BTreeMap;
      40              : use std::collections::VecDeque;
      41              : use std::fmt;
      42              : use std::future::Future;
      43              : use std::sync::atomic::AtomicBool;
      44              : use std::sync::Weak;
      45              : use std::time::SystemTime;
      46              : use storage_broker::BrokerClientChannel;
      47              : use timeline::compaction::GcCompactJob;
      48              : use timeline::compaction::ScheduledCompactionTask;
      49              : use timeline::import_pgdata;
      50              : use timeline::offload::offload_timeline;
      51              : use timeline::CompactFlags;
      52              : use timeline::CompactOptions;
      53              : use timeline::CompactionError;
      54              : use timeline::ShutdownMode;
      55              : use tokio::io::BufReader;
      56              : use tokio::sync::watch;
      57              : use tokio::task::JoinSet;
      58              : use tokio_util::sync::CancellationToken;
      59              : use tracing::*;
      60              : use upload_queue::NotInitialized;
      61              : use utils::backoff;
      62              : use utils::circuit_breaker::CircuitBreaker;
      63              : use utils::completion;
      64              : use utils::crashsafe::path_with_suffix_extension;
      65              : use utils::failpoint_support;
      66              : use utils::fs_ext;
      67              : use utils::pausable_failpoint;
      68              : use utils::sync::gate::Gate;
      69              : use utils::sync::gate::GateGuard;
      70              : use utils::timeout::timeout_cancellable;
      71              : use utils::timeout::TimeoutCancellableError;
      72              : use utils::try_rcu::ArcSwapExt;
      73              : use utils::zstd::create_zst_tarball;
      74              : use utils::zstd::extract_zst_tarball;
      75              : 
      76              : use self::config::AttachedLocationConfig;
      77              : use self::config::AttachmentMode;
      78              : use self::config::LocationConf;
      79              : use self::config::TenantConf;
      80              : use self::metadata::TimelineMetadata;
      81              : use self::mgr::GetActiveTenantError;
      82              : use self::mgr::GetTenantError;
      83              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      84              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      85              : use self::timeline::uninit::TimelineCreateGuard;
      86              : use self::timeline::uninit::TimelineExclusionError;
      87              : use self::timeline::uninit::UninitializedTimeline;
      88              : use self::timeline::EvictionTaskTenantState;
      89              : use self::timeline::GcCutoffs;
      90              : use self::timeline::TimelineDeleteProgress;
      91              : use self::timeline::TimelineResources;
      92              : use self::timeline::WaitLsnError;
      93              : use crate::config::PageServerConf;
      94              : use crate::context::{DownloadBehavior, RequestContext};
      95              : use crate::deletion_queue::DeletionQueueClient;
      96              : use crate::deletion_queue::DeletionQueueError;
      97              : use crate::import_datadir;
      98              : use crate::is_uninit_mark;
      99              : use crate::l0_flush::L0FlushGlobalState;
     100              : use crate::metrics::TENANT;
     101              : use crate::metrics::{
     102              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
     103              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
     104              : };
     105              : use crate::task_mgr;
     106              : use crate::task_mgr::TaskKind;
     107              : use crate::tenant::config::LocationMode;
     108              : use crate::tenant::config::TenantConfOpt;
     109              : use crate::tenant::gc_result::GcResult;
     110              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     111              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     112              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     113              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     114              : use crate::tenant::storage_layer::DeltaLayer;
     115              : use crate::tenant::storage_layer::ImageLayer;
     116              : use crate::walingest::WalLagCooldown;
     117              : use crate::walredo;
     118              : use crate::InitializationOrder;
     119              : use std::collections::hash_map::Entry;
     120              : use std::collections::HashMap;
     121              : use std::collections::HashSet;
     122              : use std::fmt::Debug;
     123              : use std::fmt::Display;
     124              : use std::fs;
     125              : use std::fs::File;
     126              : use std::sync::atomic::{AtomicU64, Ordering};
     127              : use std::sync::Arc;
     128              : use std::sync::Mutex;
     129              : use std::time::{Duration, Instant};
     130              : 
     131              : use crate::span;
     132              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     133              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     134              : use crate::virtual_file::VirtualFile;
     135              : use crate::walredo::PostgresRedoManager;
     136              : use crate::TEMP_FILE_SUFFIX;
     137              : use once_cell::sync::Lazy;
     138              : pub use pageserver_api::models::TenantState;
     139              : use tokio::sync::Semaphore;
     140              : 
     141            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     142              : use utils::{
     143              :     crashsafe,
     144              :     generation::Generation,
     145              :     id::TimelineId,
     146              :     lsn::{Lsn, RecordLsn},
     147              : };
     148              : 
     149              : pub mod blob_io;
     150              : pub mod block_io;
     151              : pub mod vectored_blob_io;
     152              : 
     153              : pub mod disk_btree;
     154              : pub(crate) mod ephemeral_file;
     155              : pub mod layer_map;
     156              : 
     157              : pub mod metadata;
     158              : pub mod remote_timeline_client;
     159              : pub mod storage_layer;
     160              : 
     161              : pub mod checks;
     162              : pub mod config;
     163              : pub mod mgr;
     164              : pub mod secondary;
     165              : pub mod tasks;
     166              : pub mod upload_queue;
     167              : 
     168              : pub(crate) mod timeline;
     169              : 
     170              : pub mod size;
     171              : 
     172              : mod gc_block;
     173              : mod gc_result;
     174              : pub(crate) mod throttle;
     175              : 
     176              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     177              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     178              : 
     179              : // re-export for use in walreceiver
     180              : pub use crate::tenant::timeline::WalReceiverInfo;
     181              : 
     182              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     183              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     184              : 
     185              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     186              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     187              : 
     188              : /// References to shared objects that are passed into each tenant, such
     189              : /// as the shared remote storage client and process initialization state.
     190              : #[derive(Clone)]
     191              : pub struct TenantSharedResources {
     192              :     pub broker_client: storage_broker::BrokerClientChannel,
     193              :     pub remote_storage: GenericRemoteStorage,
     194              :     pub deletion_queue_client: DeletionQueueClient,
     195              :     pub l0_flush_global_state: L0FlushGlobalState,
     196              : }
     197              : 
     198              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     199              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     200              : /// in this struct.
     201              : #[derive(Clone)]
     202              : pub(super) struct AttachedTenantConf {
     203              :     tenant_conf: TenantConfOpt,
     204              :     location: AttachedLocationConfig,
     205              :     /// The deadline before which we are blocked from GC so that
     206              :     /// leases have a chance to be renewed.
     207              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     208              : }
     209              : 
     210              : impl AttachedTenantConf {
     211          196 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     212              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     213              :         //
     214              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     215              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     216              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     217          196 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     218          196 :             Some(
     219          196 :                 tokio::time::Instant::now()
     220          196 :                     + tenant_conf
     221          196 :                         .lsn_lease_length
     222          196 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     223          196 :             )
     224              :         } else {
     225              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     226              :             // because we don't do GC in these modes.
     227            0 :             None
     228              :         };
     229              : 
     230          196 :         Self {
     231          196 :             tenant_conf,
     232          196 :             location,
     233          196 :             lsn_lease_deadline,
     234          196 :         }
     235          196 :     }
     236              : 
     237          196 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     238          196 :         match &location_conf.mode {
     239          196 :             LocationMode::Attached(attach_conf) => {
     240          196 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     241              :             }
     242              :             LocationMode::Secondary(_) => {
     243            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     244              :             }
     245              :         }
     246          196 :     }
     247              : 
     248          762 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     249          762 :         self.lsn_lease_deadline
     250          762 :             .map(|d| tokio::time::Instant::now() < d)
     251          762 :             .unwrap_or(false)
     252          762 :     }
     253              : }
     254              : struct TimelinePreload {
     255              :     timeline_id: TimelineId,
     256              :     client: RemoteTimelineClient,
     257              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     258              : }
     259              : 
     260              : pub(crate) struct TenantPreload {
     261              :     tenant_manifest: TenantManifest,
     262              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     263              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     264              : }
     265              : 
     266              : /// When we spawn a tenant, there is a special mode for tenant creation that
     267              : /// avoids trying to read anything from remote storage.
     268              : pub(crate) enum SpawnMode {
     269              :     /// Activate as soon as possible
     270              :     Eager,
     271              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     272              :     Lazy,
     273              : }
     274              : 
     275              : ///
     276              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     277              : ///
     278              : pub struct Tenant {
     279              :     // Global pageserver config parameters
     280              :     pub conf: &'static PageServerConf,
     281              : 
     282              :     /// The value creation timestamp, used to measure activation delay, see:
     283              :     /// <https://github.com/neondatabase/neon/issues/4025>
     284              :     constructed_at: Instant,
     285              : 
     286              :     state: watch::Sender<TenantState>,
     287              : 
     288              :     // Overridden tenant-specific config parameters.
     289              :     // We keep TenantConfOpt sturct here to preserve the information
     290              :     // about parameters that are not set.
     291              :     // This is necessary to allow global config updates.
     292              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     293              : 
     294              :     tenant_shard_id: TenantShardId,
     295              : 
     296              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     297              :     shard_identity: ShardIdentity,
     298              : 
     299              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     300              :     /// Does not change over the lifetime of the [`Tenant`] object.
     301              :     ///
     302              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     303              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     304              :     generation: Generation,
     305              : 
     306              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     307              : 
     308              :     /// During timeline creation, we first insert the TimelineId to the
     309              :     /// creating map, then `timelines`, then remove it from the creating map.
     310              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     311              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     312              : 
     313              :     /// Possibly offloaded and archived timelines
     314              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     315              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     316              : 
     317              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     318              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     319              :     /// each other (this could be optimized to coalesce writes if necessary).
     320              :     ///
     321              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     322              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     323              : 
     324              :     // This mutex prevents creation of new timelines during GC.
     325              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     326              :     // `timelines` mutex during all GC iteration
     327              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     328              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     329              :     // timeout...
     330              :     gc_cs: tokio::sync::Mutex<()>,
     331              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     332              : 
     333              :     // provides access to timeline data sitting in the remote storage
     334              :     pub(crate) remote_storage: GenericRemoteStorage,
     335              : 
     336              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     337              :     deletion_queue_client: DeletionQueueClient,
     338              : 
     339              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     340              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     341              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     342              : 
     343              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     344              : 
     345              :     /// Track repeated failures to compact, so that we can back off.
     346              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     347              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     348              : 
     349              :     /// Scheduled compaction tasks. Currently, this can only be populated by triggering
     350              :     /// a manual gc-compaction from the manual compaction API.
     351              :     scheduled_compaction_tasks:
     352              :         std::sync::Mutex<HashMap<TimelineId, VecDeque<ScheduledCompactionTask>>>,
     353              : 
     354              :     /// If the tenant is in Activating state, notify this to encourage it
     355              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     356              :     /// background warmup.
     357              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     358              : 
     359              :     /// Time it took for the tenant to activate. Zero if not active yet.
     360              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     361              : 
     362              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     363              :     // Timelines' cancellation token.
     364              :     pub(crate) cancel: CancellationToken,
     365              : 
     366              :     // Users of the Tenant such as the page service must take this Gate to avoid
     367              :     // trying to use a Tenant which is shutting down.
     368              :     pub(crate) gate: Gate,
     369              : 
     370              :     /// Throttle applied at the top of [`Timeline::get`].
     371              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     372              :     pub(crate) pagestream_throttle:
     373              :         Arc<throttle::Throttle<crate::metrics::tenant_throttling::Pagestream>>,
     374              : 
     375              :     /// An ongoing timeline detach concurrency limiter.
     376              :     ///
     377              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     378              :     /// to have two running at the same time. A different one can be started if an earlier one
     379              :     /// has failed for whatever reason.
     380              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     381              : 
     382              :     /// `index_part.json` based gc blocking reason tracking.
     383              :     ///
     384              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     385              :     /// proceeding.
     386              :     pub(crate) gc_block: gc_block::GcBlock,
     387              : 
     388              :     l0_flush_global_state: L0FlushGlobalState,
     389              : }
     390              : impl std::fmt::Debug for Tenant {
     391            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     392            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     393            0 :     }
     394              : }
     395              : 
     396              : pub(crate) enum WalRedoManager {
     397              :     Prod(WalredoManagerId, PostgresRedoManager),
     398              :     #[cfg(test)]
     399              :     Test(harness::TestRedoManager),
     400              : }
     401              : 
     402              : #[derive(thiserror::Error, Debug)]
     403              : #[error("pageserver is shutting down")]
     404              : pub(crate) struct GlobalShutDown;
     405              : 
     406              : impl WalRedoManager {
     407            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     408            0 :         let id = WalredoManagerId::next();
     409            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     410            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     411            0 :         match &mut *guard {
     412            0 :             Some(map) => {
     413            0 :                 map.insert(id, Arc::downgrade(&arc));
     414            0 :                 Ok(arc)
     415              :             }
     416            0 :             None => Err(GlobalShutDown),
     417              :         }
     418            0 :     }
     419              : }
     420              : 
     421              : impl Drop for WalRedoManager {
     422           10 :     fn drop(&mut self) {
     423           10 :         match self {
     424            0 :             Self::Prod(id, _) => {
     425            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     426            0 :                 if let Some(map) = &mut *guard {
     427            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     428            0 :                 }
     429              :             }
     430              :             #[cfg(test)]
     431           10 :             Self::Test(_) => {
     432           10 :                 // Not applicable to test redo manager
     433           10 :             }
     434              :         }
     435           10 :     }
     436              : }
     437              : 
     438              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     439              : /// the walredo processes outside of the regular order.
     440              : ///
     441              : /// This is necessary to work around a systemd bug where it freezes if there are
     442              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     443              : #[allow(clippy::type_complexity)]
     444              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     445              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     446            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     447              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     448              : pub(crate) struct WalredoManagerId(u64);
     449              : impl WalredoManagerId {
     450            0 :     pub fn next() -> Self {
     451              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     452            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     453            0 :         if id == 0 {
     454            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     455            0 :         }
     456            0 :         Self(id)
     457            0 :     }
     458              : }
     459              : 
     460              : #[cfg(test)]
     461              : impl From<harness::TestRedoManager> for WalRedoManager {
     462          196 :     fn from(mgr: harness::TestRedoManager) -> Self {
     463          196 :         Self::Test(mgr)
     464          196 :     }
     465              : }
     466              : 
     467              : impl WalRedoManager {
     468            6 :     pub(crate) async fn shutdown(&self) -> bool {
     469            6 :         match self {
     470            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     471              :             #[cfg(test)]
     472              :             Self::Test(_) => {
     473              :                 // Not applicable to test redo manager
     474            6 :                 true
     475              :             }
     476              :         }
     477            6 :     }
     478              : 
     479            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     480            0 :         match self {
     481            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     482            0 :             #[cfg(test)]
     483            0 :             Self::Test(_) => {
     484            0 :                 // Not applicable to test redo manager
     485            0 :             }
     486            0 :         }
     487            0 :     }
     488              : 
     489              :     /// # Cancel-Safety
     490              :     ///
     491              :     /// This method is cancellation-safe.
     492          520 :     pub async fn request_redo(
     493          520 :         &self,
     494          520 :         key: pageserver_api::key::Key,
     495          520 :         lsn: Lsn,
     496          520 :         base_img: Option<(Lsn, bytes::Bytes)>,
     497          520 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     498          520 :         pg_version: u32,
     499          520 :     ) -> Result<bytes::Bytes, walredo::Error> {
     500          520 :         match self {
     501            0 :             Self::Prod(_, mgr) => {
     502            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     503            0 :                     .await
     504              :             }
     505              :             #[cfg(test)]
     506          520 :             Self::Test(mgr) => {
     507          520 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     508          520 :                     .await
     509              :             }
     510              :         }
     511          520 :     }
     512              : 
     513            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     514            0 :         match self {
     515            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     516            0 :             #[cfg(test)]
     517            0 :             WalRedoManager::Test(_) => None,
     518            0 :         }
     519            0 :     }
     520              : }
     521              : 
     522              : /// A very lightweight memory representation of an offloaded timeline.
     523              : ///
     524              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     525              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     526              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     527              : /// more offloaded timelines than we can manage ones that aren't.
     528              : pub struct OffloadedTimeline {
     529              :     pub tenant_shard_id: TenantShardId,
     530              :     pub timeline_id: TimelineId,
     531              :     pub ancestor_timeline_id: Option<TimelineId>,
     532              :     /// Whether to retain the branch lsn at the ancestor or not
     533              :     pub ancestor_retain_lsn: Option<Lsn>,
     534              : 
     535              :     /// When the timeline was archived.
     536              :     ///
     537              :     /// Present for future flattening deliberations.
     538              :     pub archived_at: NaiveDateTime,
     539              : 
     540              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     541              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     542              :     pub delete_progress: TimelineDeleteProgress,
     543              : 
     544              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     545              :     pub deleted_from_ancestor: AtomicBool,
     546              : }
     547              : 
     548              : impl OffloadedTimeline {
     549              :     /// Obtains an offloaded timeline from a given timeline object.
     550              :     ///
     551              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     552              :     /// the timeline is not in a stopped state.
     553              :     /// Panics if the timeline is not archived.
     554            2 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     555            2 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     556            2 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     557            2 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     558            2 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     559            2 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     560            2 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     561            2 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     562              :             } else {
     563            0 :                 (None, None)
     564              :             };
     565            2 :         let archived_at = timeline
     566            2 :             .remote_client
     567            2 :             .archived_at_stopped_queue()?
     568            2 :             .expect("must be called on an archived timeline");
     569            2 :         Ok(Self {
     570            2 :             tenant_shard_id: timeline.tenant_shard_id,
     571            2 :             timeline_id: timeline.timeline_id,
     572            2 :             ancestor_timeline_id,
     573            2 :             ancestor_retain_lsn,
     574            2 :             archived_at,
     575            2 : 
     576            2 :             delete_progress: timeline.delete_progress.clone(),
     577            2 :             deleted_from_ancestor: AtomicBool::new(false),
     578            2 :         })
     579            2 :     }
     580            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     581            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     582            0 :         // by the `initialize_gc_info` function.
     583            0 :         let OffloadedTimelineManifest {
     584            0 :             timeline_id,
     585            0 :             ancestor_timeline_id,
     586            0 :             ancestor_retain_lsn,
     587            0 :             archived_at,
     588            0 :         } = *manifest;
     589            0 :         Self {
     590            0 :             tenant_shard_id,
     591            0 :             timeline_id,
     592            0 :             ancestor_timeline_id,
     593            0 :             ancestor_retain_lsn,
     594            0 :             archived_at,
     595            0 :             delete_progress: TimelineDeleteProgress::default(),
     596            0 :             deleted_from_ancestor: AtomicBool::new(false),
     597            0 :         }
     598            0 :     }
     599            2 :     fn manifest(&self) -> OffloadedTimelineManifest {
     600            2 :         let Self {
     601            2 :             timeline_id,
     602            2 :             ancestor_timeline_id,
     603            2 :             ancestor_retain_lsn,
     604            2 :             archived_at,
     605            2 :             ..
     606            2 :         } = self;
     607            2 :         OffloadedTimelineManifest {
     608            2 :             timeline_id: *timeline_id,
     609            2 :             ancestor_timeline_id: *ancestor_timeline_id,
     610            2 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     611            2 :             archived_at: *archived_at,
     612            2 :         }
     613            2 :     }
     614              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     615            0 :     fn delete_from_ancestor_with_timelines(
     616            0 :         &self,
     617            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     618            0 :     ) {
     619            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     620            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     621              :         {
     622            0 :             if let Some((_, ancestor_timeline)) = timelines
     623            0 :                 .iter()
     624            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     625              :             {
     626            0 :                 let removal_happened = ancestor_timeline
     627            0 :                     .gc_info
     628            0 :                     .write()
     629            0 :                     .unwrap()
     630            0 :                     .remove_child_offloaded(self.timeline_id);
     631            0 :                 if !removal_happened {
     632            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     633            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     634            0 :                 }
     635            0 :             }
     636            0 :         }
     637            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     638            0 :     }
     639              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     640              :     ///
     641              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     642            2 :     fn defuse_for_tenant_drop(&self) {
     643            2 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     644            2 :     }
     645              : }
     646              : 
     647              : impl fmt::Debug for OffloadedTimeline {
     648            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     649            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     650            0 :     }
     651              : }
     652              : 
     653              : impl Drop for OffloadedTimeline {
     654            2 :     fn drop(&mut self) {
     655            2 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     656            0 :             tracing::warn!(
     657            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     658              :                 self.timeline_id
     659              :             );
     660            2 :         }
     661            2 :     }
     662              : }
     663              : 
     664              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     665              : pub enum MaybeOffloaded {
     666              :     Yes,
     667              :     No,
     668              : }
     669              : 
     670              : #[derive(Clone, Debug)]
     671              : pub enum TimelineOrOffloaded {
     672              :     Timeline(Arc<Timeline>),
     673              :     Offloaded(Arc<OffloadedTimeline>),
     674              : }
     675              : 
     676              : impl TimelineOrOffloaded {
     677            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     678            0 :         match self {
     679            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     680            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     681              :             }
     682            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     683            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     684              :             }
     685              :         }
     686            0 :     }
     687            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     688            0 :         self.arc_ref().tenant_shard_id()
     689            0 :     }
     690            0 :     pub fn timeline_id(&self) -> TimelineId {
     691            0 :         self.arc_ref().timeline_id()
     692            0 :     }
     693            2 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     694            2 :         match self {
     695            2 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     696            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     697              :         }
     698            2 :     }
     699            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     700            0 :         match self {
     701            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     702            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     703              :         }
     704            0 :     }
     705              : }
     706              : 
     707              : pub enum TimelineOrOffloadedArcRef<'a> {
     708              :     Timeline(&'a Arc<Timeline>),
     709              :     Offloaded(&'a Arc<OffloadedTimeline>),
     710              : }
     711              : 
     712              : impl TimelineOrOffloadedArcRef<'_> {
     713            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     714            0 :         match self {
     715            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     716            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     717              :         }
     718            0 :     }
     719            0 :     pub fn timeline_id(&self) -> TimelineId {
     720            0 :         match self {
     721            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     722            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     723              :         }
     724            0 :     }
     725              : }
     726              : 
     727              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     728            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     729            0 :         Self::Timeline(timeline)
     730            0 :     }
     731              : }
     732              : 
     733              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     734            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     735            0 :         Self::Offloaded(timeline)
     736            0 :     }
     737              : }
     738              : 
     739              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     740              : pub enum GetTimelineError {
     741              :     #[error("Timeline is shutting down")]
     742              :     ShuttingDown,
     743              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     744              :     NotActive {
     745              :         tenant_id: TenantShardId,
     746              :         timeline_id: TimelineId,
     747              :         state: TimelineState,
     748              :     },
     749              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     750              :     NotFound {
     751              :         tenant_id: TenantShardId,
     752              :         timeline_id: TimelineId,
     753              :     },
     754              : }
     755              : 
     756              : #[derive(Debug, thiserror::Error)]
     757              : pub enum LoadLocalTimelineError {
     758              :     #[error("FailedToLoad")]
     759              :     Load(#[source] anyhow::Error),
     760              :     #[error("FailedToResumeDeletion")]
     761              :     ResumeDeletion(#[source] anyhow::Error),
     762              : }
     763              : 
     764              : #[derive(thiserror::Error)]
     765              : pub enum DeleteTimelineError {
     766              :     #[error("NotFound")]
     767              :     NotFound,
     768              : 
     769              :     #[error("HasChildren")]
     770              :     HasChildren(Vec<TimelineId>),
     771              : 
     772              :     #[error("Timeline deletion is already in progress")]
     773              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     774              : 
     775              :     #[error("Cancelled")]
     776              :     Cancelled,
     777              : 
     778              :     #[error(transparent)]
     779              :     Other(#[from] anyhow::Error),
     780              : }
     781              : 
     782              : impl Debug for DeleteTimelineError {
     783            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     784            0 :         match self {
     785            0 :             Self::NotFound => write!(f, "NotFound"),
     786            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     787            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     788            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     789            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     790              :         }
     791            0 :     }
     792              : }
     793              : 
     794              : #[derive(thiserror::Error)]
     795              : pub enum TimelineArchivalError {
     796              :     #[error("NotFound")]
     797              :     NotFound,
     798              : 
     799              :     #[error("Timeout")]
     800              :     Timeout,
     801              : 
     802              :     #[error("Cancelled")]
     803              :     Cancelled,
     804              : 
     805              :     #[error("ancestor is archived: {}", .0)]
     806              :     HasArchivedParent(TimelineId),
     807              : 
     808              :     #[error("HasUnarchivedChildren")]
     809              :     HasUnarchivedChildren(Vec<TimelineId>),
     810              : 
     811              :     #[error("Timeline archival is already in progress")]
     812              :     AlreadyInProgress,
     813              : 
     814              :     #[error(transparent)]
     815              :     Other(anyhow::Error),
     816              : }
     817              : 
     818              : #[derive(thiserror::Error, Debug)]
     819              : pub(crate) enum TenantManifestError {
     820              :     #[error("Remote storage error: {0}")]
     821              :     RemoteStorage(anyhow::Error),
     822              : 
     823              :     #[error("Cancelled")]
     824              :     Cancelled,
     825              : }
     826              : 
     827              : impl From<TenantManifestError> for TimelineArchivalError {
     828            0 :     fn from(e: TenantManifestError) -> Self {
     829            0 :         match e {
     830            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     831            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     832              :         }
     833            0 :     }
     834              : }
     835              : 
     836              : impl Debug for TimelineArchivalError {
     837            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     838            0 :         match self {
     839            0 :             Self::NotFound => write!(f, "NotFound"),
     840            0 :             Self::Timeout => write!(f, "Timeout"),
     841            0 :             Self::Cancelled => write!(f, "Cancelled"),
     842            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     843            0 :             Self::HasUnarchivedChildren(c) => {
     844            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     845              :             }
     846            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     847            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     848              :         }
     849            0 :     }
     850              : }
     851              : 
     852              : pub enum SetStoppingError {
     853              :     AlreadyStopping(completion::Barrier),
     854              :     Broken,
     855              : }
     856              : 
     857              : impl Debug for SetStoppingError {
     858            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     859            0 :         match self {
     860            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     861            0 :             Self::Broken => write!(f, "Broken"),
     862              :         }
     863            0 :     }
     864              : }
     865              : 
     866              : /// Arguments to [`Tenant::create_timeline`].
     867              : ///
     868              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     869              : /// is `None`, the result of the timeline create call is not deterministic.
     870              : ///
     871              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     872              : #[derive(Debug)]
     873              : pub(crate) enum CreateTimelineParams {
     874              :     Bootstrap(CreateTimelineParamsBootstrap),
     875              :     Branch(CreateTimelineParamsBranch),
     876              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     877              : }
     878              : 
     879              : #[derive(Debug)]
     880              : pub(crate) struct CreateTimelineParamsBootstrap {
     881              :     pub(crate) new_timeline_id: TimelineId,
     882              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     883              :     pub(crate) pg_version: u32,
     884              : }
     885              : 
     886              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     887              : #[derive(Debug)]
     888              : pub(crate) struct CreateTimelineParamsBranch {
     889              :     pub(crate) new_timeline_id: TimelineId,
     890              :     pub(crate) ancestor_timeline_id: TimelineId,
     891              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     892              : }
     893              : 
     894              : #[derive(Debug)]
     895              : pub(crate) struct CreateTimelineParamsImportPgdata {
     896              :     pub(crate) new_timeline_id: TimelineId,
     897              :     pub(crate) location: import_pgdata::index_part_format::Location,
     898              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     899              : }
     900              : 
     901              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     902              : ///
     903              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     904              : ///
     905              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     906              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     907              : ///
     908              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     909              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     910              : ///
     911              : /// Notes:
     912              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     913              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     914              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     915              : ///
     916              : #[derive(Debug, Clone, PartialEq, Eq)]
     917              : pub(crate) enum CreateTimelineIdempotency {
     918              :     /// NB: special treatment, see comment in [`Self`].
     919              :     FailWithConflict,
     920              :     Bootstrap {
     921              :         pg_version: u32,
     922              :     },
     923              :     /// NB: branches always have the same `pg_version` as their ancestor.
     924              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     925              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     926              :     /// determining the child branch pg_version.
     927              :     Branch {
     928              :         ancestor_timeline_id: TimelineId,
     929              :         ancestor_start_lsn: Lsn,
     930              :     },
     931              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     932              : }
     933              : 
     934              : #[derive(Debug, Clone, PartialEq, Eq)]
     935              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     936              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     937              : }
     938              : 
     939              : /// What is returned by [`Tenant::start_creating_timeline`].
     940              : #[must_use]
     941              : enum StartCreatingTimelineResult {
     942              :     CreateGuard(TimelineCreateGuard),
     943              :     Idempotent(Arc<Timeline>),
     944              : }
     945              : 
     946              : enum TimelineInitAndSyncResult {
     947              :     ReadyToActivate(Arc<Timeline>),
     948              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     949              : }
     950              : 
     951              : impl TimelineInitAndSyncResult {
     952            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     953            0 :         match self {
     954            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     955            0 :             _ => None,
     956              :         }
     957            0 :     }
     958              : }
     959              : 
     960              : #[must_use]
     961              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     962              :     timeline: Arc<Timeline>,
     963              :     import_pgdata: import_pgdata::index_part_format::Root,
     964              :     guard: TimelineCreateGuard,
     965              : }
     966              : 
     967              : /// What is returned by [`Tenant::create_timeline`].
     968              : enum CreateTimelineResult {
     969              :     Created(Arc<Timeline>),
     970              :     Idempotent(Arc<Timeline>),
     971              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     972              :     /// we return this result, nor will this concrete object ever be added there.
     973              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     974              :     ImportSpawned(Arc<Timeline>),
     975              : }
     976              : 
     977              : impl CreateTimelineResult {
     978            0 :     fn discriminant(&self) -> &'static str {
     979            0 :         match self {
     980            0 :             Self::Created(_) => "Created",
     981            0 :             Self::Idempotent(_) => "Idempotent",
     982            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     983              :         }
     984            0 :     }
     985            0 :     fn timeline(&self) -> &Arc<Timeline> {
     986            0 :         match self {
     987            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     988            0 :         }
     989            0 :     }
     990              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     991              :     #[cfg(test)]
     992          230 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     993          230 :         match self {
     994          230 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     995          230 :         }
     996          230 :     }
     997              : }
     998              : 
     999              : #[derive(thiserror::Error, Debug)]
    1000              : pub enum CreateTimelineError {
    1001              :     #[error("creation of timeline with the given ID is in progress")]
    1002              :     AlreadyCreating,
    1003              :     #[error("timeline already exists with different parameters")]
    1004              :     Conflict,
    1005              :     #[error(transparent)]
    1006              :     AncestorLsn(anyhow::Error),
    1007              :     #[error("ancestor timeline is not active")]
    1008              :     AncestorNotActive,
    1009              :     #[error("ancestor timeline is archived")]
    1010              :     AncestorArchived,
    1011              :     #[error("tenant shutting down")]
    1012              :     ShuttingDown,
    1013              :     #[error(transparent)]
    1014              :     Other(#[from] anyhow::Error),
    1015              : }
    1016              : 
    1017              : #[derive(thiserror::Error, Debug)]
    1018              : pub enum InitdbError {
    1019              :     #[error("Operation was cancelled")]
    1020              :     Cancelled,
    1021              :     #[error(transparent)]
    1022              :     Other(anyhow::Error),
    1023              :     #[error(transparent)]
    1024              :     Inner(postgres_initdb::Error),
    1025              : }
    1026              : 
    1027              : enum CreateTimelineCause {
    1028              :     Load,
    1029              :     Delete,
    1030              : }
    1031              : 
    1032              : enum LoadTimelineCause {
    1033              :     Attach,
    1034              :     Unoffload,
    1035              :     ImportPgdata {
    1036              :         create_guard: TimelineCreateGuard,
    1037              :         activate: ActivateTimelineArgs,
    1038              :     },
    1039              : }
    1040              : 
    1041              : #[derive(thiserror::Error, Debug)]
    1042              : pub(crate) enum GcError {
    1043              :     // The tenant is shutting down
    1044              :     #[error("tenant shutting down")]
    1045              :     TenantCancelled,
    1046              : 
    1047              :     // The tenant is shutting down
    1048              :     #[error("timeline shutting down")]
    1049              :     TimelineCancelled,
    1050              : 
    1051              :     // The tenant is in a state inelegible to run GC
    1052              :     #[error("not active")]
    1053              :     NotActive,
    1054              : 
    1055              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1056              :     #[error("not active")]
    1057              :     BadLsn { why: String },
    1058              : 
    1059              :     // A remote storage error while scheduling updates after compaction
    1060              :     #[error(transparent)]
    1061              :     Remote(anyhow::Error),
    1062              : 
    1063              :     // An error reading while calculating GC cutoffs
    1064              :     #[error(transparent)]
    1065              :     GcCutoffs(PageReconstructError),
    1066              : 
    1067              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1068              :     #[error("timeline not found")]
    1069              :     TimelineNotFound,
    1070              : }
    1071              : 
    1072              : impl From<PageReconstructError> for GcError {
    1073            0 :     fn from(value: PageReconstructError) -> Self {
    1074            0 :         match value {
    1075            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1076            0 :             other => Self::GcCutoffs(other),
    1077              :         }
    1078            0 :     }
    1079              : }
    1080              : 
    1081              : impl From<NotInitialized> for GcError {
    1082            0 :     fn from(value: NotInitialized) -> Self {
    1083            0 :         match value {
    1084            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1085            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1086              :         }
    1087            0 :     }
    1088              : }
    1089              : 
    1090              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1091            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1092            0 :         GcError::TimelineCancelled
    1093            0 :     }
    1094              : }
    1095              : 
    1096              : #[derive(thiserror::Error, Debug)]
    1097              : pub(crate) enum LoadConfigError {
    1098              :     #[error("TOML deserialization error: '{0}'")]
    1099              :     DeserializeToml(#[from] toml_edit::de::Error),
    1100              : 
    1101              :     #[error("Config not found at {0}")]
    1102              :     NotFound(Utf8PathBuf),
    1103              : }
    1104              : 
    1105              : impl Tenant {
    1106              :     /// Yet another helper for timeline initialization.
    1107              :     ///
    1108              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1109              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1110              :     /// - Downloads remote index file and adds remote files to the layer map
    1111              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1112              :     ///
    1113              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1114              :     /// it is marked as Active.
    1115              :     #[allow(clippy::too_many_arguments)]
    1116            6 :     async fn timeline_init_and_sync(
    1117            6 :         self: &Arc<Self>,
    1118            6 :         timeline_id: TimelineId,
    1119            6 :         resources: TimelineResources,
    1120            6 :         mut index_part: IndexPart,
    1121            6 :         metadata: TimelineMetadata,
    1122            6 :         ancestor: Option<Arc<Timeline>>,
    1123            6 :         cause: LoadTimelineCause,
    1124            6 :         ctx: &RequestContext,
    1125            6 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1126            6 :         let tenant_id = self.tenant_shard_id;
    1127            6 : 
    1128            6 :         let import_pgdata = index_part.import_pgdata.take();
    1129            6 :         let idempotency = match &import_pgdata {
    1130            0 :             Some(import_pgdata) => {
    1131            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1132            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1133            0 :                 })
    1134              :             }
    1135              :             None => {
    1136            6 :                 if metadata.ancestor_timeline().is_none() {
    1137            4 :                     CreateTimelineIdempotency::Bootstrap {
    1138            4 :                         pg_version: metadata.pg_version(),
    1139            4 :                     }
    1140              :                 } else {
    1141            2 :                     CreateTimelineIdempotency::Branch {
    1142            2 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1143            2 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1144            2 :                     }
    1145              :                 }
    1146              :             }
    1147              :         };
    1148              : 
    1149            6 :         let timeline = self.create_timeline_struct(
    1150            6 :             timeline_id,
    1151            6 :             &metadata,
    1152            6 :             ancestor.clone(),
    1153            6 :             resources,
    1154            6 :             CreateTimelineCause::Load,
    1155            6 :             idempotency.clone(),
    1156            6 :         )?;
    1157            6 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1158            6 :         anyhow::ensure!(
    1159            6 :             disk_consistent_lsn.is_valid(),
    1160            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1161              :         );
    1162            6 :         assert_eq!(
    1163            6 :             disk_consistent_lsn,
    1164            6 :             metadata.disk_consistent_lsn(),
    1165            0 :             "these are used interchangeably"
    1166              :         );
    1167              : 
    1168            6 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1169              : 
    1170            6 :         timeline
    1171            6 :             .load_layer_map(disk_consistent_lsn, index_part)
    1172            6 :             .await
    1173            6 :             .with_context(|| {
    1174            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1175            6 :             })?;
    1176              : 
    1177            0 :         match import_pgdata {
    1178            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1179            0 :                 match cause {
    1180            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1181              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1182            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1183              :                     }
    1184              :                 }
    1185            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1186            0 :                 if !guard.insert(timeline_id) {
    1187              :                     // We should never try and load the same timeline twice during startup
    1188            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1189            0 :                 }
    1190            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1191            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1192            0 :                     owning_tenant: self.clone(),
    1193            0 :                     timeline_id,
    1194            0 :                     idempotency,
    1195            0 :                     // The users of this specific return value don't need the timline_path in there.
    1196            0 :                     timeline_path: timeline
    1197            0 :                         .conf
    1198            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1199            0 :                 };
    1200            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1201            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1202            0 :                         timeline,
    1203            0 :                         import_pgdata,
    1204            0 :                         guard: timeline_create_guard,
    1205            0 :                     },
    1206            0 :                 ))
    1207              :             }
    1208              :             Some(_) | None => {
    1209              :                 {
    1210            6 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1211            6 :                     match timelines_accessor.entry(timeline_id) {
    1212              :                         // We should never try and load the same timeline twice during startup
    1213              :                         Entry::Occupied(_) => {
    1214            0 :                             unreachable!(
    1215            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1216            0 :                         );
    1217              :                         }
    1218            6 :                         Entry::Vacant(v) => {
    1219            6 :                             v.insert(Arc::clone(&timeline));
    1220            6 :                             timeline.maybe_spawn_flush_loop();
    1221            6 :                         }
    1222              :                     }
    1223              :                 }
    1224              : 
    1225              :                 // Sanity check: a timeline should have some content.
    1226            6 :                 anyhow::ensure!(
    1227            6 :                     ancestor.is_some()
    1228            4 :                         || timeline
    1229            4 :                             .layers
    1230            4 :                             .read()
    1231            4 :                             .await
    1232            4 :                             .layer_map()
    1233            4 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1234            4 :                             .iter_historic_layers()
    1235            4 :                             .next()
    1236            4 :                             .is_some(),
    1237            0 :                     "Timeline has no ancestor and no layer files"
    1238              :                 );
    1239              : 
    1240            6 :                 match cause {
    1241            6 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1242              :                     LoadTimelineCause::ImportPgdata {
    1243            0 :                         create_guard,
    1244            0 :                         activate,
    1245            0 :                     } => {
    1246            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1247            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1248            0 :                         match activate {
    1249            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1250            0 :                                 info!("activating timeline after reload from pgdata import task");
    1251            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1252              :                             }
    1253            0 :                             ActivateTimelineArgs::No => (),
    1254              :                         }
    1255            0 :                         drop(create_guard);
    1256              :                     }
    1257              :                 }
    1258              : 
    1259            6 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1260              :             }
    1261              :         }
    1262            6 :     }
    1263              : 
    1264              :     /// Attach a tenant that's available in cloud storage.
    1265              :     ///
    1266              :     /// This returns quickly, after just creating the in-memory object
    1267              :     /// Tenant struct and launching a background task to download
    1268              :     /// the remote index files.  On return, the tenant is most likely still in
    1269              :     /// Attaching state, and it will become Active once the background task
    1270              :     /// finishes. You can use wait_until_active() to wait for the task to
    1271              :     /// complete.
    1272              :     ///
    1273              :     #[allow(clippy::too_many_arguments)]
    1274            0 :     pub(crate) fn spawn(
    1275            0 :         conf: &'static PageServerConf,
    1276            0 :         tenant_shard_id: TenantShardId,
    1277            0 :         resources: TenantSharedResources,
    1278            0 :         attached_conf: AttachedTenantConf,
    1279            0 :         shard_identity: ShardIdentity,
    1280            0 :         init_order: Option<InitializationOrder>,
    1281            0 :         mode: SpawnMode,
    1282            0 :         ctx: &RequestContext,
    1283            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1284            0 :         let wal_redo_manager =
    1285            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1286              : 
    1287              :         let TenantSharedResources {
    1288            0 :             broker_client,
    1289            0 :             remote_storage,
    1290            0 :             deletion_queue_client,
    1291            0 :             l0_flush_global_state,
    1292            0 :         } = resources;
    1293            0 : 
    1294            0 :         let attach_mode = attached_conf.location.attach_mode;
    1295            0 :         let generation = attached_conf.location.generation;
    1296            0 : 
    1297            0 :         let tenant = Arc::new(Tenant::new(
    1298            0 :             TenantState::Attaching,
    1299            0 :             conf,
    1300            0 :             attached_conf,
    1301            0 :             shard_identity,
    1302            0 :             Some(wal_redo_manager),
    1303            0 :             tenant_shard_id,
    1304            0 :             remote_storage.clone(),
    1305            0 :             deletion_queue_client,
    1306            0 :             l0_flush_global_state,
    1307            0 :         ));
    1308            0 : 
    1309            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1310            0 :         // we shut down while attaching.
    1311            0 :         let attach_gate_guard = tenant
    1312            0 :             .gate
    1313            0 :             .enter()
    1314            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1315            0 : 
    1316            0 :         // Do all the hard work in the background
    1317            0 :         let tenant_clone = Arc::clone(&tenant);
    1318            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1319            0 :         task_mgr::spawn(
    1320            0 :             &tokio::runtime::Handle::current(),
    1321            0 :             TaskKind::Attach,
    1322            0 :             tenant_shard_id,
    1323            0 :             None,
    1324            0 :             "attach tenant",
    1325            0 :             async move {
    1326            0 : 
    1327            0 :                 info!(
    1328              :                     ?attach_mode,
    1329            0 :                     "Attaching tenant"
    1330              :                 );
    1331              : 
    1332            0 :                 let _gate_guard = attach_gate_guard;
    1333            0 : 
    1334            0 :                 // Is this tenant being spawned as part of process startup?
    1335            0 :                 let starting_up = init_order.is_some();
    1336            0 :                 scopeguard::defer! {
    1337            0 :                     if starting_up {
    1338            0 :                         TENANT.startup_complete.inc();
    1339            0 :                     }
    1340            0 :                 }
    1341              : 
    1342              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1343              :                 enum BrokenVerbosity {
    1344              :                     Error,
    1345              :                     Info
    1346              :                 }
    1347            0 :                 let make_broken =
    1348            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1349            0 :                         match verbosity {
    1350              :                             BrokenVerbosity::Info => {
    1351            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1352              :                             },
    1353              :                             BrokenVerbosity::Error => {
    1354            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1355              :                             }
    1356              :                         }
    1357            0 :                         t.state.send_modify(|state| {
    1358            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1359            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1360            0 :                             assert!(
    1361            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1362            0 :                                 "the attach task owns the tenant state until activation is complete"
    1363              :                             );
    1364              : 
    1365            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1366            0 :                         });
    1367            0 :                     };
    1368              : 
    1369              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1370            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1371            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1372            0 :                     return Ok(());
    1373            0 :                 }
    1374            0 : 
    1375            0 :                 let mut init_order = init_order;
    1376            0 :                 // take the completion because initial tenant loading will complete when all of
    1377            0 :                 // these tasks complete.
    1378            0 :                 let _completion = init_order
    1379            0 :                     .as_mut()
    1380            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1381            0 :                 let remote_load_completion = init_order
    1382            0 :                     .as_mut()
    1383            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1384              : 
    1385              :                 enum AttachType<'a> {
    1386              :                     /// We are attaching this tenant lazily in the background.
    1387              :                     Warmup {
    1388              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1389              :                         during_startup: bool
    1390              :                     },
    1391              :                     /// We are attaching this tenant as soon as we can, because for example an
    1392              :                     /// endpoint tried to access it.
    1393              :                     OnDemand,
    1394              :                     /// During normal operations after startup, we are attaching a tenant, and
    1395              :                     /// eager attach was requested.
    1396              :                     Normal,
    1397              :                 }
    1398              : 
    1399            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1400              :                     // Before doing any I/O, wait for at least one of:
    1401              :                     // - A client attempting to access to this tenant (on-demand loading)
    1402              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1403              : 
    1404            0 :                     tokio::select!(
    1405            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1406            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1407            0 :                             tracing::info!("Activating tenant (on-demand)");
    1408            0 :                             AttachType::OnDemand
    1409              :                         },
    1410            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1411            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1412            0 :                             tracing::info!("Activating tenant (warmup)");
    1413            0 :                             AttachType::Warmup {
    1414            0 :                                 _permit,
    1415            0 :                                 during_startup: init_order.is_some()
    1416            0 :                             }
    1417              :                         }
    1418            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1419              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1420              :                             // stayed in Activating for such a long time that shutdown found it in
    1421              :                             // that state.
    1422            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1423              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1424              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1425              :                             // just shutting down), but ensures progress.
    1426            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1427            0 :                             return Ok(());
    1428              :                         },
    1429              :                     )
    1430              :                 } else {
    1431              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1432              :                     // concurrent_tenant_warmup queue
    1433            0 :                     AttachType::Normal
    1434              :                 };
    1435              : 
    1436            0 :                 let preload = match &mode {
    1437              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1438            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1439            0 :                         let res = tenant_clone
    1440            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1441            0 :                             .await;
    1442            0 :                         match res {
    1443            0 :                             Ok(p) => Some(p),
    1444            0 :                             Err(e) => {
    1445            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1446            0 :                                 return Ok(());
    1447              :                             }
    1448              :                         }
    1449              :                     }
    1450              : 
    1451              :                 };
    1452              : 
    1453              :                 // Remote preload is complete.
    1454            0 :                 drop(remote_load_completion);
    1455            0 : 
    1456            0 : 
    1457            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1458            0 :                 let attach_start = std::time::Instant::now();
    1459            0 :                 let attached = {
    1460            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1461            0 :                     tenant_clone.attach(preload, &ctx).await
    1462              :                 };
    1463            0 :                 let attach_duration = attach_start.elapsed();
    1464            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1465            0 : 
    1466            0 :                 match attached {
    1467              :                     Ok(()) => {
    1468            0 :                         info!("attach finished, activating");
    1469            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1470              :                     }
    1471            0 :                     Err(e) => {
    1472            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1473            0 :                     }
    1474              :                 }
    1475              : 
    1476              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1477              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1478              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1479              :                 //
    1480              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1481              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1482              :                 // then warmup will wait for that before proceeding to the next tenant.
    1483            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1484            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1485            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1486            0 :                     while futs.next().await.is_some() {}
    1487            0 :                     tracing::info!("Warm-up complete");
    1488            0 :                 }
    1489              : 
    1490            0 :                 Ok(())
    1491            0 :             }
    1492            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1493              :         );
    1494            0 :         Ok(tenant)
    1495            0 :     }
    1496              : 
    1497          196 :     #[instrument(skip_all)]
    1498              :     pub(crate) async fn preload(
    1499              :         self: &Arc<Self>,
    1500              :         remote_storage: &GenericRemoteStorage,
    1501              :         cancel: CancellationToken,
    1502              :     ) -> anyhow::Result<TenantPreload> {
    1503              :         span::debug_assert_current_span_has_tenant_id();
    1504              :         // Get list of remote timelines
    1505              :         // download index files for every tenant timeline
    1506              :         info!("listing remote timelines");
    1507              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1508              :             remote_storage,
    1509              :             self.tenant_shard_id,
    1510              :             cancel.clone(),
    1511              :         )
    1512              :         .await?;
    1513              :         let (offloaded_add, tenant_manifest) =
    1514              :             match remote_timeline_client::download_tenant_manifest(
    1515              :                 remote_storage,
    1516              :                 &self.tenant_shard_id,
    1517              :                 self.generation,
    1518              :                 &cancel,
    1519              :             )
    1520              :             .await
    1521              :             {
    1522              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1523              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1524              :                     tenant_manifest,
    1525              :                 ),
    1526              :                 Err(DownloadError::NotFound) => {
    1527              :                     ("no manifest".to_string(), TenantManifest::empty())
    1528              :                 }
    1529              :                 Err(e) => Err(e)?,
    1530              :             };
    1531              : 
    1532              :         info!(
    1533              :             "found {} timelines, and {offloaded_add}",
    1534              :             remote_timeline_ids.len()
    1535              :         );
    1536              : 
    1537              :         for k in other_keys {
    1538              :             warn!("Unexpected non timeline key {k}");
    1539              :         }
    1540              : 
    1541              :         // Avoid downloading IndexPart of offloaded timelines.
    1542              :         let mut offloaded_with_prefix = HashSet::new();
    1543              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1544              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1545              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1546              :             } else {
    1547              :                 // We'll take care later of timelines in the manifest without a prefix
    1548              :             }
    1549              :         }
    1550              : 
    1551              :         let timelines = self
    1552              :             .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1553              :             .await?;
    1554              : 
    1555              :         Ok(TenantPreload {
    1556              :             tenant_manifest,
    1557              :             timelines: timelines
    1558              :                 .into_iter()
    1559            6 :                 .map(|(id, tl)| (id, Some(tl)))
    1560            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1561              :                 .collect(),
    1562              :         })
    1563              :     }
    1564              : 
    1565              :     ///
    1566              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1567              :     ///
    1568              :     /// No background tasks are started as part of this routine.
    1569              :     ///
    1570          196 :     async fn attach(
    1571          196 :         self: &Arc<Tenant>,
    1572          196 :         preload: Option<TenantPreload>,
    1573          196 :         ctx: &RequestContext,
    1574          196 :     ) -> anyhow::Result<()> {
    1575          196 :         span::debug_assert_current_span_has_tenant_id();
    1576          196 : 
    1577          196 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1578              : 
    1579          196 :         let Some(preload) = preload else {
    1580            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1581              :         };
    1582              : 
    1583          196 :         let mut offloaded_timeline_ids = HashSet::new();
    1584          196 :         let mut offloaded_timelines_list = Vec::new();
    1585          196 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1586            0 :             let timeline_id = timeline_manifest.timeline_id;
    1587            0 :             let offloaded_timeline =
    1588            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1589            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1590            0 :             offloaded_timeline_ids.insert(timeline_id);
    1591            0 :         }
    1592              :         // Complete deletions for offloaded timeline id's from manifest.
    1593              :         // The manifest will be uploaded later in this function.
    1594          196 :         offloaded_timelines_list
    1595          196 :             .retain(|(offloaded_id, offloaded)| {
    1596            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1597            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1598            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1599            0 :                 if delete {
    1600            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1601            0 :                     offloaded.defuse_for_tenant_drop();
    1602            0 :                 }
    1603            0 :                 !delete
    1604          196 :         });
    1605          196 : 
    1606          196 :         let mut timelines_to_resume_deletions = vec![];
    1607          196 : 
    1608          196 :         let mut remote_index_and_client = HashMap::new();
    1609          196 :         let mut timeline_ancestors = HashMap::new();
    1610          196 :         let mut existent_timelines = HashSet::new();
    1611          202 :         for (timeline_id, preload) in preload.timelines {
    1612            6 :             let Some(preload) = preload else { continue };
    1613              :             // This is an invariant of the `preload` function's API
    1614            6 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1615            6 :             let index_part = match preload.index_part {
    1616            6 :                 Ok(i) => {
    1617            6 :                     debug!("remote index part exists for timeline {timeline_id}");
    1618              :                     // We found index_part on the remote, this is the standard case.
    1619            6 :                     existent_timelines.insert(timeline_id);
    1620            6 :                     i
    1621              :                 }
    1622              :                 Err(DownloadError::NotFound) => {
    1623              :                     // There is no index_part on the remote. We only get here
    1624              :                     // if there is some prefix for the timeline in the remote storage.
    1625              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1626              :                     // remnant from a prior incomplete creation or deletion attempt.
    1627              :                     // Delete the local directory as the deciding criterion for a
    1628              :                     // timeline's existence is presence of index_part.
    1629            0 :                     info!(%timeline_id, "index_part not found on remote");
    1630            0 :                     continue;
    1631              :                 }
    1632            0 :                 Err(DownloadError::Fatal(why)) => {
    1633            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1634            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1635            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1636            0 :                     anyhow::bail!(why.to_string());
    1637              :                 }
    1638            0 :                 Err(e) => {
    1639            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1640            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1641            0 :                     // as it might be a temporary issue and we don't want to re-download
    1642            0 :                     // everything after it resolves.
    1643            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1644              : 
    1645            0 :                     existent_timelines.insert(timeline_id);
    1646            0 :                     continue;
    1647              :                 }
    1648              :             };
    1649            6 :             match index_part {
    1650            6 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1651            6 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1652            6 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1653            6 :                 }
    1654            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1655            0 :                     info!(
    1656            0 :                         "timeline {} is deleted, picking to resume deletion",
    1657              :                         timeline_id
    1658              :                     );
    1659            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1660              :                 }
    1661              :             }
    1662              :         }
    1663              : 
    1664          196 :         let mut gc_blocks = HashMap::new();
    1665              : 
    1666              :         // For every timeline, download the metadata file, scan the local directory,
    1667              :         // and build a layer map that contains an entry for each remote and local
    1668              :         // layer file.
    1669          196 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1670          202 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1671            6 :             let (index_part, remote_client) = remote_index_and_client
    1672            6 :                 .remove(&timeline_id)
    1673            6 :                 .expect("just put it in above");
    1674              : 
    1675            6 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1676              :                 // could just filter these away, but it helps while testing
    1677            0 :                 anyhow::ensure!(
    1678            0 :                     !blocking.reasons.is_empty(),
    1679            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1680              :                 );
    1681            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1682            0 :                 assert!(prev.is_none());
    1683            6 :             }
    1684              : 
    1685              :             // TODO again handle early failure
    1686            6 :             let effect = self
    1687            6 :                 .load_remote_timeline(
    1688            6 :                     timeline_id,
    1689            6 :                     index_part,
    1690            6 :                     remote_metadata,
    1691            6 :                     TimelineResources {
    1692            6 :                         remote_client,
    1693            6 :                         pagestream_throttle: self.pagestream_throttle.clone(),
    1694            6 :                         l0_flush_global_state: self.l0_flush_global_state.clone(),
    1695            6 :                     },
    1696            6 :                     LoadTimelineCause::Attach,
    1697            6 :                     ctx,
    1698            6 :                 )
    1699            6 :                 .await
    1700            6 :                 .with_context(|| {
    1701            0 :                     format!(
    1702            0 :                         "failed to load remote timeline {} for tenant {}",
    1703            0 :                         timeline_id, self.tenant_shard_id
    1704            0 :                     )
    1705            6 :                 })?;
    1706              : 
    1707            6 :             match effect {
    1708            6 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1709            6 :                     // activation happens later, on Tenant::activate
    1710            6 :                 }
    1711              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1712              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1713            0 :                         timeline,
    1714            0 :                         import_pgdata,
    1715            0 :                         guard,
    1716            0 :                     },
    1717            0 :                 ) => {
    1718            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1719            0 :                         timeline,
    1720            0 :                         import_pgdata,
    1721            0 :                         ActivateTimelineArgs::No,
    1722            0 :                         guard,
    1723            0 :                     ));
    1724            0 :                 }
    1725              :             }
    1726              :         }
    1727              : 
    1728              :         // Walk through deleted timelines, resume deletion
    1729          196 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1730            0 :             remote_timeline_client
    1731            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1732            0 :                 .context("init queue stopped")
    1733            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1734              : 
    1735            0 :             DeleteTimelineFlow::resume_deletion(
    1736            0 :                 Arc::clone(self),
    1737            0 :                 timeline_id,
    1738            0 :                 &index_part.metadata,
    1739            0 :                 remote_timeline_client,
    1740            0 :             )
    1741            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1742            0 :             .await
    1743            0 :             .context("resume_deletion")
    1744            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1745              :         }
    1746          196 :         let needs_manifest_upload =
    1747          196 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1748          196 :         {
    1749          196 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1750          196 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1751          196 :         }
    1752          196 :         if needs_manifest_upload {
    1753            0 :             self.store_tenant_manifest().await?;
    1754          196 :         }
    1755              : 
    1756              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1757              :         // IndexPart is the source of truth.
    1758          196 :         self.clean_up_timelines(&existent_timelines)?;
    1759              : 
    1760          196 :         self.gc_block.set_scanned(gc_blocks);
    1761          196 : 
    1762          196 :         fail::fail_point!("attach-before-activate", |_| {
    1763            0 :             anyhow::bail!("attach-before-activate");
    1764          196 :         });
    1765          196 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1766              : 
    1767          196 :         info!("Done");
    1768              : 
    1769          196 :         Ok(())
    1770          196 :     }
    1771              : 
    1772              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1773              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1774              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1775          196 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1776          196 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1777              : 
    1778          196 :         let entries = match timelines_dir.read_dir_utf8() {
    1779          196 :             Ok(d) => d,
    1780            0 :             Err(e) => {
    1781            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1782            0 :                     return Ok(());
    1783              :                 } else {
    1784            0 :                     return Err(e).context("list timelines directory for tenant");
    1785              :                 }
    1786              :             }
    1787              :         };
    1788              : 
    1789          204 :         for entry in entries {
    1790            8 :             let entry = entry.context("read timeline dir entry")?;
    1791            8 :             let entry_path = entry.path();
    1792              : 
    1793            8 :             let purge = if crate::is_temporary(entry_path)
    1794              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1795            8 :                 || is_uninit_mark(entry_path)
    1796            8 :                 || crate::is_delete_mark(entry_path)
    1797              :             {
    1798            0 :                 true
    1799              :             } else {
    1800            8 :                 match TimelineId::try_from(entry_path.file_name()) {
    1801            8 :                     Ok(i) => {
    1802            8 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1803            8 :                         !existent_timelines.contains(&i)
    1804              :                     }
    1805            0 :                     Err(e) => {
    1806            0 :                         tracing::warn!(
    1807            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1808              :                         );
    1809              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1810            0 :                         false
    1811              :                     }
    1812              :                 }
    1813              :             };
    1814              : 
    1815            8 :             if purge {
    1816            2 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1817            2 :                 if let Err(e) = match entry.file_type() {
    1818            2 :                     Ok(t) => if t.is_dir() {
    1819            2 :                         std::fs::remove_dir_all(entry_path)
    1820              :                     } else {
    1821            0 :                         std::fs::remove_file(entry_path)
    1822              :                     }
    1823            2 :                     .or_else(fs_ext::ignore_not_found),
    1824            0 :                     Err(e) => Err(e),
    1825              :                 } {
    1826            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1827            2 :                 }
    1828            6 :             }
    1829              :         }
    1830              : 
    1831          196 :         Ok(())
    1832          196 :     }
    1833              : 
    1834              :     /// Get sum of all remote timelines sizes
    1835              :     ///
    1836              :     /// This function relies on the index_part instead of listing the remote storage
    1837            0 :     pub fn remote_size(&self) -> u64 {
    1838            0 :         let mut size = 0;
    1839              : 
    1840            0 :         for timeline in self.list_timelines() {
    1841            0 :             size += timeline.remote_client.get_remote_physical_size();
    1842            0 :         }
    1843              : 
    1844            0 :         size
    1845            0 :     }
    1846              : 
    1847            6 :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1848              :     async fn load_remote_timeline(
    1849              :         self: &Arc<Self>,
    1850              :         timeline_id: TimelineId,
    1851              :         index_part: IndexPart,
    1852              :         remote_metadata: TimelineMetadata,
    1853              :         resources: TimelineResources,
    1854              :         cause: LoadTimelineCause,
    1855              :         ctx: &RequestContext,
    1856              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1857              :         span::debug_assert_current_span_has_tenant_id();
    1858              : 
    1859              :         info!("downloading index file for timeline {}", timeline_id);
    1860              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1861              :             .await
    1862              :             .context("Failed to create new timeline directory")?;
    1863              : 
    1864              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1865              :             let timelines = self.timelines.lock().unwrap();
    1866              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1867            0 :                 || {
    1868            0 :                     anyhow::anyhow!(
    1869            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1870            0 :                     )
    1871            0 :                 },
    1872              :             )?))
    1873              :         } else {
    1874              :             None
    1875              :         };
    1876              : 
    1877              :         self.timeline_init_and_sync(
    1878              :             timeline_id,
    1879              :             resources,
    1880              :             index_part,
    1881              :             remote_metadata,
    1882              :             ancestor,
    1883              :             cause,
    1884              :             ctx,
    1885              :         )
    1886              :         .await
    1887              :     }
    1888              : 
    1889          196 :     async fn load_timelines_metadata(
    1890          196 :         self: &Arc<Tenant>,
    1891          196 :         timeline_ids: HashSet<TimelineId>,
    1892          196 :         remote_storage: &GenericRemoteStorage,
    1893          196 :         cancel: CancellationToken,
    1894          196 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1895          196 :         let mut part_downloads = JoinSet::new();
    1896          202 :         for timeline_id in timeline_ids {
    1897            6 :             let cancel_clone = cancel.clone();
    1898            6 :             part_downloads.spawn(
    1899            6 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1900            6 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1901              :             );
    1902              :         }
    1903              : 
    1904          196 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1905              : 
    1906              :         loop {
    1907          202 :             tokio::select!(
    1908          202 :                 next = part_downloads.join_next() => {
    1909          202 :                     match next {
    1910            6 :                         Some(result) => {
    1911            6 :                             let preload = result.context("join preload task")?;
    1912            6 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1913              :                         },
    1914              :                         None => {
    1915          196 :                             break;
    1916              :                         }
    1917              :                     }
    1918              :                 },
    1919          202 :                 _ = cancel.cancelled() => {
    1920            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1921              :                 }
    1922              :             )
    1923              :         }
    1924              : 
    1925          196 :         Ok(timeline_preloads)
    1926          196 :     }
    1927              : 
    1928            6 :     fn build_timeline_client(
    1929            6 :         &self,
    1930            6 :         timeline_id: TimelineId,
    1931            6 :         remote_storage: GenericRemoteStorage,
    1932            6 :     ) -> RemoteTimelineClient {
    1933            6 :         RemoteTimelineClient::new(
    1934            6 :             remote_storage.clone(),
    1935            6 :             self.deletion_queue_client.clone(),
    1936            6 :             self.conf,
    1937            6 :             self.tenant_shard_id,
    1938            6 :             timeline_id,
    1939            6 :             self.generation,
    1940            6 :             &self.tenant_conf.load().location,
    1941            6 :         )
    1942            6 :     }
    1943              : 
    1944            6 :     fn load_timeline_metadata(
    1945            6 :         self: &Arc<Tenant>,
    1946            6 :         timeline_id: TimelineId,
    1947            6 :         remote_storage: GenericRemoteStorage,
    1948            6 :         cancel: CancellationToken,
    1949            6 :     ) -> impl Future<Output = TimelinePreload> {
    1950            6 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1951            6 :         async move {
    1952            6 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1953            6 :             debug!("starting index part download");
    1954              : 
    1955            6 :             let index_part = client.download_index_file(&cancel).await;
    1956              : 
    1957            6 :             debug!("finished index part download");
    1958              : 
    1959            6 :             TimelinePreload {
    1960            6 :                 client,
    1961            6 :                 timeline_id,
    1962            6 :                 index_part,
    1963            6 :             }
    1964            6 :         }
    1965            6 :     }
    1966              : 
    1967            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1968            0 :         timeline_id: TimelineId,
    1969            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1970            0 :     ) -> Result<(), TimelineArchivalError> {
    1971            0 :         let children: Vec<TimelineId> = timelines
    1972            0 :             .iter()
    1973            0 :             .filter_map(|(id, entry)| {
    1974            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1975            0 :                     return None;
    1976            0 :                 }
    1977            0 :                 if entry.is_archived() == Some(true) {
    1978            0 :                     return None;
    1979            0 :                 }
    1980            0 :                 Some(*id)
    1981            0 :             })
    1982            0 :             .collect();
    1983            0 : 
    1984            0 :         if !children.is_empty() {
    1985            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1986            0 :         }
    1987            0 :         Ok(())
    1988            0 :     }
    1989              : 
    1990            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1991            0 :         ancestor_timeline_id: TimelineId,
    1992            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1993            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1994            0 :             '_,
    1995            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1996            0 :         >,
    1997            0 :     ) -> Result<(), TimelineArchivalError> {
    1998            0 :         let has_archived_parent =
    1999            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2000            0 :                 ancestor_timeline.is_archived() == Some(true)
    2001            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2002            0 :                 true
    2003              :             } else {
    2004            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2005            0 :                 if cfg!(debug_assertions) {
    2006            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2007            0 :                 }
    2008            0 :                 return Err(TimelineArchivalError::NotFound);
    2009              :             };
    2010            0 :         if has_archived_parent {
    2011            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2012            0 :                 ancestor_timeline_id,
    2013            0 :             ));
    2014            0 :         }
    2015            0 :         Ok(())
    2016            0 :     }
    2017              : 
    2018            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2019            0 :         timeline: &Arc<Timeline>,
    2020            0 :     ) -> Result<(), TimelineArchivalError> {
    2021            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2022            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2023            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2024            0 :                     ancestor_timeline.timeline_id,
    2025            0 :                 ));
    2026            0 :             }
    2027            0 :         }
    2028            0 :         Ok(())
    2029            0 :     }
    2030              : 
    2031              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2032              :     ///
    2033              :     /// Counterpart to [`offload_timeline`].
    2034            0 :     async fn unoffload_timeline(
    2035            0 :         self: &Arc<Self>,
    2036            0 :         timeline_id: TimelineId,
    2037            0 :         broker_client: storage_broker::BrokerClientChannel,
    2038            0 :         ctx: RequestContext,
    2039            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2040            0 :         info!("unoffloading timeline");
    2041              : 
    2042              :         // We activate the timeline below manually, so this must be called on an active timeline.
    2043              :         // We expect callers of this function to ensure this.
    2044            0 :         match self.current_state() {
    2045              :             TenantState::Activating { .. }
    2046              :             | TenantState::Attaching
    2047              :             | TenantState::Broken { .. } => {
    2048            0 :                 panic!("Timeline expected to be active")
    2049              :             }
    2050            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2051            0 :             TenantState::Active => {}
    2052            0 :         }
    2053            0 :         let cancel = self.cancel.clone();
    2054            0 : 
    2055            0 :         // Protect against concurrent attempts to use this TimelineId
    2056            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2057            0 :         let allow_offloaded = true;
    2058            0 :         let _create_guard = self
    2059            0 :             .create_timeline_create_guard(
    2060            0 :                 timeline_id,
    2061            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2062            0 :                 allow_offloaded,
    2063            0 :             )
    2064            0 :             .map_err(|err| match err {
    2065            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2066              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2067            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2068              :                 }
    2069            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2070            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2071            0 :             })?;
    2072              : 
    2073            0 :         let timeline_preload = self
    2074            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    2075            0 :             .await;
    2076              : 
    2077            0 :         let index_part = match timeline_preload.index_part {
    2078            0 :             Ok(index_part) => {
    2079            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2080            0 :                 index_part
    2081              :             }
    2082              :             Err(DownloadError::NotFound) => {
    2083            0 :                 error!(%timeline_id, "index_part not found on remote");
    2084            0 :                 return Err(TimelineArchivalError::NotFound);
    2085              :             }
    2086            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2087            0 :             Err(e) => {
    2088            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2089            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2090            0 :                 return Err(TimelineArchivalError::Other(
    2091            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2092            0 :                 ));
    2093              :             }
    2094              :         };
    2095            0 :         let index_part = match index_part {
    2096            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2097            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2098            0 :                 info!("timeline is deleted according to index_part.json");
    2099            0 :                 return Err(TimelineArchivalError::NotFound);
    2100              :             }
    2101              :         };
    2102            0 :         let remote_metadata = index_part.metadata.clone();
    2103            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2104            0 :         self.load_remote_timeline(
    2105            0 :             timeline_id,
    2106            0 :             index_part,
    2107            0 :             remote_metadata,
    2108            0 :             timeline_resources,
    2109            0 :             LoadTimelineCause::Unoffload,
    2110            0 :             &ctx,
    2111            0 :         )
    2112            0 :         .await
    2113            0 :         .with_context(|| {
    2114            0 :             format!(
    2115            0 :                 "failed to load remote timeline {} for tenant {}",
    2116            0 :                 timeline_id, self.tenant_shard_id
    2117            0 :             )
    2118            0 :         })
    2119            0 :         .map_err(TimelineArchivalError::Other)?;
    2120              : 
    2121            0 :         let timeline = {
    2122            0 :             let timelines = self.timelines.lock().unwrap();
    2123            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2124            0 :                 warn!("timeline not available directly after attach");
    2125              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2126              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2127            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2128            0 :                     "timeline not available directly after attach"
    2129            0 :                 )));
    2130              :             };
    2131            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2132            0 :             match offloaded_timelines.remove(&timeline_id) {
    2133            0 :                 Some(offloaded) => {
    2134            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2135            0 :                 }
    2136            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2137              :             }
    2138              : 
    2139            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2140            0 : 
    2141            0 :             Arc::clone(timeline)
    2142            0 :         };
    2143            0 : 
    2144            0 :         // Upload new list of offloaded timelines to S3
    2145            0 :         self.store_tenant_manifest().await?;
    2146              : 
    2147              :         // Activate the timeline (if it makes sense)
    2148            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2149            0 :             let background_jobs_can_start = None;
    2150            0 :             timeline.activate(
    2151            0 :                 self.clone(),
    2152            0 :                 broker_client.clone(),
    2153            0 :                 background_jobs_can_start,
    2154            0 :                 &ctx,
    2155            0 :             );
    2156            0 :         }
    2157              : 
    2158            0 :         info!("timeline unoffloading complete");
    2159            0 :         Ok(timeline)
    2160            0 :     }
    2161              : 
    2162            0 :     pub(crate) async fn apply_timeline_archival_config(
    2163            0 :         self: &Arc<Self>,
    2164            0 :         timeline_id: TimelineId,
    2165            0 :         new_state: TimelineArchivalState,
    2166            0 :         broker_client: storage_broker::BrokerClientChannel,
    2167            0 :         ctx: RequestContext,
    2168            0 :     ) -> Result<(), TimelineArchivalError> {
    2169            0 :         info!("setting timeline archival config");
    2170              :         // First part: figure out what is needed to do, and do validation
    2171            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2172            0 :             let timelines = self.timelines.lock().unwrap();
    2173              : 
    2174            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2175            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2176            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2177            0 :                     return Err(TimelineArchivalError::NotFound);
    2178              :                 };
    2179            0 :                 if new_state == TimelineArchivalState::Archived {
    2180              :                     // It's offloaded already, so nothing to do
    2181            0 :                     return Ok(());
    2182            0 :                 }
    2183            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2184            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2185            0 :                         ancestor_timeline_id,
    2186            0 :                         &timelines,
    2187            0 :                         &offloaded_timelines,
    2188            0 :                     )?;
    2189            0 :                 }
    2190            0 :                 break 'outer None;
    2191              :             };
    2192              : 
    2193              :             // Do some validation. We release the timelines lock below, so there is potential
    2194              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2195              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2196            0 :             match new_state {
    2197              :                 TimelineArchivalState::Unarchived => {
    2198            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2199              :                 }
    2200              :                 TimelineArchivalState::Archived => {
    2201            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2202              :                 }
    2203              :             }
    2204            0 :             Some(Arc::clone(timeline))
    2205              :         };
    2206              : 
    2207              :         // Second part: unoffload timeline (if needed)
    2208            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2209            0 :             timeline
    2210              :         } else {
    2211              :             // Turn offloaded timeline into a non-offloaded one
    2212            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2213            0 :                 .await?
    2214              :         };
    2215              : 
    2216              :         // Third part: upload new timeline archival state and block until it is present in S3
    2217            0 :         let upload_needed = match timeline
    2218            0 :             .remote_client
    2219            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2220              :         {
    2221            0 :             Ok(upload_needed) => upload_needed,
    2222            0 :             Err(e) => {
    2223            0 :                 if timeline.cancel.is_cancelled() {
    2224            0 :                     return Err(TimelineArchivalError::Cancelled);
    2225              :                 } else {
    2226            0 :                     return Err(TimelineArchivalError::Other(e));
    2227              :                 }
    2228              :             }
    2229              :         };
    2230              : 
    2231            0 :         if upload_needed {
    2232            0 :             info!("Uploading new state");
    2233              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2234            0 :             let Ok(v) =
    2235            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2236              :             else {
    2237            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2238            0 :                 return Err(TimelineArchivalError::Timeout);
    2239              :             };
    2240            0 :             v.map_err(|e| match e {
    2241            0 :                 WaitCompletionError::NotInitialized(e) => {
    2242            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2243              :                 }
    2244              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2245            0 :                     TimelineArchivalError::Cancelled
    2246              :                 }
    2247            0 :             })?;
    2248            0 :         }
    2249            0 :         Ok(())
    2250            0 :     }
    2251              : 
    2252            2 :     pub fn get_offloaded_timeline(
    2253            2 :         &self,
    2254            2 :         timeline_id: TimelineId,
    2255            2 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2256            2 :         self.timelines_offloaded
    2257            2 :             .lock()
    2258            2 :             .unwrap()
    2259            2 :             .get(&timeline_id)
    2260            2 :             .map(Arc::clone)
    2261            2 :             .ok_or(GetTimelineError::NotFound {
    2262            2 :                 tenant_id: self.tenant_shard_id,
    2263            2 :                 timeline_id,
    2264            2 :             })
    2265            2 :     }
    2266              : 
    2267            4 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2268            4 :         self.tenant_shard_id
    2269            4 :     }
    2270              : 
    2271              :     /// Get Timeline handle for given Neon timeline ID.
    2272              :     /// This function is idempotent. It doesn't change internal state in any way.
    2273          222 :     pub fn get_timeline(
    2274          222 :         &self,
    2275          222 :         timeline_id: TimelineId,
    2276          222 :         active_only: bool,
    2277          222 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2278          222 :         let timelines_accessor = self.timelines.lock().unwrap();
    2279          222 :         let timeline = timelines_accessor
    2280          222 :             .get(&timeline_id)
    2281          222 :             .ok_or(GetTimelineError::NotFound {
    2282          222 :                 tenant_id: self.tenant_shard_id,
    2283          222 :                 timeline_id,
    2284          222 :             })?;
    2285              : 
    2286          220 :         if active_only && !timeline.is_active() {
    2287            0 :             Err(GetTimelineError::NotActive {
    2288            0 :                 tenant_id: self.tenant_shard_id,
    2289            0 :                 timeline_id,
    2290            0 :                 state: timeline.current_state(),
    2291            0 :             })
    2292              :         } else {
    2293          220 :             Ok(Arc::clone(timeline))
    2294              :         }
    2295          222 :     }
    2296              : 
    2297              :     /// Lists timelines the tenant contains.
    2298              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2299            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2300            0 :         self.timelines
    2301            0 :             .lock()
    2302            0 :             .unwrap()
    2303            0 :             .values()
    2304            0 :             .map(Arc::clone)
    2305            0 :             .collect()
    2306            0 :     }
    2307              : 
    2308              :     /// Lists timelines the tenant manages, including offloaded ones.
    2309              :     ///
    2310              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2311            0 :     pub fn list_timelines_and_offloaded(
    2312            0 :         &self,
    2313            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2314            0 :         let timelines = self
    2315            0 :             .timelines
    2316            0 :             .lock()
    2317            0 :             .unwrap()
    2318            0 :             .values()
    2319            0 :             .map(Arc::clone)
    2320            0 :             .collect();
    2321            0 :         let offloaded = self
    2322            0 :             .timelines_offloaded
    2323            0 :             .lock()
    2324            0 :             .unwrap()
    2325            0 :             .values()
    2326            0 :             .map(Arc::clone)
    2327            0 :             .collect();
    2328            0 :         (timelines, offloaded)
    2329            0 :     }
    2330              : 
    2331            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2332            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2333            0 :     }
    2334              : 
    2335              :     /// This is used by tests & import-from-basebackup.
    2336              :     ///
    2337              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2338              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2339              :     ///
    2340              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2341              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2342              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2343              :     /// to the [`Tenant::timelines`].
    2344              :     ///
    2345              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2346          188 :     pub(crate) async fn create_empty_timeline(
    2347          188 :         self: &Arc<Self>,
    2348          188 :         new_timeline_id: TimelineId,
    2349          188 :         initdb_lsn: Lsn,
    2350          188 :         pg_version: u32,
    2351          188 :         _ctx: &RequestContext,
    2352          188 :     ) -> anyhow::Result<UninitializedTimeline> {
    2353          188 :         anyhow::ensure!(
    2354          188 :             self.is_active(),
    2355            0 :             "Cannot create empty timelines on inactive tenant"
    2356              :         );
    2357              : 
    2358              :         // Protect against concurrent attempts to use this TimelineId
    2359          188 :         let create_guard = match self
    2360          188 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2361          188 :             .await?
    2362              :         {
    2363          186 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2364              :             StartCreatingTimelineResult::Idempotent(_) => {
    2365            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2366              :             }
    2367              :         };
    2368              : 
    2369          186 :         let new_metadata = TimelineMetadata::new(
    2370          186 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2371          186 :             // make it valid, before calling finish_creation()
    2372          186 :             Lsn(0),
    2373          186 :             None,
    2374          186 :             None,
    2375          186 :             Lsn(0),
    2376          186 :             initdb_lsn,
    2377          186 :             initdb_lsn,
    2378          186 :             pg_version,
    2379          186 :         );
    2380          186 :         self.prepare_new_timeline(
    2381          186 :             new_timeline_id,
    2382          186 :             &new_metadata,
    2383          186 :             create_guard,
    2384          186 :             initdb_lsn,
    2385          186 :             None,
    2386          186 :         )
    2387          186 :         .await
    2388          188 :     }
    2389              : 
    2390              :     /// Helper for unit tests to create an empty timeline.
    2391              :     ///
    2392              :     /// The timeline is has state value `Active` but its background loops are not running.
    2393              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2394              :     // Our current tests don't need the background loops.
    2395              :     #[cfg(test)]
    2396          178 :     pub async fn create_test_timeline(
    2397          178 :         self: &Arc<Self>,
    2398          178 :         new_timeline_id: TimelineId,
    2399          178 :         initdb_lsn: Lsn,
    2400          178 :         pg_version: u32,
    2401          178 :         ctx: &RequestContext,
    2402          178 :     ) -> anyhow::Result<Arc<Timeline>> {
    2403          178 :         let uninit_tl = self
    2404          178 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2405          178 :             .await?;
    2406          178 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2407          178 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2408              : 
    2409              :         // Setup minimum keys required for the timeline to be usable.
    2410          178 :         let mut modification = tline.begin_modification(initdb_lsn);
    2411          178 :         modification
    2412          178 :             .init_empty_test_timeline()
    2413          178 :             .context("init_empty_test_timeline")?;
    2414          178 :         modification
    2415          178 :             .commit(ctx)
    2416          178 :             .await
    2417          178 :             .context("commit init_empty_test_timeline modification")?;
    2418              : 
    2419              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2420          178 :         tline.maybe_spawn_flush_loop();
    2421          178 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2422              : 
    2423              :         // Make sure the freeze_and_flush reaches remote storage.
    2424          178 :         tline.remote_client.wait_completion().await.unwrap();
    2425              : 
    2426          178 :         let tl = uninit_tl.finish_creation()?;
    2427              :         // The non-test code would call tl.activate() here.
    2428          178 :         tl.set_state(TimelineState::Active);
    2429          178 :         Ok(tl)
    2430          178 :     }
    2431              : 
    2432              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2433              :     #[cfg(test)]
    2434              :     #[allow(clippy::too_many_arguments)]
    2435           36 :     pub async fn create_test_timeline_with_layers(
    2436           36 :         self: &Arc<Self>,
    2437           36 :         new_timeline_id: TimelineId,
    2438           36 :         initdb_lsn: Lsn,
    2439           36 :         pg_version: u32,
    2440           36 :         ctx: &RequestContext,
    2441           36 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2442           36 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2443           36 :         end_lsn: Lsn,
    2444           36 :     ) -> anyhow::Result<Arc<Timeline>> {
    2445              :         use checks::check_valid_layermap;
    2446              :         use itertools::Itertools;
    2447              : 
    2448           36 :         let tline = self
    2449           36 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2450           36 :             .await?;
    2451           36 :         tline.force_advance_lsn(end_lsn);
    2452          120 :         for deltas in delta_layer_desc {
    2453           84 :             tline
    2454           84 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2455           84 :                 .await?;
    2456              :         }
    2457           88 :         for (lsn, images) in image_layer_desc {
    2458           52 :             tline
    2459           52 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2460           52 :                 .await?;
    2461              :         }
    2462           36 :         let layer_names = tline
    2463           36 :             .layers
    2464           36 :             .read()
    2465           36 :             .await
    2466           36 :             .layer_map()
    2467           36 :             .unwrap()
    2468           36 :             .iter_historic_layers()
    2469          172 :             .map(|layer| layer.layer_name())
    2470           36 :             .collect_vec();
    2471           36 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2472            0 :             bail!("invalid layermap: {err}");
    2473           36 :         }
    2474           36 :         Ok(tline)
    2475           36 :     }
    2476              : 
    2477              :     /// Create a new timeline.
    2478              :     ///
    2479              :     /// Returns the new timeline ID and reference to its Timeline object.
    2480              :     ///
    2481              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2482              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2483              :     #[allow(clippy::too_many_arguments)]
    2484            0 :     pub(crate) async fn create_timeline(
    2485            0 :         self: &Arc<Tenant>,
    2486            0 :         params: CreateTimelineParams,
    2487            0 :         broker_client: storage_broker::BrokerClientChannel,
    2488            0 :         ctx: &RequestContext,
    2489            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2490            0 :         if !self.is_active() {
    2491            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2492            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2493              :             } else {
    2494            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2495            0 :                     "Cannot create timelines on inactive tenant"
    2496            0 :                 )));
    2497              :             }
    2498            0 :         }
    2499              : 
    2500            0 :         let _gate = self
    2501            0 :             .gate
    2502            0 :             .enter()
    2503            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2504              : 
    2505            0 :         let result: CreateTimelineResult = match params {
    2506              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2507            0 :                 new_timeline_id,
    2508            0 :                 existing_initdb_timeline_id,
    2509            0 :                 pg_version,
    2510            0 :             }) => {
    2511            0 :                 self.bootstrap_timeline(
    2512            0 :                     new_timeline_id,
    2513            0 :                     pg_version,
    2514            0 :                     existing_initdb_timeline_id,
    2515            0 :                     ctx,
    2516            0 :                 )
    2517            0 :                 .await?
    2518              :             }
    2519              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2520            0 :                 new_timeline_id,
    2521            0 :                 ancestor_timeline_id,
    2522            0 :                 mut ancestor_start_lsn,
    2523              :             }) => {
    2524            0 :                 let ancestor_timeline = self
    2525            0 :                     .get_timeline(ancestor_timeline_id, false)
    2526            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2527              : 
    2528              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2529              :                 // ready for other purposes either.
    2530            0 :                 if !ancestor_timeline.is_active() {
    2531            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2532            0 :                 }
    2533            0 : 
    2534            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2535            0 :                     info!("tried to branch archived timeline");
    2536            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2537            0 :                 }
    2538              : 
    2539            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2540            0 :                     *lsn = lsn.align();
    2541            0 : 
    2542            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2543            0 :                     if ancestor_ancestor_lsn > *lsn {
    2544              :                         // can we safely just branch from the ancestor instead?
    2545            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2546            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2547            0 :                             lsn,
    2548            0 :                             ancestor_timeline_id,
    2549            0 :                             ancestor_ancestor_lsn,
    2550            0 :                         )));
    2551            0 :                     }
    2552            0 : 
    2553            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2554            0 :                     // to the requested branch point. The repository code itself doesn't
    2555            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2556            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2557            0 :                     // sizes etc. and that would get confused if the previous page versions
    2558            0 :                     // are not in the repository yet.
    2559            0 :                     ancestor_timeline
    2560            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    2561            0 :                         .await
    2562            0 :                         .map_err(|e| match e {
    2563            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2564            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2565              :                             }
    2566            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2567            0 :                         })?;
    2568            0 :                 }
    2569              : 
    2570            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2571            0 :                     .await?
    2572              :             }
    2573            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2574            0 :                 self.create_timeline_import_pgdata(
    2575            0 :                     params,
    2576            0 :                     ActivateTimelineArgs::Yes {
    2577            0 :                         broker_client: broker_client.clone(),
    2578            0 :                     },
    2579            0 :                     ctx,
    2580            0 :                 )
    2581            0 :                 .await?
    2582              :             }
    2583              :         };
    2584              : 
    2585              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2586              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2587              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2588              :         //
    2589              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2590              :         // assume that, because they can see the timeline via API, that the creation is done and
    2591              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2592              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2593              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2594              :         //
    2595              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2596              :         // creation API until it returns success. Only then is durability guaranteed.
    2597            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2598            0 :         result
    2599            0 :             .timeline()
    2600            0 :             .remote_client
    2601            0 :             .wait_completion()
    2602            0 :             .await
    2603            0 :             .map_err(|e| match e {
    2604              :                 WaitCompletionError::NotInitialized(
    2605            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2606            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2607            0 :                 e => CreateTimelineError::Other(e.into()),
    2608            0 :             })
    2609            0 :             .context("wait for timeline initial uploads to complete")?;
    2610              : 
    2611              :         // The creating task is responsible for activating the timeline.
    2612              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2613              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2614            0 :         let activated_timeline = match result {
    2615            0 :             CreateTimelineResult::Created(timeline) => {
    2616            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2617            0 :                 timeline
    2618              :             }
    2619            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2620            0 :                 info!(
    2621            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2622              :                 );
    2623            0 :                 timeline
    2624              :             }
    2625            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2626            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2627            0 :                 timeline
    2628              :             }
    2629              :         };
    2630              : 
    2631            0 :         Ok(activated_timeline)
    2632            0 :     }
    2633              : 
    2634              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2635              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2636              :     /// [`Tenant::timelines`] map when the import completes.
    2637              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2638              :     /// for the response.
    2639            0 :     async fn create_timeline_import_pgdata(
    2640            0 :         self: &Arc<Tenant>,
    2641            0 :         params: CreateTimelineParamsImportPgdata,
    2642            0 :         activate: ActivateTimelineArgs,
    2643            0 :         ctx: &RequestContext,
    2644            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2645            0 :         let CreateTimelineParamsImportPgdata {
    2646            0 :             new_timeline_id,
    2647            0 :             location,
    2648            0 :             idempotency_key,
    2649            0 :         } = params;
    2650            0 : 
    2651            0 :         let started_at = chrono::Utc::now().naive_utc();
    2652              : 
    2653              :         //
    2654              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2655              :         // is the canonical way we do it.
    2656              :         // - create an empty timeline in-memory
    2657              :         // - use its remote_timeline_client to do the upload
    2658              :         // - dispose of the uninit timeline
    2659              :         // - keep the creation guard alive
    2660              : 
    2661            0 :         let timeline_create_guard = match self
    2662            0 :             .start_creating_timeline(
    2663            0 :                 new_timeline_id,
    2664            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2665            0 :                     idempotency_key: idempotency_key.clone(),
    2666            0 :                 }),
    2667            0 :             )
    2668            0 :             .await?
    2669              :         {
    2670            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2671            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2672            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2673              :             }
    2674              :         };
    2675              : 
    2676            0 :         let mut uninit_timeline = {
    2677            0 :             let this = &self;
    2678            0 :             let initdb_lsn = Lsn(0);
    2679            0 :             let _ctx = ctx;
    2680            0 :             async move {
    2681            0 :                 let new_metadata = TimelineMetadata::new(
    2682            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2683            0 :                     // make it valid, before calling finish_creation()
    2684            0 :                     Lsn(0),
    2685            0 :                     None,
    2686            0 :                     None,
    2687            0 :                     Lsn(0),
    2688            0 :                     initdb_lsn,
    2689            0 :                     initdb_lsn,
    2690            0 :                     15,
    2691            0 :                 );
    2692            0 :                 this.prepare_new_timeline(
    2693            0 :                     new_timeline_id,
    2694            0 :                     &new_metadata,
    2695            0 :                     timeline_create_guard,
    2696            0 :                     initdb_lsn,
    2697            0 :                     None,
    2698            0 :                 )
    2699            0 :                 .await
    2700            0 :             }
    2701            0 :         }
    2702            0 :         .await?;
    2703              : 
    2704            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2705            0 :             idempotency_key,
    2706            0 :             location,
    2707            0 :             started_at,
    2708            0 :         };
    2709            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2710            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2711            0 :         );
    2712            0 :         uninit_timeline
    2713            0 :             .raw_timeline()
    2714            0 :             .unwrap()
    2715            0 :             .remote_client
    2716            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2717              : 
    2718              :         // wait_completion happens in caller
    2719              : 
    2720            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2721            0 : 
    2722            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2723            0 :             timeline.clone(),
    2724            0 :             index_part,
    2725            0 :             activate,
    2726            0 :             timeline_create_guard,
    2727            0 :         ));
    2728            0 : 
    2729            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2730            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2731            0 :     }
    2732              : 
    2733            0 :     #[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))]
    2734              :     async fn create_timeline_import_pgdata_task(
    2735              :         self: Arc<Tenant>,
    2736              :         timeline: Arc<Timeline>,
    2737              :         index_part: import_pgdata::index_part_format::Root,
    2738              :         activate: ActivateTimelineArgs,
    2739              :         timeline_create_guard: TimelineCreateGuard,
    2740              :     ) {
    2741              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2742              :         info!("starting");
    2743              :         scopeguard::defer! {info!("exiting")};
    2744              : 
    2745              :         let res = self
    2746              :             .create_timeline_import_pgdata_task_impl(
    2747              :                 timeline,
    2748              :                 index_part,
    2749              :                 activate,
    2750              :                 timeline_create_guard,
    2751              :             )
    2752              :             .await;
    2753              :         if let Err(err) = &res {
    2754              :             error!(?err, "task failed");
    2755              :             // TODO sleep & retry, sensitive to tenant shutdown
    2756              :             // TODO: allow timeline deletion requests => should cancel the task
    2757              :         }
    2758              :     }
    2759              : 
    2760            0 :     async fn create_timeline_import_pgdata_task_impl(
    2761            0 :         self: Arc<Tenant>,
    2762            0 :         timeline: Arc<Timeline>,
    2763            0 :         index_part: import_pgdata::index_part_format::Root,
    2764            0 :         activate: ActivateTimelineArgs,
    2765            0 :         timeline_create_guard: TimelineCreateGuard,
    2766            0 :     ) -> Result<(), anyhow::Error> {
    2767            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2768            0 : 
    2769            0 :         info!("importing pgdata");
    2770            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2771            0 :             .await
    2772            0 :             .context("import")?;
    2773            0 :         info!("import done");
    2774              : 
    2775              :         //
    2776              :         // Reload timeline from remote.
    2777              :         // This proves that the remote state is attachable, and it reuses the code.
    2778              :         //
    2779              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2780              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2781              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2782              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2783              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2784              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2785              :         // to manifest because of the long runtime of this import task.
    2786              : 
    2787              :         //        in theory this shouldn't even .await anything except for coop yield
    2788            0 :         info!("shutting down timeline");
    2789            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2790            0 :         info!("timeline shut down, reloading from remote");
    2791              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2792              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2793              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2794              :         // };
    2795            0 :         let timeline_id = timeline.timeline_id;
    2796            0 : 
    2797            0 :         // load from object storage like Tenant::attach does
    2798            0 :         let resources = self.build_timeline_resources(timeline_id);
    2799            0 :         let index_part = resources
    2800            0 :             .remote_client
    2801            0 :             .download_index_file(&self.cancel)
    2802            0 :             .await?;
    2803            0 :         let index_part = match index_part {
    2804              :             MaybeDeletedIndexPart::Deleted(_) => {
    2805              :                 // likely concurrent delete call, cplane should prevent this
    2806            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2807              :             }
    2808            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2809            0 :         };
    2810            0 :         let metadata = index_part.metadata.clone();
    2811            0 :         self
    2812            0 :             .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
    2813            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2814            0 :             .await?
    2815            0 :             .ready_to_activate()
    2816            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2817              : 
    2818            0 :         anyhow::Ok(())
    2819            0 :     }
    2820              : 
    2821            0 :     pub(crate) async fn delete_timeline(
    2822            0 :         self: Arc<Self>,
    2823            0 :         timeline_id: TimelineId,
    2824            0 :     ) -> Result<(), DeleteTimelineError> {
    2825            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2826              : 
    2827            0 :         Ok(())
    2828            0 :     }
    2829              : 
    2830              :     /// perform one garbage collection iteration, removing old data files from disk.
    2831              :     /// this function is periodically called by gc task.
    2832              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2833              :     ///
    2834              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2835              :     ///
    2836              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2837              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2838              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2839              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2840              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2841              :     /// requires more history to be retained.
    2842              :     //
    2843          754 :     pub(crate) async fn gc_iteration(
    2844          754 :         &self,
    2845          754 :         target_timeline_id: Option<TimelineId>,
    2846          754 :         horizon: u64,
    2847          754 :         pitr: Duration,
    2848          754 :         cancel: &CancellationToken,
    2849          754 :         ctx: &RequestContext,
    2850          754 :     ) -> Result<GcResult, GcError> {
    2851          754 :         // Don't start doing work during shutdown
    2852          754 :         if let TenantState::Stopping { .. } = self.current_state() {
    2853            0 :             return Ok(GcResult::default());
    2854          754 :         }
    2855          754 : 
    2856          754 :         // there is a global allowed_error for this
    2857          754 :         if !self.is_active() {
    2858            0 :             return Err(GcError::NotActive);
    2859          754 :         }
    2860          754 : 
    2861          754 :         {
    2862          754 :             let conf = self.tenant_conf.load();
    2863          754 : 
    2864          754 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2865          754 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2866          754 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2867          754 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2868          754 :             if !conf.location.may_delete_layers_hint() {
    2869            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2870            0 :                 return Ok(GcResult::default());
    2871          754 :             }
    2872          754 : 
    2873          754 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2874          750 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2875          750 :                 return Ok(GcResult::default());
    2876            4 :             }
    2877              :         }
    2878              : 
    2879            4 :         let _guard = match self.gc_block.start().await {
    2880            4 :             Ok(guard) => guard,
    2881            0 :             Err(reasons) => {
    2882            0 :                 info!("Skipping GC: {reasons}");
    2883            0 :                 return Ok(GcResult::default());
    2884              :             }
    2885              :         };
    2886              : 
    2887            4 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2888            4 :             .await
    2889          754 :     }
    2890              : 
    2891              :     /// Perform one compaction iteration.
    2892              :     /// This function is periodically called by compactor task.
    2893              :     /// Also it can be explicitly requested per timeline through page server
    2894              :     /// api's 'compact' command.
    2895              :     ///
    2896              :     /// Returns whether we have pending compaction task.
    2897            0 :     async fn compaction_iteration(
    2898            0 :         self: &Arc<Self>,
    2899            0 :         cancel: &CancellationToken,
    2900            0 :         ctx: &RequestContext,
    2901            0 :     ) -> Result<bool, timeline::CompactionError> {
    2902            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2903            0 :         if !self.is_active() {
    2904            0 :             return Ok(false);
    2905            0 :         }
    2906            0 : 
    2907            0 :         {
    2908            0 :             let conf = self.tenant_conf.load();
    2909            0 : 
    2910            0 :             // Note that compaction usually requires deletions, but we don't respect
    2911            0 :             // may_delete_layers_hint here: that is because tenants in AttachedMulti
    2912            0 :             // should proceed with compaction even if they can't do deletion, to avoid
    2913            0 :             // accumulating dangerously deep stacks of L0 layers.  Deletions will be
    2914            0 :             // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
    2915            0 :             // to AttachedSingle state.
    2916            0 :             if !conf.location.may_upload_layers_hint() {
    2917            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2918            0 :                 return Ok(false);
    2919            0 :             }
    2920            0 :         }
    2921            0 : 
    2922            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2923            0 :         // while holding the lock. Then drop the lock and actually perform the
    2924            0 :         // compactions.  We don't want to block everything else while the
    2925            0 :         // compaction runs.
    2926            0 :         let timelines_to_compact_or_offload;
    2927            0 :         {
    2928            0 :             let timelines = self.timelines.lock().unwrap();
    2929            0 :             timelines_to_compact_or_offload = timelines
    2930            0 :                 .iter()
    2931            0 :                 .filter_map(|(timeline_id, timeline)| {
    2932            0 :                     let (is_active, (can_offload, _)) =
    2933            0 :                         (timeline.is_active(), timeline.can_offload());
    2934            0 :                     let has_no_unoffloaded_children = {
    2935            0 :                         !timelines
    2936            0 :                             .iter()
    2937            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2938              :                     };
    2939            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2940            0 :                         || self
    2941            0 :                             .tenant_conf
    2942            0 :                             .load()
    2943            0 :                             .tenant_conf
    2944            0 :                             .timeline_offloading
    2945            0 :                             .unwrap_or_default();
    2946            0 :                     let can_offload =
    2947            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2948            0 :                     if (is_active, can_offload) == (false, false) {
    2949            0 :                         None
    2950              :                     } else {
    2951            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2952              :                     }
    2953            0 :                 })
    2954            0 :                 .collect::<Vec<_>>();
    2955            0 :             drop(timelines);
    2956            0 :         }
    2957            0 : 
    2958            0 :         // Before doing any I/O work, check our circuit breaker
    2959            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2960            0 :             info!("Skipping compaction due to previous failures");
    2961            0 :             return Ok(false);
    2962            0 :         }
    2963            0 : 
    2964            0 :         let mut has_pending_task = false;
    2965              : 
    2966            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2967              :         {
    2968              :             // pending_task_left == None: cannot compact, maybe still pending tasks
    2969              :             // pending_task_left == Some(true): compaction task left
    2970              :             // pending_task_left == Some(false): no compaction task left
    2971            0 :             let pending_task_left = if *can_compact {
    2972            0 :                 let has_pending_l0_compaction_task = timeline
    2973            0 :                     .compact(cancel, EnumSet::empty(), ctx)
    2974            0 :                     .instrument(info_span!("compact_timeline", %timeline_id))
    2975            0 :                     .await
    2976            0 :                     .inspect_err(|e| match e {
    2977            0 :                         timeline::CompactionError::ShuttingDown => (),
    2978            0 :                         timeline::CompactionError::Offload(_) => {
    2979            0 :                             // Failures to offload timelines do not trip the circuit breaker, because
    2980            0 :                             // they do not do lots of writes the way compaction itself does: it is cheap
    2981            0 :                             // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2982            0 :                         }
    2983            0 :                         timeline::CompactionError::Other(e) => {
    2984            0 :                             self.compaction_circuit_breaker
    2985            0 :                                 .lock()
    2986            0 :                                 .unwrap()
    2987            0 :                                 .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2988            0 :                         }
    2989            0 :                     })?;
    2990            0 :                 if has_pending_l0_compaction_task {
    2991            0 :                     Some(true)
    2992              :                 } else {
    2993              :                     let mut has_pending_scheduled_compaction_task;
    2994            0 :                     let next_scheduled_compaction_task = {
    2995            0 :                         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    2996            0 :                         if let Some(tline_pending_tasks) = guard.get_mut(timeline_id) {
    2997            0 :                             if !tline_pending_tasks.is_empty() {
    2998            0 :                                 info!(
    2999            0 :                                     "{} tasks left in the compaction schedule queue",
    3000            0 :                                     tline_pending_tasks.len()
    3001              :                                 );
    3002            0 :                             }
    3003            0 :                             let next_task = tline_pending_tasks.pop_front();
    3004            0 :                             has_pending_scheduled_compaction_task = !tline_pending_tasks.is_empty();
    3005            0 :                             next_task
    3006              :                         } else {
    3007            0 :                             has_pending_scheduled_compaction_task = false;
    3008            0 :                             None
    3009              :                         }
    3010              :                     };
    3011            0 :                     if let Some(mut next_scheduled_compaction_task) = next_scheduled_compaction_task
    3012              :                     {
    3013            0 :                         if !next_scheduled_compaction_task
    3014            0 :                             .options
    3015            0 :                             .flags
    3016            0 :                             .contains(CompactFlags::EnhancedGcBottomMostCompaction)
    3017              :                         {
    3018            0 :                             warn!("ignoring scheduled compaction task: scheduled task must be gc compaction: {:?}", next_scheduled_compaction_task.options);
    3019            0 :                         } else if next_scheduled_compaction_task.options.sub_compaction {
    3020            0 :                             info!("running scheduled enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs");
    3021            0 :                             let jobs: Vec<GcCompactJob> = timeline
    3022            0 :                                 .gc_compaction_split_jobs(
    3023            0 :                                     GcCompactJob::from_compact_options(
    3024            0 :                                         next_scheduled_compaction_task.options.clone(),
    3025            0 :                                     ),
    3026            0 :                                     next_scheduled_compaction_task
    3027            0 :                                         .options
    3028            0 :                                         .sub_compaction_max_job_size_mb,
    3029            0 :                                 )
    3030            0 :                                 .await
    3031            0 :                                 .map_err(CompactionError::Other)?;
    3032            0 :                             if jobs.is_empty() {
    3033            0 :                                 info!("no jobs to run, skipping scheduled compaction task");
    3034              :                             } else {
    3035            0 :                                 has_pending_scheduled_compaction_task = true;
    3036            0 :                                 let jobs_len = jobs.len();
    3037            0 :                                 let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3038            0 :                                 let tline_pending_tasks = guard.entry(*timeline_id).or_default();
    3039            0 :                                 for (idx, job) in jobs.into_iter().enumerate() {
    3040              :                                     // Unfortunately we need to convert the `GcCompactJob` back to `CompactionOptions`
    3041              :                                     // until we do further refactors to allow directly call `compact_with_gc`.
    3042            0 :                                     let mut flags: EnumSet<CompactFlags> = EnumSet::default();
    3043            0 :                                     flags |= CompactFlags::EnhancedGcBottomMostCompaction;
    3044            0 :                                     if job.dry_run {
    3045            0 :                                         flags |= CompactFlags::DryRun;
    3046            0 :                                     }
    3047            0 :                                     let options = CompactOptions {
    3048            0 :                                         flags,
    3049            0 :                                         sub_compaction: false,
    3050            0 :                                         compact_key_range: Some(job.compact_key_range.into()),
    3051            0 :                                         compact_lsn_range: Some(job.compact_lsn_range.into()),
    3052            0 :                                         sub_compaction_max_job_size_mb: None,
    3053            0 :                                     };
    3054            0 :                                     tline_pending_tasks.push_back(if idx == jobs_len - 1 {
    3055            0 :                                         ScheduledCompactionTask {
    3056            0 :                                             options,
    3057            0 :                                             // The last job in the queue sends the signal and releases the gc guard
    3058            0 :                                             result_tx: next_scheduled_compaction_task
    3059            0 :                                                 .result_tx
    3060            0 :                                                 .take(),
    3061            0 :                                             gc_block: next_scheduled_compaction_task
    3062            0 :                                                 .gc_block
    3063            0 :                                                 .take(),
    3064            0 :                                         }
    3065              :                                     } else {
    3066            0 :                                         ScheduledCompactionTask {
    3067            0 :                                             options,
    3068            0 :                                             result_tx: None,
    3069            0 :                                             gc_block: None,
    3070            0 :                                         }
    3071              :                                     });
    3072              :                                 }
    3073            0 :                                 info!("scheduled enhanced gc bottom-most compaction with sub-compaction, split into {} jobs", jobs_len);
    3074              :                             }
    3075              :                         } else {
    3076            0 :                             let _ = timeline
    3077            0 :                                 .compact_with_options(
    3078            0 :                                     cancel,
    3079            0 :                                     next_scheduled_compaction_task.options,
    3080            0 :                                     ctx,
    3081            0 :                                 )
    3082            0 :                                 .instrument(info_span!("scheduled_compact_timeline", %timeline_id))
    3083            0 :                                 .await?;
    3084            0 :                             if let Some(tx) = next_scheduled_compaction_task.result_tx.take() {
    3085            0 :                                 // TODO: we can send compaction statistics in the future
    3086            0 :                                 tx.send(()).ok();
    3087            0 :                             }
    3088              :                         }
    3089            0 :                     }
    3090            0 :                     Some(has_pending_scheduled_compaction_task)
    3091              :                 }
    3092              :             } else {
    3093            0 :                 None
    3094              :             };
    3095            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    3096            0 :             if pending_task_left == Some(false) && *can_offload {
    3097            0 :                 offload_timeline(self, timeline)
    3098            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    3099            0 :                     .await?;
    3100            0 :             }
    3101              :         }
    3102              : 
    3103            0 :         self.compaction_circuit_breaker
    3104            0 :             .lock()
    3105            0 :             .unwrap()
    3106            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3107            0 : 
    3108            0 :         Ok(has_pending_task)
    3109            0 :     }
    3110              : 
    3111              :     /// Cancel scheduled compaction tasks
    3112            0 :     pub(crate) fn cancel_scheduled_compaction(
    3113            0 :         &self,
    3114            0 :         timeline_id: TimelineId,
    3115            0 :     ) -> Vec<ScheduledCompactionTask> {
    3116            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3117            0 :         if let Some(tline_pending_tasks) = guard.get_mut(&timeline_id) {
    3118            0 :             let current_tline_pending_tasks = std::mem::take(tline_pending_tasks);
    3119            0 :             current_tline_pending_tasks.into_iter().collect()
    3120              :         } else {
    3121            0 :             Vec::new()
    3122              :         }
    3123            0 :     }
    3124              : 
    3125            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3126            0 :         &self,
    3127            0 :         timeline_id: TimelineId,
    3128            0 :     ) -> Vec<CompactOptions> {
    3129              :         use itertools::Itertools;
    3130            0 :         let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3131            0 :         guard
    3132            0 :             .get(&timeline_id)
    3133            0 :             .map(|tline_pending_tasks| {
    3134            0 :                 tline_pending_tasks
    3135            0 :                     .iter()
    3136            0 :                     .map(|x| x.options.clone())
    3137            0 :                     .collect_vec()
    3138            0 :             })
    3139            0 :             .unwrap_or_default()
    3140            0 :     }
    3141              : 
    3142              :     /// Schedule a compaction task for a timeline.
    3143            0 :     pub(crate) async fn schedule_compaction(
    3144            0 :         &self,
    3145            0 :         timeline_id: TimelineId,
    3146            0 :         options: CompactOptions,
    3147            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3148            0 :         let gc_guard = match self.gc_block.start().await {
    3149            0 :             Ok(guard) => guard,
    3150            0 :             Err(e) => {
    3151            0 :                 bail!("cannot run gc-compaction because gc is blocked: {}", e);
    3152              :             }
    3153              :         };
    3154            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3155            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3156            0 :         let tline_pending_tasks = guard.entry(timeline_id).or_default();
    3157            0 :         tline_pending_tasks.push_back(ScheduledCompactionTask {
    3158            0 :             options,
    3159            0 :             result_tx: Some(tx),
    3160            0 :             gc_block: Some(gc_guard),
    3161            0 :         });
    3162            0 :         Ok(rx)
    3163            0 :     }
    3164              : 
    3165              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    3166              :     // this happens during ingest: this background housekeeping is for freezing layers
    3167              :     // that are open but haven't been written to for some time.
    3168            0 :     async fn ingest_housekeeping(&self) {
    3169            0 :         // Scan through the hashmap and collect a list of all the timelines,
    3170            0 :         // while holding the lock. Then drop the lock and actually perform the
    3171            0 :         // compactions.  We don't want to block everything else while the
    3172            0 :         // compaction runs.
    3173            0 :         let timelines = {
    3174            0 :             self.timelines
    3175            0 :                 .lock()
    3176            0 :                 .unwrap()
    3177            0 :                 .values()
    3178            0 :                 .filter_map(|timeline| {
    3179            0 :                     if timeline.is_active() {
    3180            0 :                         Some(timeline.clone())
    3181              :                     } else {
    3182            0 :                         None
    3183              :                     }
    3184            0 :                 })
    3185            0 :                 .collect::<Vec<_>>()
    3186              :         };
    3187              : 
    3188            0 :         for timeline in &timelines {
    3189            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3190              :         }
    3191            0 :     }
    3192              : 
    3193            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3194            0 :         let timelines = self.timelines.lock().unwrap();
    3195            0 :         !timelines
    3196            0 :             .iter()
    3197            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3198            0 :     }
    3199              : 
    3200         1706 :     pub fn current_state(&self) -> TenantState {
    3201         1706 :         self.state.borrow().clone()
    3202         1706 :     }
    3203              : 
    3204          946 :     pub fn is_active(&self) -> bool {
    3205          946 :         self.current_state() == TenantState::Active
    3206          946 :     }
    3207              : 
    3208            0 :     pub fn generation(&self) -> Generation {
    3209            0 :         self.generation
    3210            0 :     }
    3211              : 
    3212            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3213            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3214            0 :     }
    3215              : 
    3216              :     /// Changes tenant status to active, unless shutdown was already requested.
    3217              :     ///
    3218              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3219              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3220            0 :     fn activate(
    3221            0 :         self: &Arc<Self>,
    3222            0 :         broker_client: BrokerClientChannel,
    3223            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3224            0 :         ctx: &RequestContext,
    3225            0 :     ) {
    3226            0 :         span::debug_assert_current_span_has_tenant_id();
    3227            0 : 
    3228            0 :         let mut activating = false;
    3229            0 :         self.state.send_modify(|current_state| {
    3230              :             use pageserver_api::models::ActivatingFrom;
    3231            0 :             match &*current_state {
    3232              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3233            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3234              :                 }
    3235            0 :                 TenantState::Attaching => {
    3236            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3237            0 :                 }
    3238            0 :             }
    3239            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3240            0 :             activating = true;
    3241            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3242            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3243            0 :         });
    3244            0 : 
    3245            0 :         if activating {
    3246            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3247            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3248            0 :             let timelines_to_activate = timelines_accessor
    3249            0 :                 .values()
    3250            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3251            0 : 
    3252            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3253            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3254            0 : 
    3255            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3256            0 :             // down when they notice that the tenant is inactive.
    3257            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3258            0 : 
    3259            0 :             let mut activated_timelines = 0;
    3260              : 
    3261            0 :             for timeline in timelines_to_activate {
    3262            0 :                 timeline.activate(
    3263            0 :                     self.clone(),
    3264            0 :                     broker_client.clone(),
    3265            0 :                     background_jobs_can_start,
    3266            0 :                     ctx,
    3267            0 :                 );
    3268            0 :                 activated_timelines += 1;
    3269            0 :             }
    3270              : 
    3271            0 :             self.state.send_modify(move |current_state| {
    3272            0 :                 assert!(
    3273            0 :                     matches!(current_state, TenantState::Activating(_)),
    3274            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3275              :                 );
    3276            0 :                 *current_state = TenantState::Active;
    3277            0 : 
    3278            0 :                 let elapsed = self.constructed_at.elapsed();
    3279            0 :                 let total_timelines = timelines_accessor.len();
    3280            0 : 
    3281            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3282            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3283            0 :                 info!(
    3284            0 :                     since_creation_millis = elapsed.as_millis(),
    3285            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3286            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3287            0 :                     activated_timelines,
    3288            0 :                     total_timelines,
    3289            0 :                     post_state = <&'static str>::from(&*current_state),
    3290            0 :                     "activation attempt finished"
    3291              :                 );
    3292              : 
    3293            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3294            0 :             });
    3295            0 :         }
    3296            0 :     }
    3297              : 
    3298              :     /// Shutdown the tenant and join all of the spawned tasks.
    3299              :     ///
    3300              :     /// The method caters for all use-cases:
    3301              :     /// - pageserver shutdown (freeze_and_flush == true)
    3302              :     /// - detach + ignore (freeze_and_flush == false)
    3303              :     ///
    3304              :     /// This will attempt to shutdown even if tenant is broken.
    3305              :     ///
    3306              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3307              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3308              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3309              :     /// the ongoing shutdown.
    3310            6 :     async fn shutdown(
    3311            6 :         &self,
    3312            6 :         shutdown_progress: completion::Barrier,
    3313            6 :         shutdown_mode: timeline::ShutdownMode,
    3314            6 :     ) -> Result<(), completion::Barrier> {
    3315            6 :         span::debug_assert_current_span_has_tenant_id();
    3316              : 
    3317              :         // Set tenant (and its timlines) to Stoppping state.
    3318              :         //
    3319              :         // Since we can only transition into Stopping state after activation is complete,
    3320              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3321              :         //
    3322              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3323              :         // 1. Lock out any new requests to the tenants.
    3324              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3325              :         // 3. Signal cancellation for other tenant background loops.
    3326              :         // 4. ???
    3327              :         //
    3328              :         // The waiting for the cancellation is not done uniformly.
    3329              :         // We certainly wait for WAL receivers to shut down.
    3330              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3331              :         // But the tenant background loops are joined-on in our caller.
    3332              :         // It's mesed up.
    3333              :         // we just ignore the failure to stop
    3334              : 
    3335              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3336              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3337              :         // is very slow.
    3338            6 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3339            0 :             self.cancel.cancel();
    3340            0 : 
    3341            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3342            0 :             // are children of ours, so their flush loops will have shut down already
    3343            0 :             timeline::ShutdownMode::Hard
    3344              :         } else {
    3345            6 :             shutdown_mode
    3346              :         };
    3347              : 
    3348            6 :         match self.set_stopping(shutdown_progress, false, false).await {
    3349            6 :             Ok(()) => {}
    3350            0 :             Err(SetStoppingError::Broken) => {
    3351            0 :                 // assume that this is acceptable
    3352            0 :             }
    3353            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3354            0 :                 // give caller the option to wait for this this shutdown
    3355            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3356            0 :                 return Err(other);
    3357              :             }
    3358              :         };
    3359              : 
    3360            6 :         let mut js = tokio::task::JoinSet::new();
    3361            6 :         {
    3362            6 :             let timelines = self.timelines.lock().unwrap();
    3363            6 :             timelines.values().for_each(|timeline| {
    3364            6 :                 let timeline = Arc::clone(timeline);
    3365            6 :                 let timeline_id = timeline.timeline_id;
    3366            6 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3367            6 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3368            6 :             });
    3369            6 :         }
    3370            6 :         {
    3371            6 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3372            6 :             timelines_offloaded.values().for_each(|timeline| {
    3373            0 :                 timeline.defuse_for_tenant_drop();
    3374            6 :             });
    3375            6 :         }
    3376            6 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3377            6 :         tracing::info!("Waiting for timelines...");
    3378           12 :         while let Some(res) = js.join_next().await {
    3379            0 :             match res {
    3380            6 :                 Ok(()) => {}
    3381            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3382            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3383            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3384              :             }
    3385              :         }
    3386              : 
    3387            6 :         if let ShutdownMode::Reload = shutdown_mode {
    3388            0 :             tracing::info!("Flushing deletion queue");
    3389            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3390            0 :                 match e {
    3391            0 :                     DeletionQueueError::ShuttingDown => {
    3392            0 :                         // This is the only error we expect for now. In the future, if more error
    3393            0 :                         // variants are added, we should handle them here.
    3394            0 :                     }
    3395              :                 }
    3396            0 :             }
    3397            6 :         }
    3398              : 
    3399              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3400              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3401            6 :         tracing::debug!("Cancelling CancellationToken");
    3402            6 :         self.cancel.cancel();
    3403            6 : 
    3404            6 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3405            6 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3406            6 :         //
    3407            6 :         // this will additionally shutdown and await all timeline tasks.
    3408            6 :         tracing::debug!("Waiting for tasks...");
    3409            6 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3410              : 
    3411            6 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3412            6 :             walredo_mgr.shutdown().await;
    3413            0 :         }
    3414              : 
    3415              :         // Wait for any in-flight operations to complete
    3416            6 :         self.gate.close().await;
    3417              : 
    3418            6 :         remove_tenant_metrics(&self.tenant_shard_id);
    3419            6 : 
    3420            6 :         Ok(())
    3421            6 :     }
    3422              : 
    3423              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3424              :     ///
    3425              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3426              :     ///
    3427              :     /// This function is not cancel-safe!
    3428              :     ///
    3429              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3430              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3431            6 :     async fn set_stopping(
    3432            6 :         &self,
    3433            6 :         progress: completion::Barrier,
    3434            6 :         _allow_transition_from_loading: bool,
    3435            6 :         allow_transition_from_attaching: bool,
    3436            6 :     ) -> Result<(), SetStoppingError> {
    3437            6 :         let mut rx = self.state.subscribe();
    3438            6 : 
    3439            6 :         // cannot stop before we're done activating, so wait out until we're done activating
    3440            6 :         rx.wait_for(|state| match state {
    3441            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3442              :             TenantState::Activating(_) | TenantState::Attaching => {
    3443            0 :                 info!(
    3444            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3445            0 :                     <&'static str>::from(state)
    3446              :                 );
    3447            0 :                 false
    3448              :             }
    3449            6 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3450            6 :         })
    3451            6 :         .await
    3452            6 :         .expect("cannot drop self.state while on a &self method");
    3453            6 : 
    3454            6 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3455            6 :         let mut err = None;
    3456            6 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3457              :             TenantState::Activating(_) => {
    3458            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3459              :             }
    3460              :             TenantState::Attaching => {
    3461            0 :                 if !allow_transition_from_attaching {
    3462            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3463            0 :                 };
    3464            0 :                 *current_state = TenantState::Stopping { progress };
    3465            0 :                 true
    3466              :             }
    3467              :             TenantState::Active => {
    3468              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3469              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3470              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3471            6 :                 *current_state = TenantState::Stopping { progress };
    3472            6 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3473            6 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3474            6 :                 true
    3475              :             }
    3476            0 :             TenantState::Broken { reason, .. } => {
    3477            0 :                 info!(
    3478            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3479              :                 );
    3480            0 :                 err = Some(SetStoppingError::Broken);
    3481            0 :                 false
    3482              :             }
    3483            0 :             TenantState::Stopping { progress } => {
    3484            0 :                 info!("Tenant is already in Stopping state");
    3485            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3486            0 :                 false
    3487              :             }
    3488            6 :         });
    3489            6 :         match (stopping, err) {
    3490            6 :             (true, None) => {} // continue
    3491            0 :             (false, Some(err)) => return Err(err),
    3492            0 :             (true, Some(_)) => unreachable!(
    3493            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3494            0 :             ),
    3495            0 :             (false, None) => unreachable!(
    3496            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3497            0 :             ),
    3498              :         }
    3499              : 
    3500            6 :         let timelines_accessor = self.timelines.lock().unwrap();
    3501            6 :         let not_broken_timelines = timelines_accessor
    3502            6 :             .values()
    3503            6 :             .filter(|timeline| !timeline.is_broken());
    3504           12 :         for timeline in not_broken_timelines {
    3505            6 :             timeline.set_state(TimelineState::Stopping);
    3506            6 :         }
    3507            6 :         Ok(())
    3508            6 :     }
    3509              : 
    3510              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3511              :     /// `remove_tenant_from_memory`
    3512              :     ///
    3513              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3514              :     ///
    3515              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3516            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3517            0 :         let mut rx = self.state.subscribe();
    3518            0 : 
    3519            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3520            0 :         // So, wait until it's done.
    3521            0 :         rx.wait_for(|state| match state {
    3522              :             TenantState::Activating(_) | TenantState::Attaching => {
    3523            0 :                 info!(
    3524            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3525            0 :                     <&'static str>::from(state)
    3526              :                 );
    3527            0 :                 false
    3528              :             }
    3529            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3530            0 :         })
    3531            0 :         .await
    3532            0 :         .expect("cannot drop self.state while on a &self method");
    3533            0 : 
    3534            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3535            0 :         self.set_broken_no_wait(reason)
    3536            0 :     }
    3537              : 
    3538            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3539            0 :         let reason = reason.to_string();
    3540            0 :         self.state.send_modify(|current_state| {
    3541            0 :             match *current_state {
    3542              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3543            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3544              :                 }
    3545              :                 TenantState::Active => {
    3546            0 :                     if cfg!(feature = "testing") {
    3547            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3548            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3549              :                     } else {
    3550            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3551              :                     }
    3552              :                 }
    3553              :                 TenantState::Broken { .. } => {
    3554            0 :                     warn!("Tenant is already in Broken state");
    3555              :                 }
    3556              :                 // This is the only "expected" path, any other path is a bug.
    3557              :                 TenantState::Stopping { .. } => {
    3558            0 :                     warn!(
    3559            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3560              :                         reason
    3561              :                     );
    3562            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3563              :                 }
    3564              :            }
    3565            0 :         });
    3566            0 :     }
    3567              : 
    3568            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3569            0 :         self.state.subscribe()
    3570            0 :     }
    3571              : 
    3572              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3573              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3574            0 :     pub(crate) fn activate_now(&self) {
    3575            0 :         self.activate_now_sem.add_permits(1);
    3576            0 :     }
    3577              : 
    3578            0 :     pub(crate) async fn wait_to_become_active(
    3579            0 :         &self,
    3580            0 :         timeout: Duration,
    3581            0 :     ) -> Result<(), GetActiveTenantError> {
    3582            0 :         let mut receiver = self.state.subscribe();
    3583              :         loop {
    3584            0 :             let current_state = receiver.borrow_and_update().clone();
    3585            0 :             match current_state {
    3586              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3587              :                     // in these states, there's a chance that we can reach ::Active
    3588            0 :                     self.activate_now();
    3589            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3590            0 :                         Ok(r) => {
    3591            0 :                             r.map_err(
    3592            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3593              :                                 // Tenant existed but was dropped: report it as non-existent
    3594            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3595            0 :                         )?
    3596              :                         }
    3597              :                         Err(TimeoutCancellableError::Cancelled) => {
    3598            0 :                             return Err(GetActiveTenantError::Cancelled);
    3599              :                         }
    3600              :                         Err(TimeoutCancellableError::Timeout) => {
    3601            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3602            0 :                                 latest_state: Some(self.current_state()),
    3603            0 :                                 wait_time: timeout,
    3604            0 :                             });
    3605              :                         }
    3606              :                     }
    3607              :                 }
    3608              :                 TenantState::Active { .. } => {
    3609            0 :                     return Ok(());
    3610              :                 }
    3611            0 :                 TenantState::Broken { reason, .. } => {
    3612            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3613            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3614            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3615              :                 }
    3616              :                 TenantState::Stopping { .. } => {
    3617              :                     // There's no chance the tenant can transition back into ::Active
    3618            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3619              :                 }
    3620              :             }
    3621              :         }
    3622            0 :     }
    3623              : 
    3624            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3625            0 :         self.tenant_conf.load().location.attach_mode
    3626            0 :     }
    3627              : 
    3628              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3629              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3630              :     /// rare external API calls, like a reconciliation at startup.
    3631            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3632            0 :         let conf = self.tenant_conf.load();
    3633              : 
    3634            0 :         let location_config_mode = match conf.location.attach_mode {
    3635            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3636            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3637            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3638              :         };
    3639              : 
    3640              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3641            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3642            0 : 
    3643            0 :         models::LocationConfig {
    3644            0 :             mode: location_config_mode,
    3645            0 :             generation: self.generation.into(),
    3646            0 :             secondary_conf: None,
    3647            0 :             shard_number: self.shard_identity.number.0,
    3648            0 :             shard_count: self.shard_identity.count.literal(),
    3649            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3650            0 :             tenant_conf: tenant_config,
    3651            0 :         }
    3652            0 :     }
    3653              : 
    3654            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3655            0 :         &self.tenant_shard_id
    3656            0 :     }
    3657              : 
    3658            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3659            0 :         self.shard_identity.stripe_size
    3660            0 :     }
    3661              : 
    3662            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3663            0 :         self.generation
    3664            0 :     }
    3665              : 
    3666              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3667              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3668              :     /// resetting this tenant to a valid state if we fail.
    3669            0 :     pub(crate) async fn split_prepare(
    3670            0 :         &self,
    3671            0 :         child_shards: &Vec<TenantShardId>,
    3672            0 :     ) -> anyhow::Result<()> {
    3673            0 :         let (timelines, offloaded) = {
    3674            0 :             let timelines = self.timelines.lock().unwrap();
    3675            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3676            0 :             (timelines.clone(), offloaded.clone())
    3677            0 :         };
    3678            0 :         let timelines_iter = timelines
    3679            0 :             .values()
    3680            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3681            0 :             .chain(
    3682            0 :                 offloaded
    3683            0 :                     .values()
    3684            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3685            0 :             );
    3686            0 :         for timeline in timelines_iter {
    3687              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3688              :             // to ensure that they do not start a split if currently in the process of doing these.
    3689              : 
    3690            0 :             let timeline_id = timeline.timeline_id();
    3691              : 
    3692            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3693              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3694              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3695              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3696            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3697            0 :                 timeline
    3698            0 :                     .remote_client
    3699            0 :                     .schedule_index_upload_for_file_changes()?;
    3700            0 :                 timeline.remote_client.wait_completion().await?;
    3701            0 :             }
    3702              : 
    3703            0 :             let remote_client = match timeline {
    3704            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3705            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3706            0 :                     let remote_client = self
    3707            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3708            0 :                     Arc::new(remote_client)
    3709              :                 }
    3710              :             };
    3711              : 
    3712              :             // Shut down the timeline's remote client: this means that the indices we write
    3713              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3714            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3715            0 :             remote_client.shutdown().await;
    3716              : 
    3717              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3718              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3719              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3720              :             // we use here really is the remotely persistent one).
    3721            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3722            0 :             let result = remote_client
    3723            0 :                 .download_index_file(&self.cancel)
    3724            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))
    3725            0 :                 .await?;
    3726            0 :             let index_part = match result {
    3727              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3728            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3729              :                 }
    3730            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3731              :             };
    3732              : 
    3733            0 :             for child_shard in child_shards {
    3734            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3735            0 :                 upload_index_part(
    3736            0 :                     &self.remote_storage,
    3737            0 :                     child_shard,
    3738            0 :                     &timeline_id,
    3739            0 :                     self.generation,
    3740            0 :                     &index_part,
    3741            0 :                     &self.cancel,
    3742            0 :                 )
    3743            0 :                 .await?;
    3744              :             }
    3745              :         }
    3746              : 
    3747            0 :         let tenant_manifest = self.build_tenant_manifest();
    3748            0 :         for child_shard in child_shards {
    3749            0 :             tracing::info!(
    3750            0 :                 "Uploading tenant manifest for child {}",
    3751            0 :                 child_shard.to_index()
    3752              :             );
    3753            0 :             upload_tenant_manifest(
    3754            0 :                 &self.remote_storage,
    3755            0 :                 child_shard,
    3756            0 :                 self.generation,
    3757            0 :                 &tenant_manifest,
    3758            0 :                 &self.cancel,
    3759            0 :             )
    3760            0 :             .await?;
    3761              :         }
    3762              : 
    3763            0 :         Ok(())
    3764            0 :     }
    3765              : 
    3766            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3767            0 :         let mut result = TopTenantShardItem {
    3768            0 :             id: self.tenant_shard_id,
    3769            0 :             resident_size: 0,
    3770            0 :             physical_size: 0,
    3771            0 :             max_logical_size: 0,
    3772            0 :         };
    3773              : 
    3774            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3775            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3776            0 : 
    3777            0 :             result.physical_size += timeline
    3778            0 :                 .remote_client
    3779            0 :                 .metrics
    3780            0 :                 .remote_physical_size_gauge
    3781            0 :                 .get();
    3782            0 :             result.max_logical_size = std::cmp::max(
    3783            0 :                 result.max_logical_size,
    3784            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3785            0 :             );
    3786            0 :         }
    3787              : 
    3788            0 :         result
    3789            0 :     }
    3790              : }
    3791              : 
    3792              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3793              : /// perform a topological sort, so that the parent of each timeline comes
    3794              : /// before the children.
    3795              : /// E extracts the ancestor from T
    3796              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3797          196 : fn tree_sort_timelines<T, E>(
    3798          196 :     timelines: HashMap<TimelineId, T>,
    3799          196 :     extractor: E,
    3800          196 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3801          196 : where
    3802          196 :     E: Fn(&T) -> Option<TimelineId>,
    3803          196 : {
    3804          196 :     let mut result = Vec::with_capacity(timelines.len());
    3805          196 : 
    3806          196 :     let mut now = Vec::with_capacity(timelines.len());
    3807          196 :     // (ancestor, children)
    3808          196 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3809          196 :         HashMap::with_capacity(timelines.len());
    3810              : 
    3811          202 :     for (timeline_id, value) in timelines {
    3812            6 :         if let Some(ancestor_id) = extractor(&value) {
    3813            2 :             let children = later.entry(ancestor_id).or_default();
    3814            2 :             children.push((timeline_id, value));
    3815            4 :         } else {
    3816            4 :             now.push((timeline_id, value));
    3817            4 :         }
    3818              :     }
    3819              : 
    3820          202 :     while let Some((timeline_id, metadata)) = now.pop() {
    3821            6 :         result.push((timeline_id, metadata));
    3822              :         // All children of this can be loaded now
    3823            6 :         if let Some(mut children) = later.remove(&timeline_id) {
    3824            2 :             now.append(&mut children);
    3825            4 :         }
    3826              :     }
    3827              : 
    3828              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3829          196 :     if !later.is_empty() {
    3830            0 :         for (missing_id, orphan_ids) in later {
    3831            0 :             for (orphan_id, _) in orphan_ids {
    3832            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3833              :             }
    3834              :         }
    3835            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3836          196 :     }
    3837          196 : 
    3838          196 :     Ok(result)
    3839          196 : }
    3840              : 
    3841              : enum ActivateTimelineArgs {
    3842              :     Yes {
    3843              :         broker_client: storage_broker::BrokerClientChannel,
    3844              :     },
    3845              :     No,
    3846              : }
    3847              : 
    3848              : impl Tenant {
    3849            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3850            0 :         self.tenant_conf.load().tenant_conf.clone()
    3851            0 :     }
    3852              : 
    3853            0 :     pub fn effective_config(&self) -> TenantConf {
    3854            0 :         self.tenant_specific_overrides()
    3855            0 :             .merge(self.conf.default_tenant_conf.clone())
    3856            0 :     }
    3857              : 
    3858            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3859            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3860            0 :         tenant_conf
    3861            0 :             .checkpoint_distance
    3862            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3863            0 :     }
    3864              : 
    3865            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3866            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3867            0 :         tenant_conf
    3868            0 :             .checkpoint_timeout
    3869            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3870            0 :     }
    3871              : 
    3872            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3873            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3874            0 :         tenant_conf
    3875            0 :             .compaction_target_size
    3876            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3877            0 :     }
    3878              : 
    3879            0 :     pub fn get_compaction_period(&self) -> Duration {
    3880            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3881            0 :         tenant_conf
    3882            0 :             .compaction_period
    3883            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3884            0 :     }
    3885              : 
    3886            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3887            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3888            0 :         tenant_conf
    3889            0 :             .compaction_threshold
    3890            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3891            0 :     }
    3892              : 
    3893            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3894            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3895            0 :         tenant_conf
    3896            0 :             .gc_horizon
    3897            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3898            0 :     }
    3899              : 
    3900            0 :     pub fn get_gc_period(&self) -> Duration {
    3901            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3902            0 :         tenant_conf
    3903            0 :             .gc_period
    3904            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3905            0 :     }
    3906              : 
    3907            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3908            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3909            0 :         tenant_conf
    3910            0 :             .image_creation_threshold
    3911            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3912            0 :     }
    3913              : 
    3914            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3915            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3916            0 :         tenant_conf
    3917            0 :             .pitr_interval
    3918            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3919            0 :     }
    3920              : 
    3921            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3922            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3923            0 :         tenant_conf
    3924            0 :             .min_resident_size_override
    3925            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3926            0 :     }
    3927              : 
    3928            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3929            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3930            0 :         let heatmap_period = tenant_conf
    3931            0 :             .heatmap_period
    3932            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3933            0 :         if heatmap_period.is_zero() {
    3934            0 :             None
    3935              :         } else {
    3936            0 :             Some(heatmap_period)
    3937              :         }
    3938            0 :     }
    3939              : 
    3940            4 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3941            4 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3942            4 :         tenant_conf
    3943            4 :             .lsn_lease_length
    3944            4 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3945            4 :     }
    3946              : 
    3947              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3948            2 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3949            2 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3950            2 : 
    3951            2 :         let mut timeline_manifests = timelines_offloaded
    3952            2 :             .iter()
    3953            2 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3954            2 :             .collect::<Vec<_>>();
    3955            2 :         // Sort the manifests so that our output is deterministic
    3956            2 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3957            2 : 
    3958            2 :         TenantManifest {
    3959            2 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3960            2 :             offloaded_timelines: timeline_manifests,
    3961            2 :         }
    3962            2 :     }
    3963              : 
    3964            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    3965            0 :         &self,
    3966            0 :         update: F,
    3967            0 :     ) -> anyhow::Result<TenantConfOpt> {
    3968            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3969            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3970            0 :         // this race is not possible if both request types come from the storage
    3971            0 :         // controller (as they should!) because an exclusive op lock is required
    3972            0 :         // on the storage controller side.
    3973            0 : 
    3974            0 :         self.tenant_conf
    3975            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    3976            0 :                 Ok(Arc::new(AttachedTenantConf {
    3977            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    3978            0 :                     location: attached_conf.location,
    3979            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    3980              :                 }))
    3981            0 :             })?;
    3982              : 
    3983            0 :         let updated = self.tenant_conf.load();
    3984            0 : 
    3985            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    3986            0 :         // Don't hold self.timelines.lock() during the notifies.
    3987            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3988            0 :         // mutexes in struct Timeline in the future.
    3989            0 :         let timelines = self.list_timelines();
    3990            0 :         for timeline in timelines {
    3991            0 :             timeline.tenant_conf_updated(&updated);
    3992            0 :         }
    3993              : 
    3994            0 :         Ok(updated.tenant_conf.clone())
    3995            0 :     }
    3996              : 
    3997            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3998            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3999            0 : 
    4000            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4001            0 : 
    4002            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4003            0 :         // Don't hold self.timelines.lock() during the notifies.
    4004            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4005            0 :         // mutexes in struct Timeline in the future.
    4006            0 :         let timelines = self.list_timelines();
    4007            0 :         for timeline in timelines {
    4008            0 :             timeline.tenant_conf_updated(&new_conf);
    4009            0 :         }
    4010            0 :     }
    4011              : 
    4012          196 :     fn get_pagestream_throttle_config(
    4013          196 :         psconf: &'static PageServerConf,
    4014          196 :         overrides: &TenantConfOpt,
    4015          196 :     ) -> throttle::Config {
    4016          196 :         overrides
    4017          196 :             .timeline_get_throttle
    4018          196 :             .clone()
    4019          196 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4020          196 :     }
    4021              : 
    4022            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    4023            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4024            0 :         self.pagestream_throttle.reconfigure(conf)
    4025            0 :     }
    4026              : 
    4027              :     /// Helper function to create a new Timeline struct.
    4028              :     ///
    4029              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4030              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4031              :     /// map.
    4032              :     ///
    4033              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4034              :     /// and we might not have the ancestor present anymore which is fine for to be
    4035              :     /// deleted timelines.
    4036              :     #[allow(clippy::too_many_arguments)]
    4037          422 :     fn create_timeline_struct(
    4038          422 :         &self,
    4039          422 :         new_timeline_id: TimelineId,
    4040          422 :         new_metadata: &TimelineMetadata,
    4041          422 :         ancestor: Option<Arc<Timeline>>,
    4042          422 :         resources: TimelineResources,
    4043          422 :         cause: CreateTimelineCause,
    4044          422 :         create_idempotency: CreateTimelineIdempotency,
    4045          422 :     ) -> anyhow::Result<Arc<Timeline>> {
    4046          422 :         let state = match cause {
    4047              :             CreateTimelineCause::Load => {
    4048          422 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4049          422 :                 anyhow::ensure!(
    4050          422 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4051            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4052              :                 );
    4053          422 :                 TimelineState::Loading
    4054              :             }
    4055            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4056              :         };
    4057              : 
    4058          422 :         let pg_version = new_metadata.pg_version();
    4059          422 : 
    4060          422 :         let timeline = Timeline::new(
    4061          422 :             self.conf,
    4062          422 :             Arc::clone(&self.tenant_conf),
    4063          422 :             new_metadata,
    4064          422 :             ancestor,
    4065          422 :             new_timeline_id,
    4066          422 :             self.tenant_shard_id,
    4067          422 :             self.generation,
    4068          422 :             self.shard_identity,
    4069          422 :             self.walredo_mgr.clone(),
    4070          422 :             resources,
    4071          422 :             pg_version,
    4072          422 :             state,
    4073          422 :             self.attach_wal_lag_cooldown.clone(),
    4074          422 :             create_idempotency,
    4075          422 :             self.cancel.child_token(),
    4076          422 :         );
    4077          422 : 
    4078          422 :         Ok(timeline)
    4079          422 :     }
    4080              : 
    4081              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4082              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4083              :     #[allow(clippy::too_many_arguments)]
    4084          196 :     fn new(
    4085          196 :         state: TenantState,
    4086          196 :         conf: &'static PageServerConf,
    4087          196 :         attached_conf: AttachedTenantConf,
    4088          196 :         shard_identity: ShardIdentity,
    4089          196 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4090          196 :         tenant_shard_id: TenantShardId,
    4091          196 :         remote_storage: GenericRemoteStorage,
    4092          196 :         deletion_queue_client: DeletionQueueClient,
    4093          196 :         l0_flush_global_state: L0FlushGlobalState,
    4094          196 :     ) -> Tenant {
    4095          196 :         debug_assert!(
    4096          196 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4097              :         );
    4098              : 
    4099          196 :         let (state, mut rx) = watch::channel(state);
    4100          196 : 
    4101          196 :         tokio::spawn(async move {
    4102          196 :             // reflect tenant state in metrics:
    4103          196 :             // - global per tenant state: TENANT_STATE_METRIC
    4104          196 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4105          196 :             //
    4106          196 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4107          196 :             // alerting.
    4108          196 : 
    4109          196 :             let tid = tenant_shard_id.to_string();
    4110          196 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4111          196 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4112              : 
    4113          392 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4114          392 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4115          392 :             }
    4116              : 
    4117          196 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4118          196 : 
    4119          196 :             let is_broken = tuple.1;
    4120          196 :             let mut counted_broken = if is_broken {
    4121              :                 // add the id to the set right away, there should not be any updates on the channel
    4122              :                 // after before tenant is removed, if ever
    4123            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4124            0 :                 true
    4125              :             } else {
    4126          196 :                 false
    4127              :             };
    4128              : 
    4129              :             loop {
    4130          392 :                 let labels = &tuple.0;
    4131          392 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4132          392 :                 current.inc();
    4133          392 : 
    4134          392 :                 if rx.changed().await.is_err() {
    4135              :                     // tenant has been dropped
    4136           14 :                     current.dec();
    4137           14 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4138           14 :                     break;
    4139          196 :                 }
    4140          196 : 
    4141          196 :                 current.dec();
    4142          196 :                 tuple = inspect_state(&rx.borrow_and_update());
    4143          196 : 
    4144          196 :                 let is_broken = tuple.1;
    4145          196 :                 if is_broken && !counted_broken {
    4146            0 :                     counted_broken = true;
    4147            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4148            0 :                     // access
    4149            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4150          196 :                 }
    4151              :             }
    4152          196 :         });
    4153          196 : 
    4154          196 :         Tenant {
    4155          196 :             tenant_shard_id,
    4156          196 :             shard_identity,
    4157          196 :             generation: attached_conf.location.generation,
    4158          196 :             conf,
    4159          196 :             // using now here is good enough approximation to catch tenants with really long
    4160          196 :             // activation times.
    4161          196 :             constructed_at: Instant::now(),
    4162          196 :             timelines: Mutex::new(HashMap::new()),
    4163          196 :             timelines_creating: Mutex::new(HashSet::new()),
    4164          196 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4165          196 :             tenant_manifest_upload: Default::default(),
    4166          196 :             gc_cs: tokio::sync::Mutex::new(()),
    4167          196 :             walredo_mgr,
    4168          196 :             remote_storage,
    4169          196 :             deletion_queue_client,
    4170          196 :             state,
    4171          196 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4172          196 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4173          196 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4174          196 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4175          196 :                 format!("compaction-{tenant_shard_id}"),
    4176          196 :                 5,
    4177          196 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4178          196 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4179          196 :                 // use an extremely long backoff.
    4180          196 :                 Some(Duration::from_secs(3600 * 24)),
    4181          196 :             )),
    4182          196 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4183          196 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4184          196 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4185          196 :             cancel: CancellationToken::default(),
    4186          196 :             gate: Gate::default(),
    4187          196 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4188          196 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4189          196 :                 crate::metrics::tenant_throttling::Metrics::new(&tenant_shard_id),
    4190          196 :             )),
    4191          196 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4192          196 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4193          196 :             gc_block: Default::default(),
    4194          196 :             l0_flush_global_state,
    4195          196 :         }
    4196          196 :     }
    4197              : 
    4198              :     /// Locate and load config
    4199            0 :     pub(super) fn load_tenant_config(
    4200            0 :         conf: &'static PageServerConf,
    4201            0 :         tenant_shard_id: &TenantShardId,
    4202            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4203            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4204            0 : 
    4205            0 :         info!("loading tenant configuration from {config_path}");
    4206              : 
    4207              :         // load and parse file
    4208            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4209            0 :             match e.kind() {
    4210              :                 std::io::ErrorKind::NotFound => {
    4211              :                     // The config should almost always exist for a tenant directory:
    4212              :                     //  - When attaching a tenant, the config is the first thing we write
    4213              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4214              :                     //    before deleting contents.
    4215              :                     //
    4216              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4217              :                     // between creating directory and writing config.  Callers should handle that as if the
    4218              :                     // directory didn't exist.
    4219              : 
    4220            0 :                     LoadConfigError::NotFound(config_path)
    4221              :                 }
    4222              :                 _ => {
    4223              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4224              :                     // that we cannot cleanly recover
    4225            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4226              :                 }
    4227              :             }
    4228            0 :         })?;
    4229              : 
    4230            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4231            0 :     }
    4232              : 
    4233            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4234              :     pub(super) async fn persist_tenant_config(
    4235              :         conf: &'static PageServerConf,
    4236              :         tenant_shard_id: &TenantShardId,
    4237              :         location_conf: &LocationConf,
    4238              :     ) -> std::io::Result<()> {
    4239              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4240              : 
    4241              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4242              :     }
    4243              : 
    4244            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4245              :     pub(super) async fn persist_tenant_config_at(
    4246              :         tenant_shard_id: &TenantShardId,
    4247              :         config_path: &Utf8Path,
    4248              :         location_conf: &LocationConf,
    4249              :     ) -> std::io::Result<()> {
    4250              :         debug!("persisting tenantconf to {config_path}");
    4251              : 
    4252              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4253              : #  It is read in case of pageserver restart.
    4254              : "#
    4255              :         .to_string();
    4256              : 
    4257            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4258            0 :             Err(std::io::Error::new(
    4259            0 :                 std::io::ErrorKind::Other,
    4260            0 :                 "tenant-config-before-write",
    4261            0 :             ))
    4262            0 :         });
    4263              : 
    4264              :         // Convert the config to a toml file.
    4265              :         conf_content +=
    4266              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4267              : 
    4268              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4269              : 
    4270              :         let conf_content = conf_content.into_bytes();
    4271              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4272              :     }
    4273              : 
    4274              :     //
    4275              :     // How garbage collection works:
    4276              :     //
    4277              :     //                    +--bar------------->
    4278              :     //                   /
    4279              :     //             +----+-----foo---------------->
    4280              :     //            /
    4281              :     // ----main--+-------------------------->
    4282              :     //                \
    4283              :     //                 +-----baz-------->
    4284              :     //
    4285              :     //
    4286              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4287              :     //    `gc_infos` are being refreshed
    4288              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4289              :     //    all the points where other timelines have been branched off.
    4290              :     //    We will refrain from removing page versions at those LSNs.
    4291              :     // 3. For each timeline, scan all layer files on the timeline.
    4292              :     //    Remove all files for which a newer file exists and which
    4293              :     //    don't cover any branch point LSNs.
    4294              :     //
    4295              :     // TODO:
    4296              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4297              :     //   don't need to keep that in the parent anymore. But currently
    4298              :     //   we do.
    4299            4 :     async fn gc_iteration_internal(
    4300            4 :         &self,
    4301            4 :         target_timeline_id: Option<TimelineId>,
    4302            4 :         horizon: u64,
    4303            4 :         pitr: Duration,
    4304            4 :         cancel: &CancellationToken,
    4305            4 :         ctx: &RequestContext,
    4306            4 :     ) -> Result<GcResult, GcError> {
    4307            4 :         let mut totals: GcResult = Default::default();
    4308            4 :         let now = Instant::now();
    4309              : 
    4310            4 :         let gc_timelines = self
    4311            4 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4312            4 :             .await?;
    4313              : 
    4314            4 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4315              : 
    4316              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4317            4 :         if !gc_timelines.is_empty() {
    4318            4 :             info!("{} timelines need GC", gc_timelines.len());
    4319              :         } else {
    4320            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4321              :         }
    4322              : 
    4323              :         // Perform GC for each timeline.
    4324              :         //
    4325              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4326              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4327              :         // with branch creation.
    4328              :         //
    4329              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4330              :         // creation task can run concurrently with timeline's GC iteration.
    4331            8 :         for timeline in gc_timelines {
    4332            4 :             if cancel.is_cancelled() {
    4333              :                 // We were requested to shut down. Stop and return with the progress we
    4334              :                 // made.
    4335            0 :                 break;
    4336            4 :             }
    4337            4 :             let result = match timeline.gc().await {
    4338              :                 Err(GcError::TimelineCancelled) => {
    4339            0 :                     if target_timeline_id.is_some() {
    4340              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4341            0 :                         return Err(GcError::TimelineCancelled);
    4342              :                     } else {
    4343              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4344              :                         // skip past this and proceed to try GC on other timelines.
    4345            0 :                         continue;
    4346              :                     }
    4347              :                 }
    4348            4 :                 r => r?,
    4349              :             };
    4350            4 :             totals += result;
    4351              :         }
    4352              : 
    4353            4 :         totals.elapsed = now.elapsed();
    4354            4 :         Ok(totals)
    4355            4 :     }
    4356              : 
    4357              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4358              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4359              :     /// [`Tenant::get_gc_horizon`].
    4360              :     ///
    4361              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4362            0 :     pub(crate) async fn refresh_gc_info(
    4363            0 :         &self,
    4364            0 :         cancel: &CancellationToken,
    4365            0 :         ctx: &RequestContext,
    4366            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4367            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4368            0 :         // might be that these configuration values get applied faster than what it was previously,
    4369            0 :         // since these were only read from the gc task.
    4370            0 :         let horizon = self.get_gc_horizon();
    4371            0 :         let pitr = self.get_pitr_interval();
    4372            0 : 
    4373            0 :         // refresh all timelines
    4374            0 :         let target_timeline_id = None;
    4375            0 : 
    4376            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4377            0 :             .await
    4378            0 :     }
    4379              : 
    4380              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4381              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4382              :     ///
    4383              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4384            0 :     fn initialize_gc_info(
    4385            0 :         &self,
    4386            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4387            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4388            0 :         restrict_to_timeline: Option<TimelineId>,
    4389            0 :     ) {
    4390            0 :         if restrict_to_timeline.is_none() {
    4391              :             // This function must be called before activation: after activation timeline create/delete operations
    4392              :             // might happen, and this function is not safe to run concurrently with those.
    4393            0 :             assert!(!self.is_active());
    4394            0 :         }
    4395              : 
    4396              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4397              :         // the branch point where it was created.
    4398            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4399            0 :             BTreeMap::new();
    4400            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4401            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4402            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4403            0 :                 ancestor_children.push((
    4404            0 :                     timeline_entry.get_ancestor_lsn(),
    4405            0 :                     *timeline_id,
    4406            0 :                     MaybeOffloaded::No,
    4407            0 :                 ));
    4408            0 :             }
    4409            0 :         });
    4410            0 :         timelines_offloaded
    4411            0 :             .iter()
    4412            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4413            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4414            0 :                     return;
    4415              :                 };
    4416            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4417            0 :                     return;
    4418              :                 };
    4419            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4420            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4421            0 :             });
    4422            0 : 
    4423            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4424            0 :         let horizon = self.get_gc_horizon();
    4425              : 
    4426              :         // Populate each timeline's GcInfo with information about its child branches
    4427            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4428            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4429              :         } else {
    4430            0 :             itertools::Either::Right(timelines.values())
    4431              :         };
    4432            0 :         for timeline in timelines_to_write {
    4433            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4434            0 :                 .remove(&timeline.timeline_id)
    4435            0 :                 .unwrap_or_default();
    4436            0 : 
    4437            0 :             branchpoints.sort_by_key(|b| b.0);
    4438            0 : 
    4439            0 :             let mut target = timeline.gc_info.write().unwrap();
    4440            0 : 
    4441            0 :             target.retain_lsns = branchpoints;
    4442            0 : 
    4443            0 :             let space_cutoff = timeline
    4444            0 :                 .get_last_record_lsn()
    4445            0 :                 .checked_sub(horizon)
    4446            0 :                 .unwrap_or(Lsn(0));
    4447            0 : 
    4448            0 :             target.cutoffs = GcCutoffs {
    4449            0 :                 space: space_cutoff,
    4450            0 :                 time: Lsn::INVALID,
    4451            0 :             };
    4452            0 :         }
    4453            0 :     }
    4454              : 
    4455            4 :     async fn refresh_gc_info_internal(
    4456            4 :         &self,
    4457            4 :         target_timeline_id: Option<TimelineId>,
    4458            4 :         horizon: u64,
    4459            4 :         pitr: Duration,
    4460            4 :         cancel: &CancellationToken,
    4461            4 :         ctx: &RequestContext,
    4462            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4463            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4464            4 :         // currently visible timelines.
    4465            4 :         let timelines = self
    4466            4 :             .timelines
    4467            4 :             .lock()
    4468            4 :             .unwrap()
    4469            4 :             .values()
    4470            4 :             .filter(|tl| match target_timeline_id.as_ref() {
    4471            4 :                 Some(target) => &tl.timeline_id == target,
    4472            0 :                 None => true,
    4473            4 :             })
    4474            4 :             .cloned()
    4475            4 :             .collect::<Vec<_>>();
    4476            4 : 
    4477            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4478              :             // We were to act on a particular timeline and it wasn't found
    4479            0 :             return Err(GcError::TimelineNotFound);
    4480            4 :         }
    4481            4 : 
    4482            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4483            4 :             HashMap::with_capacity(timelines.len());
    4484              : 
    4485            4 :         for timeline in timelines.iter() {
    4486            4 :             let cutoff = timeline
    4487            4 :                 .get_last_record_lsn()
    4488            4 :                 .checked_sub(horizon)
    4489            4 :                 .unwrap_or(Lsn(0));
    4490              : 
    4491            4 :             let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
    4492            4 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4493            4 :             assert!(old.is_none());
    4494              :         }
    4495              : 
    4496            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    4497            0 :             return Err(GcError::TenantCancelled);
    4498            4 :         }
    4499              : 
    4500              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4501              :         // because that will stall branch creation.
    4502            4 :         let gc_cs = self.gc_cs.lock().await;
    4503              : 
    4504              :         // Ok, we now know all the branch points.
    4505              :         // Update the GC information for each timeline.
    4506            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4507            8 :         for timeline in timelines {
    4508              :             // We filtered the timeline list above
    4509            4 :             if let Some(target_timeline_id) = target_timeline_id {
    4510            4 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4511            0 :             }
    4512              : 
    4513              :             {
    4514            4 :                 let mut target = timeline.gc_info.write().unwrap();
    4515            4 : 
    4516            4 :                 // Cull any expired leases
    4517            4 :                 let now = SystemTime::now();
    4518            6 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4519            4 : 
    4520            4 :                 timeline
    4521            4 :                     .metrics
    4522            4 :                     .valid_lsn_lease_count_gauge
    4523            4 :                     .set(target.leases.len() as u64);
    4524              : 
    4525              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4526            4 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4527            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4528            0 :                         target.within_ancestor_pitr =
    4529            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4530            0 :                     }
    4531            4 :                 }
    4532              : 
    4533              :                 // Update metrics that depend on GC state
    4534            4 :                 timeline
    4535            4 :                     .metrics
    4536            4 :                     .archival_size
    4537            4 :                     .set(if target.within_ancestor_pitr {
    4538            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4539              :                     } else {
    4540            4 :                         0
    4541              :                     });
    4542            4 :                 timeline.metrics.pitr_history_size.set(
    4543            4 :                     timeline
    4544            4 :                         .get_last_record_lsn()
    4545            4 :                         .checked_sub(target.cutoffs.time)
    4546            4 :                         .unwrap_or(Lsn(0))
    4547            4 :                         .0,
    4548            4 :                 );
    4549              : 
    4550              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4551              :                 // - this timeline was created while we were finding cutoffs
    4552              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4553            4 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4554            4 :                     let original_cutoffs = target.cutoffs.clone();
    4555            4 :                     // GC cutoffs should never go back
    4556            4 :                     target.cutoffs = GcCutoffs {
    4557            4 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4558            4 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4559            4 :                     }
    4560            0 :                 }
    4561              :             }
    4562              : 
    4563            4 :             gc_timelines.push(timeline);
    4564              :         }
    4565            4 :         drop(gc_cs);
    4566            4 :         Ok(gc_timelines)
    4567            4 :     }
    4568              : 
    4569              :     /// A substitute for `branch_timeline` for use in unit tests.
    4570              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4571              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4572              :     /// timeline background tasks are launched, except the flush loop.
    4573              :     #[cfg(test)]
    4574          232 :     async fn branch_timeline_test(
    4575          232 :         self: &Arc<Self>,
    4576          232 :         src_timeline: &Arc<Timeline>,
    4577          232 :         dst_id: TimelineId,
    4578          232 :         ancestor_lsn: Option<Lsn>,
    4579          232 :         ctx: &RequestContext,
    4580          232 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4581          232 :         let tl = self
    4582          232 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4583          232 :             .await?
    4584          228 :             .into_timeline_for_test();
    4585          228 :         tl.set_state(TimelineState::Active);
    4586          228 :         Ok(tl)
    4587          232 :     }
    4588              : 
    4589              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4590              :     #[cfg(test)]
    4591              :     #[allow(clippy::too_many_arguments)]
    4592            6 :     pub async fn branch_timeline_test_with_layers(
    4593            6 :         self: &Arc<Self>,
    4594            6 :         src_timeline: &Arc<Timeline>,
    4595            6 :         dst_id: TimelineId,
    4596            6 :         ancestor_lsn: Option<Lsn>,
    4597            6 :         ctx: &RequestContext,
    4598            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4599            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4600            6 :         end_lsn: Lsn,
    4601            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4602              :         use checks::check_valid_layermap;
    4603              :         use itertools::Itertools;
    4604              : 
    4605            6 :         let tline = self
    4606            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4607            6 :             .await?;
    4608            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4609            6 :             ancestor_lsn
    4610              :         } else {
    4611            0 :             tline.get_last_record_lsn()
    4612              :         };
    4613            6 :         assert!(end_lsn >= ancestor_lsn);
    4614            6 :         tline.force_advance_lsn(end_lsn);
    4615           12 :         for deltas in delta_layer_desc {
    4616            6 :             tline
    4617            6 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4618            6 :                 .await?;
    4619              :         }
    4620           10 :         for (lsn, images) in image_layer_desc {
    4621            4 :             tline
    4622            4 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4623            4 :                 .await?;
    4624              :         }
    4625            6 :         let layer_names = tline
    4626            6 :             .layers
    4627            6 :             .read()
    4628            6 :             .await
    4629            6 :             .layer_map()
    4630            6 :             .unwrap()
    4631            6 :             .iter_historic_layers()
    4632           10 :             .map(|layer| layer.layer_name())
    4633            6 :             .collect_vec();
    4634            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4635            0 :             bail!("invalid layermap: {err}");
    4636            6 :         }
    4637            6 :         Ok(tline)
    4638            6 :     }
    4639              : 
    4640              :     /// Branch an existing timeline.
    4641            0 :     async fn branch_timeline(
    4642            0 :         self: &Arc<Self>,
    4643            0 :         src_timeline: &Arc<Timeline>,
    4644            0 :         dst_id: TimelineId,
    4645            0 :         start_lsn: Option<Lsn>,
    4646            0 :         ctx: &RequestContext,
    4647            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4648            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4649            0 :             .await
    4650            0 :     }
    4651              : 
    4652          232 :     async fn branch_timeline_impl(
    4653          232 :         self: &Arc<Self>,
    4654          232 :         src_timeline: &Arc<Timeline>,
    4655          232 :         dst_id: TimelineId,
    4656          232 :         start_lsn: Option<Lsn>,
    4657          232 :         _ctx: &RequestContext,
    4658          232 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4659          232 :         let src_id = src_timeline.timeline_id;
    4660              : 
    4661              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4662              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4663              :         // valid while we are creating the branch.
    4664          232 :         let _gc_cs = self.gc_cs.lock().await;
    4665              : 
    4666              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4667          232 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4668            2 :             let lsn = src_timeline.get_last_record_lsn();
    4669            2 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4670            2 :             lsn
    4671          232 :         });
    4672              : 
    4673              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4674          232 :         let timeline_create_guard = match self
    4675          232 :             .start_creating_timeline(
    4676          232 :                 dst_id,
    4677          232 :                 CreateTimelineIdempotency::Branch {
    4678          232 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4679          232 :                     ancestor_start_lsn: start_lsn,
    4680          232 :                 },
    4681          232 :             )
    4682          232 :             .await?
    4683              :         {
    4684          232 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4685            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4686            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4687              :             }
    4688              :         };
    4689              : 
    4690              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4691              :         // horizon on the source timeline
    4692              :         //
    4693              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4694              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4695              :         // planned GC cutoff in 'gc_info' is normally larger than
    4696              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4697              :         // changed the GC settings for the tenant to make the PITR window
    4698              :         // larger, but some of the data was already removed by an earlier GC
    4699              :         // iteration.
    4700              : 
    4701              :         // check against last actual 'latest_gc_cutoff' first
    4702          232 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4703          232 :         src_timeline
    4704          232 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4705          232 :             .context(format!(
    4706          232 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4707          232 :                 *latest_gc_cutoff_lsn,
    4708          232 :             ))
    4709          232 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4710              : 
    4711              :         // and then the planned GC cutoff
    4712              :         {
    4713          228 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4714          228 :             let cutoff = gc_info.min_cutoff();
    4715          228 :             if start_lsn < cutoff {
    4716            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4717            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4718            0 :                 )));
    4719          228 :             }
    4720          228 :         }
    4721          228 : 
    4722          228 :         //
    4723          228 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4724          228 :         // so that GC cannot advance the GC cutoff until we are finished.
    4725          228 :         // Proceed with the branch creation.
    4726          228 :         //
    4727          228 : 
    4728          228 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4729          228 :         // the timeline was branched at the current end of the source timeline.
    4730          228 :         let RecordLsn {
    4731          228 :             last: src_last,
    4732          228 :             prev: src_prev,
    4733          228 :         } = src_timeline.get_last_record_rlsn();
    4734          228 :         let dst_prev = if src_last == start_lsn {
    4735          216 :             Some(src_prev)
    4736              :         } else {
    4737           12 :             None
    4738              :         };
    4739              : 
    4740              :         // Create the metadata file, noting the ancestor of the new timeline.
    4741              :         // There is initially no data in it, but all the read-calls know to look
    4742              :         // into the ancestor.
    4743          228 :         let metadata = TimelineMetadata::new(
    4744          228 :             start_lsn,
    4745          228 :             dst_prev,
    4746          228 :             Some(src_id),
    4747          228 :             start_lsn,
    4748          228 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4749          228 :             src_timeline.initdb_lsn,
    4750          228 :             src_timeline.pg_version,
    4751          228 :         );
    4752              : 
    4753          228 :         let uninitialized_timeline = self
    4754          228 :             .prepare_new_timeline(
    4755          228 :                 dst_id,
    4756          228 :                 &metadata,
    4757          228 :                 timeline_create_guard,
    4758          228 :                 start_lsn + 1,
    4759          228 :                 Some(Arc::clone(src_timeline)),
    4760          228 :             )
    4761          228 :             .await?;
    4762              : 
    4763          228 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4764              : 
    4765              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4766              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4767              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4768              :         // could get incorrect information and remove more layers, than needed.
    4769              :         // See also https://github.com/neondatabase/neon/issues/3865
    4770          228 :         new_timeline
    4771          228 :             .remote_client
    4772          228 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4773          228 :             .context("branch initial metadata upload")?;
    4774              : 
    4775              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4776              : 
    4777          228 :         Ok(CreateTimelineResult::Created(new_timeline))
    4778          232 :     }
    4779              : 
    4780              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4781              :     #[cfg(test)]
    4782            2 :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4783              :     pub(crate) async fn bootstrap_timeline_test(
    4784              :         self: &Arc<Self>,
    4785              :         timeline_id: TimelineId,
    4786              :         pg_version: u32,
    4787              :         load_existing_initdb: Option<TimelineId>,
    4788              :         ctx: &RequestContext,
    4789              :     ) -> anyhow::Result<Arc<Timeline>> {
    4790              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4791              :             .await
    4792              :             .map_err(anyhow::Error::new)
    4793            2 :             .map(|r| r.into_timeline_for_test())
    4794              :     }
    4795              : 
    4796              :     /// Get exclusive access to the timeline ID for creation.
    4797              :     ///
    4798              :     /// Timeline-creating code paths must use this function before making changes
    4799              :     /// to in-memory or persistent state.
    4800              :     ///
    4801              :     /// The `state` parameter is a description of the timeline creation operation
    4802              :     /// we intend to perform.
    4803              :     /// If the timeline was already created in the meantime, we check whether this
    4804              :     /// request conflicts or is idempotent , based on `state`.
    4805          422 :     async fn start_creating_timeline(
    4806          422 :         self: &Arc<Self>,
    4807          422 :         new_timeline_id: TimelineId,
    4808          422 :         idempotency: CreateTimelineIdempotency,
    4809          422 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4810          422 :         let allow_offloaded = false;
    4811          422 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4812          420 :             Ok(create_guard) => {
    4813          420 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4814          420 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4815              :             }
    4816            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4817              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4818              :                 // Creation is in progress, we cannot create it again, and we cannot
    4819              :                 // check if this request matches the existing one, so caller must try
    4820              :                 // again later.
    4821            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4822              :             }
    4823            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4824              :             Err(TimelineExclusionError::AlreadyExists {
    4825            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4826            0 :                 ..
    4827            0 :             }) => {
    4828            0 :                 info!("timeline already exists but is offloaded");
    4829            0 :                 Err(CreateTimelineError::Conflict)
    4830              :             }
    4831              :             Err(TimelineExclusionError::AlreadyExists {
    4832            2 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4833            2 :                 arg,
    4834            2 :             }) => {
    4835            2 :                 {
    4836            2 :                     let existing = &existing.create_idempotency;
    4837            2 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4838            2 :                     debug!("timeline already exists");
    4839              : 
    4840            2 :                     match (existing, &arg) {
    4841              :                         // FailWithConflict => no idempotency check
    4842              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4843              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4844            2 :                             warn!("timeline already exists, failing request");
    4845            2 :                             return Err(CreateTimelineError::Conflict);
    4846              :                         }
    4847              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4848            0 :                         (x, y) if x == y => {
    4849            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4850              :                             // fallthrough
    4851              :                         }
    4852              :                         (_, _) => {
    4853            0 :                             warn!("idempotency conflict, failing request");
    4854            0 :                             return Err(CreateTimelineError::Conflict);
    4855              :                         }
    4856              :                     }
    4857              :                 }
    4858              : 
    4859            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4860              :             }
    4861              :         }
    4862          422 :     }
    4863              : 
    4864            0 :     async fn upload_initdb(
    4865            0 :         &self,
    4866            0 :         timelines_path: &Utf8PathBuf,
    4867            0 :         pgdata_path: &Utf8PathBuf,
    4868            0 :         timeline_id: &TimelineId,
    4869            0 :     ) -> anyhow::Result<()> {
    4870            0 :         let temp_path = timelines_path.join(format!(
    4871            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4872            0 :         ));
    4873            0 : 
    4874            0 :         scopeguard::defer! {
    4875            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4876            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4877            0 :             }
    4878            0 :         }
    4879              : 
    4880            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4881              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4882            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4883            0 :             warn!(
    4884            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4885              :             );
    4886            0 :         }
    4887              : 
    4888            0 :         pausable_failpoint!("before-initdb-upload");
    4889              : 
    4890            0 :         backoff::retry(
    4891            0 :             || async {
    4892            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4893            0 :                     &self.remote_storage,
    4894            0 :                     &self.tenant_shard_id.tenant_id,
    4895            0 :                     timeline_id,
    4896            0 :                     pgdata_zstd.try_clone().await?,
    4897            0 :                     tar_zst_size,
    4898            0 :                     &self.cancel,
    4899            0 :                 )
    4900            0 :                 .await
    4901            0 :             },
    4902            0 :             |_| false,
    4903            0 :             3,
    4904            0 :             u32::MAX,
    4905            0 :             "persist_initdb_tar_zst",
    4906            0 :             &self.cancel,
    4907            0 :         )
    4908            0 :         .await
    4909            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4910            0 :         .and_then(|x| x)
    4911            0 :     }
    4912              : 
    4913              :     /// - run initdb to init temporary instance and get bootstrap data
    4914              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4915            2 :     async fn bootstrap_timeline(
    4916            2 :         self: &Arc<Self>,
    4917            2 :         timeline_id: TimelineId,
    4918            2 :         pg_version: u32,
    4919            2 :         load_existing_initdb: Option<TimelineId>,
    4920            2 :         ctx: &RequestContext,
    4921            2 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4922            2 :         let timeline_create_guard = match self
    4923            2 :             .start_creating_timeline(
    4924            2 :                 timeline_id,
    4925            2 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4926            2 :             )
    4927            2 :             .await?
    4928              :         {
    4929            2 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4930            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4931            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4932              :             }
    4933              :         };
    4934              : 
    4935              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4936              :         // temporary directory for basebackup files for the given timeline.
    4937              : 
    4938            2 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4939            2 :         let pgdata_path = path_with_suffix_extension(
    4940            2 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4941            2 :             TEMP_FILE_SUFFIX,
    4942            2 :         );
    4943            2 : 
    4944            2 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4945            2 :         // we won't race with other creations or existent timelines with the same path.
    4946            2 :         if pgdata_path.exists() {
    4947            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4948            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4949            0 :             })?;
    4950            2 :         }
    4951              : 
    4952              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4953            2 :         scopeguard::defer! {
    4954            2 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4955            2 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4956            2 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4957            2 :             }
    4958            2 :         }
    4959            2 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4960            2 :             if existing_initdb_timeline_id != timeline_id {
    4961            0 :                 let source_path = &remote_initdb_archive_path(
    4962            0 :                     &self.tenant_shard_id.tenant_id,
    4963            0 :                     &existing_initdb_timeline_id,
    4964            0 :                 );
    4965            0 :                 let dest_path =
    4966            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4967            0 : 
    4968            0 :                 // if this fails, it will get retried by retried control plane requests
    4969            0 :                 self.remote_storage
    4970            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4971            0 :                     .await
    4972            0 :                     .context("copy initdb tar")?;
    4973            2 :             }
    4974            2 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4975            2 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4976            2 :                     self.conf,
    4977            2 :                     &self.remote_storage,
    4978            2 :                     &self.tenant_shard_id,
    4979            2 :                     &existing_initdb_timeline_id,
    4980            2 :                     &self.cancel,
    4981            2 :                 )
    4982            2 :                 .await
    4983            2 :                 .context("download initdb tar")?;
    4984              : 
    4985            2 :             scopeguard::defer! {
    4986            2 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4987            2 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4988            2 :                 }
    4989            2 :             }
    4990            2 : 
    4991            2 :             let buf_read =
    4992            2 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4993            2 :             extract_zst_tarball(&pgdata_path, buf_read)
    4994            2 :                 .await
    4995            2 :                 .context("extract initdb tar")?;
    4996              :         } else {
    4997              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4998            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4999            0 :                 .await
    5000            0 :                 .context("run initdb")?;
    5001              : 
    5002              :             // Upload the created data dir to S3
    5003            0 :             if self.tenant_shard_id().is_shard_zero() {
    5004            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5005            0 :                     .await?;
    5006            0 :             }
    5007              :         }
    5008            2 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5009            2 : 
    5010            2 :         // Import the contents of the data directory at the initial checkpoint
    5011            2 :         // LSN, and any WAL after that.
    5012            2 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5013            2 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5014            2 :         let new_metadata = TimelineMetadata::new(
    5015            2 :             Lsn(0),
    5016            2 :             None,
    5017            2 :             None,
    5018            2 :             Lsn(0),
    5019            2 :             pgdata_lsn,
    5020            2 :             pgdata_lsn,
    5021            2 :             pg_version,
    5022            2 :         );
    5023            2 :         let raw_timeline = self
    5024            2 :             .prepare_new_timeline(
    5025            2 :                 timeline_id,
    5026            2 :                 &new_metadata,
    5027            2 :                 timeline_create_guard,
    5028            2 :                 pgdata_lsn,
    5029            2 :                 None,
    5030            2 :             )
    5031            2 :             .await?;
    5032              : 
    5033            2 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5034            2 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    5035              : 
    5036              :         // Flush the new layer files to disk, before we make the timeline as available to
    5037              :         // the outside world.
    5038              :         //
    5039              :         // Flush loop needs to be spawned in order to be able to flush.
    5040            2 :         unfinished_timeline.maybe_spawn_flush_loop();
    5041            2 : 
    5042            2 :         import_datadir::import_timeline_from_postgres_datadir(
    5043            2 :             unfinished_timeline,
    5044            2 :             &pgdata_path,
    5045            2 :             pgdata_lsn,
    5046            2 :             ctx,
    5047            2 :         )
    5048            2 :         .await
    5049            2 :         .with_context(|| {
    5050            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    5051            2 :         })?;
    5052              : 
    5053            2 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5054            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    5055            0 :                 "failpoint before-checkpoint-new-timeline"
    5056            0 :             )))
    5057            2 :         });
    5058              : 
    5059            2 :         unfinished_timeline
    5060            2 :             .freeze_and_flush()
    5061            2 :             .await
    5062            2 :             .with_context(|| {
    5063            0 :                 format!(
    5064            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    5065            0 :                 )
    5066            2 :             })?;
    5067              : 
    5068              :         // All done!
    5069            2 :         let timeline = raw_timeline.finish_creation()?;
    5070              : 
    5071              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5072              : 
    5073            2 :         Ok(CreateTimelineResult::Created(timeline))
    5074            2 :     }
    5075              : 
    5076          416 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5077          416 :         RemoteTimelineClient::new(
    5078          416 :             self.remote_storage.clone(),
    5079          416 :             self.deletion_queue_client.clone(),
    5080          416 :             self.conf,
    5081          416 :             self.tenant_shard_id,
    5082          416 :             timeline_id,
    5083          416 :             self.generation,
    5084          416 :             &self.tenant_conf.load().location,
    5085          416 :         )
    5086          416 :     }
    5087              : 
    5088              :     /// Call this before constructing a timeline, to build its required structures
    5089          416 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5090          416 :         TimelineResources {
    5091          416 :             remote_client: self.build_timeline_remote_client(timeline_id),
    5092          416 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5093          416 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5094          416 :         }
    5095          416 :     }
    5096              : 
    5097              :     /// Creates intermediate timeline structure and its files.
    5098              :     ///
    5099              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5100              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5101              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5102          416 :     async fn prepare_new_timeline<'a>(
    5103          416 :         &'a self,
    5104          416 :         new_timeline_id: TimelineId,
    5105          416 :         new_metadata: &TimelineMetadata,
    5106          416 :         create_guard: TimelineCreateGuard,
    5107          416 :         start_lsn: Lsn,
    5108          416 :         ancestor: Option<Arc<Timeline>>,
    5109          416 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5110          416 :         let tenant_shard_id = self.tenant_shard_id;
    5111          416 : 
    5112          416 :         let resources = self.build_timeline_resources(new_timeline_id);
    5113          416 :         resources
    5114          416 :             .remote_client
    5115          416 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5116              : 
    5117          416 :         let timeline_struct = self
    5118          416 :             .create_timeline_struct(
    5119          416 :                 new_timeline_id,
    5120          416 :                 new_metadata,
    5121          416 :                 ancestor,
    5122          416 :                 resources,
    5123          416 :                 CreateTimelineCause::Load,
    5124          416 :                 create_guard.idempotency.clone(),
    5125          416 :             )
    5126          416 :             .context("Failed to create timeline data structure")?;
    5127              : 
    5128          416 :         timeline_struct.init_empty_layer_map(start_lsn);
    5129              : 
    5130          416 :         if let Err(e) = self
    5131          416 :             .create_timeline_files(&create_guard.timeline_path)
    5132          416 :             .await
    5133              :         {
    5134            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5135            0 :             cleanup_timeline_directory(create_guard);
    5136            0 :             return Err(e);
    5137          416 :         }
    5138          416 : 
    5139          416 :         debug!(
    5140            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5141              :         );
    5142              : 
    5143          416 :         Ok(UninitializedTimeline::new(
    5144          416 :             self,
    5145          416 :             new_timeline_id,
    5146          416 :             Some((timeline_struct, create_guard)),
    5147          416 :         ))
    5148          416 :     }
    5149              : 
    5150          416 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5151          416 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5152              : 
    5153          416 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5154            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5155          416 :         });
    5156              : 
    5157          416 :         Ok(())
    5158          416 :     }
    5159              : 
    5160              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5161              :     /// concurrent attempts to create the same timeline.
    5162              :     ///
    5163              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5164              :     /// offloaded timelines or not.
    5165          422 :     fn create_timeline_create_guard(
    5166          422 :         self: &Arc<Self>,
    5167          422 :         timeline_id: TimelineId,
    5168          422 :         idempotency: CreateTimelineIdempotency,
    5169          422 :         allow_offloaded: bool,
    5170          422 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5171          422 :         let tenant_shard_id = self.tenant_shard_id;
    5172          422 : 
    5173          422 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5174              : 
    5175          422 :         let create_guard = TimelineCreateGuard::new(
    5176          422 :             self,
    5177          422 :             timeline_id,
    5178          422 :             timeline_path.clone(),
    5179          422 :             idempotency,
    5180          422 :             allow_offloaded,
    5181          422 :         )?;
    5182              : 
    5183              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5184              :         // for creation.
    5185              :         // A timeline directory should never exist on disk already:
    5186              :         // - a previous failed creation would have cleaned up after itself
    5187              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5188              :         //
    5189              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5190              :         // this error may indicate a bug in cleanup on failed creations.
    5191          420 :         if timeline_path.exists() {
    5192            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5193            0 :                 "Timeline directory already exists! This is a bug."
    5194            0 :             )));
    5195          420 :         }
    5196          420 : 
    5197          420 :         Ok(create_guard)
    5198          422 :     }
    5199              : 
    5200              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5201              :     ///
    5202              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5203            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5204              :     pub async fn gather_size_inputs(
    5205              :         &self,
    5206              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5207              :         // (only if it is shorter than the real cutoff).
    5208              :         max_retention_period: Option<u64>,
    5209              :         cause: LogicalSizeCalculationCause,
    5210              :         cancel: &CancellationToken,
    5211              :         ctx: &RequestContext,
    5212              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5213              :         let logical_sizes_at_once = self
    5214              :             .conf
    5215              :             .concurrent_tenant_size_logical_size_queries
    5216              :             .inner();
    5217              : 
    5218              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5219              :         //
    5220              :         // But the only case where we need to run multiple of these at once is when we
    5221              :         // request a size for a tenant manually via API, while another background calculation
    5222              :         // is in progress (which is not a common case).
    5223              :         //
    5224              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5225              :         let mut shared_cache = tokio::select! {
    5226              :             locked = self.cached_logical_sizes.lock() => locked,
    5227              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5228              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5229              :         };
    5230              : 
    5231              :         size::gather_inputs(
    5232              :             self,
    5233              :             logical_sizes_at_once,
    5234              :             max_retention_period,
    5235              :             &mut shared_cache,
    5236              :             cause,
    5237              :             cancel,
    5238              :             ctx,
    5239              :         )
    5240              :         .await
    5241              :     }
    5242              : 
    5243              :     /// Calculate synthetic tenant size and cache the result.
    5244              :     /// This is periodically called by background worker.
    5245              :     /// result is cached in tenant struct
    5246            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5247              :     pub async fn calculate_synthetic_size(
    5248              :         &self,
    5249              :         cause: LogicalSizeCalculationCause,
    5250              :         cancel: &CancellationToken,
    5251              :         ctx: &RequestContext,
    5252              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5253              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5254              : 
    5255              :         let size = inputs.calculate();
    5256              : 
    5257              :         self.set_cached_synthetic_size(size);
    5258              : 
    5259              :         Ok(size)
    5260              :     }
    5261              : 
    5262              :     /// Cache given synthetic size and update the metric value
    5263            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5264            0 :         self.cached_synthetic_tenant_size
    5265            0 :             .store(size, Ordering::Relaxed);
    5266            0 : 
    5267            0 :         // Only shard zero should be calculating synthetic sizes
    5268            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5269              : 
    5270            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5271            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5272            0 :             .unwrap()
    5273            0 :             .set(size);
    5274            0 :     }
    5275              : 
    5276            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5277            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5278            0 :     }
    5279              : 
    5280              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5281              :     ///
    5282              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5283              :     /// from an external API handler.
    5284              :     ///
    5285              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5286              :     /// still bounded by tenant/timeline shutdown.
    5287            0 :     #[tracing::instrument(skip_all)]
    5288              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5289              :         let timelines = self.timelines.lock().unwrap().clone();
    5290              : 
    5291            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5292            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5293            0 :             timeline.freeze_and_flush().await?;
    5294            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5295            0 :             timeline.remote_client.wait_completion().await?;
    5296              : 
    5297            0 :             Ok(())
    5298            0 :         }
    5299              : 
    5300              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5301              :         // aborted when this function's future is cancelled: they should stay alive
    5302              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5303              :         // before Timeline shutdown completes.
    5304              :         let mut results = FuturesUnordered::new();
    5305              : 
    5306              :         for (_timeline_id, timeline) in timelines {
    5307              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5308              :             // means that if this function's future is cancelled, the Timeline shutdown
    5309              :             // will still wait for any I/O in here to complete.
    5310              :             let Ok(gate) = timeline.gate.enter() else {
    5311              :                 continue;
    5312              :             };
    5313            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5314              :             results.push(jh);
    5315              :         }
    5316              : 
    5317              :         while let Some(r) = results.next().await {
    5318              :             if let Err(e) = r {
    5319              :                 if !e.is_cancelled() && !e.is_panic() {
    5320              :                     tracing::error!("unexpected join error: {e:?}");
    5321              :                 }
    5322              :             }
    5323              :         }
    5324              : 
    5325              :         // The flushes we did above were just writes, but the Tenant might have had
    5326              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5327              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5328              :         // because it's typically a no-op.
    5329              :         match self.deletion_queue_client.flush_execute().await {
    5330              :             Ok(_) => {}
    5331              :             Err(DeletionQueueError::ShuttingDown) => {}
    5332              :         }
    5333              : 
    5334              :         Ok(())
    5335              :     }
    5336              : 
    5337            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5338            0 :         self.tenant_conf.load().tenant_conf.clone()
    5339            0 :     }
    5340              : 
    5341              :     /// How much local storage would this tenant like to have?  It can cope with
    5342              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5343              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5344              :     /// by keeping important things on local disk.
    5345              :     ///
    5346              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5347              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5348              :     /// actually use more than they report here.
    5349            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5350            0 :         let timelines = self.timelines.lock().unwrap();
    5351            0 : 
    5352            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5353            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5354            0 :         // of them is used actively enough to occupy space on disk.
    5355            0 :         timelines
    5356            0 :             .values()
    5357            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5358            0 :             .max()
    5359            0 :             .unwrap_or(0)
    5360            0 :     }
    5361              : 
    5362              :     /// Serialize and write the latest TenantManifest to remote storage.
    5363            2 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5364              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5365              :         // must be loaded while holding this lock. This makes it safe to call this function
    5366              :         // from anywhere without worrying about colliding updates.
    5367            2 :         let mut guard = tokio::select! {
    5368            2 :             g = self.tenant_manifest_upload.lock() => {
    5369            2 :                 g
    5370              :             },
    5371            2 :             _ = self.cancel.cancelled() => {
    5372            0 :                 return Err(TenantManifestError::Cancelled);
    5373              :             }
    5374              :         };
    5375              : 
    5376            2 :         let manifest = self.build_tenant_manifest();
    5377            2 :         if Some(&manifest) == (*guard).as_ref() {
    5378              :             // Optimisation: skip uploads that don't change anything.
    5379            0 :             return Ok(());
    5380            2 :         }
    5381            2 : 
    5382            2 :         upload_tenant_manifest(
    5383            2 :             &self.remote_storage,
    5384            2 :             &self.tenant_shard_id,
    5385            2 :             self.generation,
    5386            2 :             &manifest,
    5387            2 :             &self.cancel,
    5388            2 :         )
    5389            2 :         .await
    5390            2 :         .map_err(|e| {
    5391            0 :             if self.cancel.is_cancelled() {
    5392            0 :                 TenantManifestError::Cancelled
    5393              :             } else {
    5394            0 :                 TenantManifestError::RemoteStorage(e)
    5395              :             }
    5396            2 :         })?;
    5397              : 
    5398              :         // Store the successfully uploaded manifest, so that future callers can avoid
    5399              :         // re-uploading the same thing.
    5400            2 :         *guard = Some(manifest);
    5401            2 : 
    5402            2 :         Ok(())
    5403            2 :     }
    5404              : }
    5405              : 
    5406              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5407              : /// to get bootstrap data for timeline initialization.
    5408            0 : async fn run_initdb(
    5409            0 :     conf: &'static PageServerConf,
    5410            0 :     initdb_target_dir: &Utf8Path,
    5411            0 :     pg_version: u32,
    5412            0 :     cancel: &CancellationToken,
    5413            0 : ) -> Result<(), InitdbError> {
    5414            0 :     let initdb_bin_path = conf
    5415            0 :         .pg_bin_dir(pg_version)
    5416            0 :         .map_err(InitdbError::Other)?
    5417            0 :         .join("initdb");
    5418            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5419            0 :     info!(
    5420            0 :         "running {} in {}, libdir: {}",
    5421              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5422              :     );
    5423              : 
    5424            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    5425              : 
    5426            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5427            0 :         superuser: &conf.superuser,
    5428            0 :         locale: &conf.locale,
    5429            0 :         initdb_bin: &initdb_bin_path,
    5430            0 :         pg_version,
    5431            0 :         library_search_path: &initdb_lib_dir,
    5432            0 :         pgdata: initdb_target_dir,
    5433            0 :     })
    5434            0 :     .await
    5435            0 :     .map_err(InitdbError::Inner);
    5436            0 : 
    5437            0 :     // This isn't true cancellation support, see above. Still return an error to
    5438            0 :     // excercise the cancellation code path.
    5439            0 :     if cancel.is_cancelled() {
    5440            0 :         return Err(InitdbError::Cancelled);
    5441            0 :     }
    5442            0 : 
    5443            0 :     res
    5444            0 : }
    5445              : 
    5446              : /// Dump contents of a layer file to stdout.
    5447            0 : pub async fn dump_layerfile_from_path(
    5448            0 :     path: &Utf8Path,
    5449            0 :     verbose: bool,
    5450            0 :     ctx: &RequestContext,
    5451            0 : ) -> anyhow::Result<()> {
    5452              :     use std::os::unix::fs::FileExt;
    5453              : 
    5454              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5455              :     // file.
    5456            0 :     let file = File::open(path)?;
    5457            0 :     let mut header_buf = [0u8; 2];
    5458            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5459              : 
    5460            0 :     match u16::from_be_bytes(header_buf) {
    5461              :         crate::IMAGE_FILE_MAGIC => {
    5462            0 :             ImageLayer::new_for_path(path, file)?
    5463            0 :                 .dump(verbose, ctx)
    5464            0 :                 .await?
    5465              :         }
    5466              :         crate::DELTA_FILE_MAGIC => {
    5467            0 :             DeltaLayer::new_for_path(path, file)?
    5468            0 :                 .dump(verbose, ctx)
    5469            0 :                 .await?
    5470              :         }
    5471            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5472              :     }
    5473              : 
    5474            0 :     Ok(())
    5475            0 : }
    5476              : 
    5477              : #[cfg(test)]
    5478              : pub(crate) mod harness {
    5479              :     use bytes::{Bytes, BytesMut};
    5480              :     use once_cell::sync::OnceCell;
    5481              :     use pageserver_api::models::ShardParameters;
    5482              :     use pageserver_api::shard::ShardIndex;
    5483              :     use utils::logging;
    5484              : 
    5485              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5486              :     use crate::l0_flush::L0FlushConfig;
    5487              :     use crate::walredo::apply_neon;
    5488              :     use pageserver_api::key::Key;
    5489              :     use pageserver_api::record::NeonWalRecord;
    5490              : 
    5491              :     use super::*;
    5492              :     use hex_literal::hex;
    5493              :     use utils::id::TenantId;
    5494              : 
    5495              :     pub const TIMELINE_ID: TimelineId =
    5496              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5497              :     pub const NEW_TIMELINE_ID: TimelineId =
    5498              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5499              : 
    5500              :     /// Convenience function to create a page image with given string as the only content
    5501      5028738 :     pub fn test_img(s: &str) -> Bytes {
    5502      5028738 :         let mut buf = BytesMut::new();
    5503      5028738 :         buf.extend_from_slice(s.as_bytes());
    5504      5028738 :         buf.resize(64, 0);
    5505      5028738 : 
    5506      5028738 :         buf.freeze()
    5507      5028738 :     }
    5508              : 
    5509              :     impl From<TenantConf> for TenantConfOpt {
    5510          196 :         fn from(tenant_conf: TenantConf) -> Self {
    5511          196 :             Self {
    5512          196 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5513          196 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5514          196 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5515          196 :                 compaction_period: Some(tenant_conf.compaction_period),
    5516          196 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5517          196 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5518          196 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5519          196 :                 gc_period: Some(tenant_conf.gc_period),
    5520          196 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5521          196 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5522          196 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5523          196 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5524          196 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5525          196 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5526          196 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5527          196 :                 evictions_low_residence_duration_metric_threshold: Some(
    5528          196 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5529          196 :                 ),
    5530          196 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5531          196 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5532          196 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5533          196 :                 image_layer_creation_check_threshold: Some(
    5534          196 :                     tenant_conf.image_layer_creation_check_threshold,
    5535          196 :                 ),
    5536          196 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5537          196 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5538          196 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5539          196 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5540          196 :             }
    5541          196 :         }
    5542              :     }
    5543              : 
    5544              :     pub struct TenantHarness {
    5545              :         pub conf: &'static PageServerConf,
    5546              :         pub tenant_conf: TenantConf,
    5547              :         pub tenant_shard_id: TenantShardId,
    5548              :         pub generation: Generation,
    5549              :         pub shard: ShardIndex,
    5550              :         pub remote_storage: GenericRemoteStorage,
    5551              :         pub remote_fs_dir: Utf8PathBuf,
    5552              :         pub deletion_queue: MockDeletionQueue,
    5553              :     }
    5554              : 
    5555              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5556              : 
    5557          212 :     pub(crate) fn setup_logging() {
    5558          212 :         LOG_HANDLE.get_or_init(|| {
    5559          200 :             logging::init(
    5560          200 :                 logging::LogFormat::Test,
    5561          200 :                 // enable it in case the tests exercise code paths that use
    5562          200 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5563          200 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5564          200 :                 logging::Output::Stdout,
    5565          200 :             )
    5566          200 :             .expect("Failed to init test logging")
    5567          212 :         });
    5568          212 :     }
    5569              : 
    5570              :     impl TenantHarness {
    5571          196 :         pub async fn create_custom(
    5572          196 :             test_name: &'static str,
    5573          196 :             tenant_conf: TenantConf,
    5574          196 :             tenant_id: TenantId,
    5575          196 :             shard_identity: ShardIdentity,
    5576          196 :             generation: Generation,
    5577          196 :         ) -> anyhow::Result<Self> {
    5578          196 :             setup_logging();
    5579          196 : 
    5580          196 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5581          196 :             let _ = fs::remove_dir_all(&repo_dir);
    5582          196 :             fs::create_dir_all(&repo_dir)?;
    5583              : 
    5584          196 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5585          196 :             // Make a static copy of the config. This can never be free'd, but that's
    5586          196 :             // OK in a test.
    5587          196 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5588          196 : 
    5589          196 :             let shard = shard_identity.shard_index();
    5590          196 :             let tenant_shard_id = TenantShardId {
    5591          196 :                 tenant_id,
    5592          196 :                 shard_number: shard.shard_number,
    5593          196 :                 shard_count: shard.shard_count,
    5594          196 :             };
    5595          196 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5596          196 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5597              : 
    5598              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5599          196 :             let remote_fs_dir = conf.workdir.join("localfs");
    5600          196 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5601          196 :             let config = RemoteStorageConfig {
    5602          196 :                 storage: RemoteStorageKind::LocalFs {
    5603          196 :                     local_path: remote_fs_dir.clone(),
    5604          196 :                 },
    5605          196 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5606          196 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5607          196 :             };
    5608          196 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5609          196 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5610          196 : 
    5611          196 :             Ok(Self {
    5612          196 :                 conf,
    5613          196 :                 tenant_conf,
    5614          196 :                 tenant_shard_id,
    5615          196 :                 generation,
    5616          196 :                 shard,
    5617          196 :                 remote_storage,
    5618          196 :                 remote_fs_dir,
    5619          196 :                 deletion_queue,
    5620          196 :             })
    5621          196 :         }
    5622              : 
    5623          184 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5624          184 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5625          184 :             // The tests perform them manually if needed.
    5626          184 :             let tenant_conf = TenantConf {
    5627          184 :                 gc_period: Duration::ZERO,
    5628          184 :                 compaction_period: Duration::ZERO,
    5629          184 :                 ..TenantConf::default()
    5630          184 :             };
    5631          184 :             let tenant_id = TenantId::generate();
    5632          184 :             let shard = ShardIdentity::unsharded();
    5633          184 :             Self::create_custom(
    5634          184 :                 test_name,
    5635          184 :                 tenant_conf,
    5636          184 :                 tenant_id,
    5637          184 :                 shard,
    5638          184 :                 Generation::new(0xdeadbeef),
    5639          184 :             )
    5640          184 :             .await
    5641          184 :         }
    5642              : 
    5643           20 :         pub fn span(&self) -> tracing::Span {
    5644           20 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5645           20 :         }
    5646              : 
    5647          196 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5648          196 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5649          196 :             (
    5650          196 :                 self.do_try_load(&ctx)
    5651          196 :                     .await
    5652          196 :                     .expect("failed to load test tenant"),
    5653          196 :                 ctx,
    5654          196 :             )
    5655          196 :         }
    5656              : 
    5657          196 :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5658              :         pub(crate) async fn do_try_load(
    5659              :             &self,
    5660              :             ctx: &RequestContext,
    5661              :         ) -> anyhow::Result<Arc<Tenant>> {
    5662              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5663              : 
    5664              :             let tenant = Arc::new(Tenant::new(
    5665              :                 TenantState::Attaching,
    5666              :                 self.conf,
    5667              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5668              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5669              :                     self.generation,
    5670              :                     &ShardParameters::default(),
    5671              :                 ))
    5672              :                 .unwrap(),
    5673              :                 // This is a legacy/test code path: sharding isn't supported here.
    5674              :                 ShardIdentity::unsharded(),
    5675              :                 Some(walredo_mgr),
    5676              :                 self.tenant_shard_id,
    5677              :                 self.remote_storage.clone(),
    5678              :                 self.deletion_queue.new_client(),
    5679              :                 // TODO: ideally we should run all unit tests with both configs
    5680              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5681              :             ));
    5682              : 
    5683              :             let preload = tenant
    5684              :                 .preload(&self.remote_storage, CancellationToken::new())
    5685              :                 .await?;
    5686              :             tenant.attach(Some(preload), ctx).await?;
    5687              : 
    5688              :             tenant.state.send_replace(TenantState::Active);
    5689              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5690              :                 timeline.set_state(TimelineState::Active);
    5691              :             }
    5692              :             Ok(tenant)
    5693              :         }
    5694              : 
    5695            2 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5696            2 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5697            2 :         }
    5698              :     }
    5699              : 
    5700              :     // Mock WAL redo manager that doesn't do much
    5701              :     pub(crate) struct TestRedoManager;
    5702              : 
    5703              :     impl TestRedoManager {
    5704              :         /// # Cancel-Safety
    5705              :         ///
    5706              :         /// This method is cancellation-safe.
    5707          520 :         pub async fn request_redo(
    5708          520 :             &self,
    5709          520 :             key: Key,
    5710          520 :             lsn: Lsn,
    5711          520 :             base_img: Option<(Lsn, Bytes)>,
    5712          520 :             records: Vec<(Lsn, NeonWalRecord)>,
    5713          520 :             _pg_version: u32,
    5714          520 :         ) -> Result<Bytes, walredo::Error> {
    5715          770 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5716          520 :             if records_neon {
    5717              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5718          520 :                 let mut page = match (base_img, records.first()) {
    5719          454 :                     (Some((_lsn, img)), _) => {
    5720          454 :                         let mut page = BytesMut::new();
    5721          454 :                         page.extend_from_slice(&img);
    5722          454 :                         page
    5723              :                     }
    5724           66 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5725              :                     _ => {
    5726            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5727              :                     }
    5728              :                 };
    5729              : 
    5730         1290 :                 for (record_lsn, record) in records {
    5731          770 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5732              :                 }
    5733          520 :                 Ok(page.freeze())
    5734              :             } else {
    5735              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5736            0 :                 let s = format!(
    5737            0 :                     "redo for {} to get to {}, with {} and {} records",
    5738            0 :                     key,
    5739            0 :                     lsn,
    5740            0 :                     if base_img.is_some() {
    5741            0 :                         "base image"
    5742              :                     } else {
    5743            0 :                         "no base image"
    5744              :                     },
    5745            0 :                     records.len()
    5746            0 :                 );
    5747            0 :                 println!("{s}");
    5748            0 : 
    5749            0 :                 Ok(test_img(&s))
    5750              :             }
    5751          520 :         }
    5752              :     }
    5753              : }
    5754              : 
    5755              : #[cfg(test)]
    5756              : mod tests {
    5757              :     use std::collections::{BTreeMap, BTreeSet};
    5758              : 
    5759              :     use super::*;
    5760              :     use crate::keyspace::KeySpaceAccum;
    5761              :     use crate::tenant::harness::*;
    5762              :     use crate::tenant::timeline::CompactFlags;
    5763              :     use crate::DEFAULT_PG_VERSION;
    5764              :     use bytes::{Bytes, BytesMut};
    5765              :     use hex_literal::hex;
    5766              :     use itertools::Itertools;
    5767              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
    5768              :     use pageserver_api::keyspace::KeySpace;
    5769              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5770              :     use pageserver_api::value::Value;
    5771              :     use pageserver_compaction::helpers::overlaps_with;
    5772              :     use rand::{thread_rng, Rng};
    5773              :     use storage_layer::PersistentLayerKey;
    5774              :     use tests::storage_layer::ValuesReconstructState;
    5775              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5776              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5777              :     use utils::id::TenantId;
    5778              : 
    5779              :     #[cfg(feature = "testing")]
    5780              :     use models::CompactLsnRange;
    5781              :     #[cfg(feature = "testing")]
    5782              :     use pageserver_api::record::NeonWalRecord;
    5783              :     #[cfg(feature = "testing")]
    5784              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5785              :     #[cfg(feature = "testing")]
    5786              :     use timeline::GcInfo;
    5787              : 
    5788              :     static TEST_KEY: Lazy<Key> =
    5789           18 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5790              : 
    5791              :     #[tokio::test]
    5792            2 :     async fn test_basic() -> anyhow::Result<()> {
    5793            2 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5794            2 :         let tline = tenant
    5795            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5796            2 :             .await?;
    5797            2 : 
    5798            2 :         let mut writer = tline.writer().await;
    5799            2 :         writer
    5800            2 :             .put(
    5801            2 :                 *TEST_KEY,
    5802            2 :                 Lsn(0x10),
    5803            2 :                 &Value::Image(test_img("foo at 0x10")),
    5804            2 :                 &ctx,
    5805            2 :             )
    5806            2 :             .await?;
    5807            2 :         writer.finish_write(Lsn(0x10));
    5808            2 :         drop(writer);
    5809            2 : 
    5810            2 :         let mut writer = tline.writer().await;
    5811            2 :         writer
    5812            2 :             .put(
    5813            2 :                 *TEST_KEY,
    5814            2 :                 Lsn(0x20),
    5815            2 :                 &Value::Image(test_img("foo at 0x20")),
    5816            2 :                 &ctx,
    5817            2 :             )
    5818            2 :             .await?;
    5819            2 :         writer.finish_write(Lsn(0x20));
    5820            2 :         drop(writer);
    5821            2 : 
    5822            2 :         assert_eq!(
    5823            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5824            2 :             test_img("foo at 0x10")
    5825            2 :         );
    5826            2 :         assert_eq!(
    5827            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5828            2 :             test_img("foo at 0x10")
    5829            2 :         );
    5830            2 :         assert_eq!(
    5831            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5832            2 :             test_img("foo at 0x20")
    5833            2 :         );
    5834            2 : 
    5835            2 :         Ok(())
    5836            2 :     }
    5837              : 
    5838              :     #[tokio::test]
    5839            2 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5840            2 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5841            2 :             .await?
    5842            2 :             .load()
    5843            2 :             .await;
    5844            2 :         let _ = tenant
    5845            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5846            2 :             .await?;
    5847            2 : 
    5848            2 :         match tenant
    5849            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5850            2 :             .await
    5851            2 :         {
    5852            2 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5853            2 :             Err(e) => assert_eq!(
    5854            2 :                 e.to_string(),
    5855            2 :                 "timeline already exists with different parameters".to_string()
    5856            2 :             ),
    5857            2 :         }
    5858            2 : 
    5859            2 :         Ok(())
    5860            2 :     }
    5861              : 
    5862              :     /// Convenience function to create a page image with given string as the only content
    5863           10 :     pub fn test_value(s: &str) -> Value {
    5864           10 :         let mut buf = BytesMut::new();
    5865           10 :         buf.extend_from_slice(s.as_bytes());
    5866           10 :         Value::Image(buf.freeze())
    5867           10 :     }
    5868              : 
    5869              :     ///
    5870              :     /// Test branch creation
    5871              :     ///
    5872              :     #[tokio::test]
    5873            2 :     async fn test_branch() -> anyhow::Result<()> {
    5874            2 :         use std::str::from_utf8;
    5875            2 : 
    5876            2 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5877            2 :         let tline = tenant
    5878            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5879            2 :             .await?;
    5880            2 :         let mut writer = tline.writer().await;
    5881            2 : 
    5882            2 :         #[allow(non_snake_case)]
    5883            2 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5884            2 :         #[allow(non_snake_case)]
    5885            2 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5886            2 : 
    5887            2 :         // Insert a value on the timeline
    5888            2 :         writer
    5889            2 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5890            2 :             .await?;
    5891            2 :         writer
    5892            2 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5893            2 :             .await?;
    5894            2 :         writer.finish_write(Lsn(0x20));
    5895            2 : 
    5896            2 :         writer
    5897            2 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5898            2 :             .await?;
    5899            2 :         writer.finish_write(Lsn(0x30));
    5900            2 :         writer
    5901            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5902            2 :             .await?;
    5903            2 :         writer.finish_write(Lsn(0x40));
    5904            2 : 
    5905            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5906            2 : 
    5907            2 :         // Branch the history, modify relation differently on the new timeline
    5908            2 :         tenant
    5909            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5910            2 :             .await?;
    5911            2 :         let newtline = tenant
    5912            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5913            2 :             .expect("Should have a local timeline");
    5914            2 :         let mut new_writer = newtline.writer().await;
    5915            2 :         new_writer
    5916            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5917            2 :             .await?;
    5918            2 :         new_writer.finish_write(Lsn(0x40));
    5919            2 : 
    5920            2 :         // Check page contents on both branches
    5921            2 :         assert_eq!(
    5922            2 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5923            2 :             "foo at 0x40"
    5924            2 :         );
    5925            2 :         assert_eq!(
    5926            2 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5927            2 :             "bar at 0x40"
    5928            2 :         );
    5929            2 :         assert_eq!(
    5930            2 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5931            2 :             "foobar at 0x20"
    5932            2 :         );
    5933            2 : 
    5934            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5935            2 : 
    5936            2 :         Ok(())
    5937            2 :     }
    5938              : 
    5939           20 :     async fn make_some_layers(
    5940           20 :         tline: &Timeline,
    5941           20 :         start_lsn: Lsn,
    5942           20 :         ctx: &RequestContext,
    5943           20 :     ) -> anyhow::Result<()> {
    5944           20 :         let mut lsn = start_lsn;
    5945              :         {
    5946           20 :             let mut writer = tline.writer().await;
    5947              :             // Create a relation on the timeline
    5948           20 :             writer
    5949           20 :                 .put(
    5950           20 :                     *TEST_KEY,
    5951           20 :                     lsn,
    5952           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5953           20 :                     ctx,
    5954           20 :                 )
    5955           20 :                 .await?;
    5956           20 :             writer.finish_write(lsn);
    5957           20 :             lsn += 0x10;
    5958           20 :             writer
    5959           20 :                 .put(
    5960           20 :                     *TEST_KEY,
    5961           20 :                     lsn,
    5962           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5963           20 :                     ctx,
    5964           20 :                 )
    5965           20 :                 .await?;
    5966           20 :             writer.finish_write(lsn);
    5967           20 :             lsn += 0x10;
    5968           20 :         }
    5969           20 :         tline.freeze_and_flush().await?;
    5970              :         {
    5971           20 :             let mut writer = tline.writer().await;
    5972           20 :             writer
    5973           20 :                 .put(
    5974           20 :                     *TEST_KEY,
    5975           20 :                     lsn,
    5976           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5977           20 :                     ctx,
    5978           20 :                 )
    5979           20 :                 .await?;
    5980           20 :             writer.finish_write(lsn);
    5981           20 :             lsn += 0x10;
    5982           20 :             writer
    5983           20 :                 .put(
    5984           20 :                     *TEST_KEY,
    5985           20 :                     lsn,
    5986           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5987           20 :                     ctx,
    5988           20 :                 )
    5989           20 :                 .await?;
    5990           20 :             writer.finish_write(lsn);
    5991           20 :         }
    5992           20 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5993           20 :     }
    5994              : 
    5995              :     #[tokio::test(start_paused = true)]
    5996            2 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5997            2 :         let (tenant, ctx) =
    5998            2 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5999            2 :                 .await?
    6000            2 :                 .load()
    6001            2 :                 .await;
    6002            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6003            2 :         // initial transition into AttachedSingle.
    6004            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6005            2 :         tokio::time::resume();
    6006            2 :         let tline = tenant
    6007            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6008            2 :             .await?;
    6009            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6010            2 : 
    6011            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6012            2 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6013            2 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6014            2 :         // below should fail.
    6015            2 :         tenant
    6016            2 :             .gc_iteration(
    6017            2 :                 Some(TIMELINE_ID),
    6018            2 :                 0x10,
    6019            2 :                 Duration::ZERO,
    6020            2 :                 &CancellationToken::new(),
    6021            2 :                 &ctx,
    6022            2 :             )
    6023            2 :             .await?;
    6024            2 : 
    6025            2 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6026            2 :         match tenant
    6027            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6028            2 :             .await
    6029            2 :         {
    6030            2 :             Ok(_) => panic!("branching should have failed"),
    6031            2 :             Err(err) => {
    6032            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6033            2 :                     panic!("wrong error type")
    6034            2 :                 };
    6035            2 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6036            2 :                 assert!(err
    6037            2 :                     .source()
    6038            2 :                     .unwrap()
    6039            2 :                     .to_string()
    6040            2 :                     .contains("we might've already garbage collected needed data"))
    6041            2 :             }
    6042            2 :         }
    6043            2 : 
    6044            2 :         Ok(())
    6045            2 :     }
    6046              : 
    6047              :     #[tokio::test]
    6048            2 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6049            2 :         let (tenant, ctx) =
    6050            2 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6051            2 :                 .await?
    6052            2 :                 .load()
    6053            2 :                 .await;
    6054            2 : 
    6055            2 :         let tline = tenant
    6056            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6057            2 :             .await?;
    6058            2 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6059            2 :         match tenant
    6060            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6061            2 :             .await
    6062            2 :         {
    6063            2 :             Ok(_) => panic!("branching should have failed"),
    6064            2 :             Err(err) => {
    6065            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6066            2 :                     panic!("wrong error type");
    6067            2 :                 };
    6068            2 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6069            2 :                 assert!(&err
    6070            2 :                     .source()
    6071            2 :                     .unwrap()
    6072            2 :                     .to_string()
    6073            2 :                     .contains("is earlier than latest GC cutoff"));
    6074            2 :             }
    6075            2 :         }
    6076            2 : 
    6077            2 :         Ok(())
    6078            2 :     }
    6079              : 
    6080              :     /*
    6081              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6082              :     // remove the old value, we'd need to work a little harder
    6083              :     #[tokio::test]
    6084              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6085              :         let repo =
    6086              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6087              :             .load();
    6088              : 
    6089              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6090              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6091              : 
    6092              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6093              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    6094              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    6095              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6096              :             Ok(_) => panic!("request for page should have failed"),
    6097              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6098              :         }
    6099              :         Ok(())
    6100              :     }
    6101              :      */
    6102              : 
    6103              :     #[tokio::test]
    6104            2 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6105            2 :         let (tenant, ctx) =
    6106            2 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6107            2 :                 .await?
    6108            2 :                 .load()
    6109            2 :                 .await;
    6110            2 :         let tline = tenant
    6111            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6112            2 :             .await?;
    6113            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6114            2 : 
    6115            2 :         tenant
    6116            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6117            2 :             .await?;
    6118            2 :         let newtline = tenant
    6119            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6120            2 :             .expect("Should have a local timeline");
    6121            2 : 
    6122            2 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6123            2 : 
    6124            2 :         tline.set_broken("test".to_owned());
    6125            2 : 
    6126            2 :         tenant
    6127            2 :             .gc_iteration(
    6128            2 :                 Some(TIMELINE_ID),
    6129            2 :                 0x10,
    6130            2 :                 Duration::ZERO,
    6131            2 :                 &CancellationToken::new(),
    6132            2 :                 &ctx,
    6133            2 :             )
    6134            2 :             .await?;
    6135            2 : 
    6136            2 :         // The branchpoints should contain all timelines, even ones marked
    6137            2 :         // as Broken.
    6138            2 :         {
    6139            2 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6140            2 :             assert_eq!(branchpoints.len(), 1);
    6141            2 :             assert_eq!(
    6142            2 :                 branchpoints[0],
    6143            2 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6144            2 :             );
    6145            2 :         }
    6146            2 : 
    6147            2 :         // You can read the key from the child branch even though the parent is
    6148            2 :         // Broken, as long as you don't need to access data from the parent.
    6149            2 :         assert_eq!(
    6150            2 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6151            2 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6152            2 :         );
    6153            2 : 
    6154            2 :         // This needs to traverse to the parent, and fails.
    6155            2 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6156            2 :         assert!(
    6157            2 :             err.to_string().starts_with(&format!(
    6158            2 :                 "bad state on timeline {}: Broken",
    6159            2 :                 tline.timeline_id
    6160            2 :             )),
    6161            2 :             "{err}"
    6162            2 :         );
    6163            2 : 
    6164            2 :         Ok(())
    6165            2 :     }
    6166              : 
    6167              :     #[tokio::test]
    6168            2 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6169            2 :         let (tenant, ctx) =
    6170            2 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6171            2 :                 .await?
    6172            2 :                 .load()
    6173            2 :                 .await;
    6174            2 :         let tline = tenant
    6175            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6176            2 :             .await?;
    6177            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6178            2 : 
    6179            2 :         tenant
    6180            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6181            2 :             .await?;
    6182            2 :         let newtline = tenant
    6183            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6184            2 :             .expect("Should have a local timeline");
    6185            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6186            2 :         tenant
    6187            2 :             .gc_iteration(
    6188            2 :                 Some(TIMELINE_ID),
    6189            2 :                 0x10,
    6190            2 :                 Duration::ZERO,
    6191            2 :                 &CancellationToken::new(),
    6192            2 :                 &ctx,
    6193            2 :             )
    6194            2 :             .await?;
    6195            2 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6196            2 : 
    6197            2 :         Ok(())
    6198            2 :     }
    6199              :     #[tokio::test]
    6200            2 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6201            2 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6202            2 :             .await?
    6203            2 :             .load()
    6204            2 :             .await;
    6205            2 :         let tline = tenant
    6206            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6207            2 :             .await?;
    6208            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6209            2 : 
    6210            2 :         tenant
    6211            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6212            2 :             .await?;
    6213            2 :         let newtline = tenant
    6214            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6215            2 :             .expect("Should have a local timeline");
    6216            2 : 
    6217            2 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6218            2 : 
    6219            2 :         // run gc on parent
    6220            2 :         tenant
    6221            2 :             .gc_iteration(
    6222            2 :                 Some(TIMELINE_ID),
    6223            2 :                 0x10,
    6224            2 :                 Duration::ZERO,
    6225            2 :                 &CancellationToken::new(),
    6226            2 :                 &ctx,
    6227            2 :             )
    6228            2 :             .await?;
    6229            2 : 
    6230            2 :         // Check that the data is still accessible on the branch.
    6231            2 :         assert_eq!(
    6232            2 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6233            2 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6234            2 :         );
    6235            2 : 
    6236            2 :         Ok(())
    6237            2 :     }
    6238              : 
    6239              :     #[tokio::test]
    6240            2 :     async fn timeline_load() -> anyhow::Result<()> {
    6241            2 :         const TEST_NAME: &str = "timeline_load";
    6242            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6243            2 :         {
    6244            2 :             let (tenant, ctx) = harness.load().await;
    6245            2 :             let tline = tenant
    6246            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6247            2 :                 .await?;
    6248            2 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6249            2 :             // so that all uploads finish & we can call harness.load() below again
    6250            2 :             tenant
    6251            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6252            2 :                 .instrument(harness.span())
    6253            2 :                 .await
    6254            2 :                 .ok()
    6255            2 :                 .unwrap();
    6256            2 :         }
    6257            2 : 
    6258            2 :         let (tenant, _ctx) = harness.load().await;
    6259            2 :         tenant
    6260            2 :             .get_timeline(TIMELINE_ID, true)
    6261            2 :             .expect("cannot load timeline");
    6262            2 : 
    6263            2 :         Ok(())
    6264            2 :     }
    6265              : 
    6266              :     #[tokio::test]
    6267            2 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6268            2 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6269            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6270            2 :         // create two timelines
    6271            2 :         {
    6272            2 :             let (tenant, ctx) = harness.load().await;
    6273            2 :             let tline = tenant
    6274            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6275            2 :                 .await?;
    6276            2 : 
    6277            2 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6278            2 : 
    6279            2 :             let child_tline = tenant
    6280            2 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6281            2 :                 .await?;
    6282            2 :             child_tline.set_state(TimelineState::Active);
    6283            2 : 
    6284            2 :             let newtline = tenant
    6285            2 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6286            2 :                 .expect("Should have a local timeline");
    6287            2 : 
    6288            2 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6289            2 : 
    6290            2 :             // so that all uploads finish & we can call harness.load() below again
    6291            2 :             tenant
    6292            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6293            2 :                 .instrument(harness.span())
    6294            2 :                 .await
    6295            2 :                 .ok()
    6296            2 :                 .unwrap();
    6297            2 :         }
    6298            2 : 
    6299            2 :         // check that both of them are initially unloaded
    6300            2 :         let (tenant, _ctx) = harness.load().await;
    6301            2 : 
    6302            2 :         // check that both, child and ancestor are loaded
    6303            2 :         let _child_tline = tenant
    6304            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6305            2 :             .expect("cannot get child timeline loaded");
    6306            2 : 
    6307            2 :         let _ancestor_tline = tenant
    6308            2 :             .get_timeline(TIMELINE_ID, true)
    6309            2 :             .expect("cannot get ancestor timeline loaded");
    6310            2 : 
    6311            2 :         Ok(())
    6312            2 :     }
    6313              : 
    6314              :     #[tokio::test]
    6315            2 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6316            2 :         use storage_layer::AsLayerDesc;
    6317            2 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6318            2 :             .await?
    6319            2 :             .load()
    6320            2 :             .await;
    6321            2 :         let tline = tenant
    6322            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6323            2 :             .await?;
    6324            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6325            2 : 
    6326            2 :         let layer_map = tline.layers.read().await;
    6327            2 :         let level0_deltas = layer_map
    6328            2 :             .layer_map()?
    6329            2 :             .level0_deltas()
    6330            2 :             .iter()
    6331            4 :             .map(|desc| layer_map.get_from_desc(desc))
    6332            2 :             .collect::<Vec<_>>();
    6333            2 : 
    6334            2 :         assert!(!level0_deltas.is_empty());
    6335            2 : 
    6336            6 :         for delta in level0_deltas {
    6337            2 :             // Ensure we are dumping a delta layer here
    6338            4 :             assert!(delta.layer_desc().is_delta);
    6339            4 :             delta.dump(true, &ctx).await.unwrap();
    6340            2 :         }
    6341            2 : 
    6342            2 :         Ok(())
    6343            2 :     }
    6344              : 
    6345              :     #[tokio::test]
    6346            2 :     async fn test_images() -> anyhow::Result<()> {
    6347            2 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6348            2 :         let tline = tenant
    6349            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6350            2 :             .await?;
    6351            2 : 
    6352            2 :         let mut writer = tline.writer().await;
    6353            2 :         writer
    6354            2 :             .put(
    6355            2 :                 *TEST_KEY,
    6356            2 :                 Lsn(0x10),
    6357            2 :                 &Value::Image(test_img("foo at 0x10")),
    6358            2 :                 &ctx,
    6359            2 :             )
    6360            2 :             .await?;
    6361            2 :         writer.finish_write(Lsn(0x10));
    6362            2 :         drop(writer);
    6363            2 : 
    6364            2 :         tline.freeze_and_flush().await?;
    6365            2 :         tline
    6366            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6367            2 :             .await?;
    6368            2 : 
    6369            2 :         let mut writer = tline.writer().await;
    6370            2 :         writer
    6371            2 :             .put(
    6372            2 :                 *TEST_KEY,
    6373            2 :                 Lsn(0x20),
    6374            2 :                 &Value::Image(test_img("foo at 0x20")),
    6375            2 :                 &ctx,
    6376            2 :             )
    6377            2 :             .await?;
    6378            2 :         writer.finish_write(Lsn(0x20));
    6379            2 :         drop(writer);
    6380            2 : 
    6381            2 :         tline.freeze_and_flush().await?;
    6382            2 :         tline
    6383            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6384            2 :             .await?;
    6385            2 : 
    6386            2 :         let mut writer = tline.writer().await;
    6387            2 :         writer
    6388            2 :             .put(
    6389            2 :                 *TEST_KEY,
    6390            2 :                 Lsn(0x30),
    6391            2 :                 &Value::Image(test_img("foo at 0x30")),
    6392            2 :                 &ctx,
    6393            2 :             )
    6394            2 :             .await?;
    6395            2 :         writer.finish_write(Lsn(0x30));
    6396            2 :         drop(writer);
    6397            2 : 
    6398            2 :         tline.freeze_and_flush().await?;
    6399            2 :         tline
    6400            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6401            2 :             .await?;
    6402            2 : 
    6403            2 :         let mut writer = tline.writer().await;
    6404            2 :         writer
    6405            2 :             .put(
    6406            2 :                 *TEST_KEY,
    6407            2 :                 Lsn(0x40),
    6408            2 :                 &Value::Image(test_img("foo at 0x40")),
    6409            2 :                 &ctx,
    6410            2 :             )
    6411            2 :             .await?;
    6412            2 :         writer.finish_write(Lsn(0x40));
    6413            2 :         drop(writer);
    6414            2 : 
    6415            2 :         tline.freeze_and_flush().await?;
    6416            2 :         tline
    6417            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6418            2 :             .await?;
    6419            2 : 
    6420            2 :         assert_eq!(
    6421            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6422            2 :             test_img("foo at 0x10")
    6423            2 :         );
    6424            2 :         assert_eq!(
    6425            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6426            2 :             test_img("foo at 0x10")
    6427            2 :         );
    6428            2 :         assert_eq!(
    6429            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6430            2 :             test_img("foo at 0x20")
    6431            2 :         );
    6432            2 :         assert_eq!(
    6433            2 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6434            2 :             test_img("foo at 0x30")
    6435            2 :         );
    6436            2 :         assert_eq!(
    6437            2 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6438            2 :             test_img("foo at 0x40")
    6439            2 :         );
    6440            2 : 
    6441            2 :         Ok(())
    6442            2 :     }
    6443              : 
    6444            4 :     async fn bulk_insert_compact_gc(
    6445            4 :         tenant: &Tenant,
    6446            4 :         timeline: &Arc<Timeline>,
    6447            4 :         ctx: &RequestContext,
    6448            4 :         lsn: Lsn,
    6449            4 :         repeat: usize,
    6450            4 :         key_count: usize,
    6451            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6452            4 :         let compact = true;
    6453            4 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6454            4 :     }
    6455              : 
    6456            8 :     async fn bulk_insert_maybe_compact_gc(
    6457            8 :         tenant: &Tenant,
    6458            8 :         timeline: &Arc<Timeline>,
    6459            8 :         ctx: &RequestContext,
    6460            8 :         mut lsn: Lsn,
    6461            8 :         repeat: usize,
    6462            8 :         key_count: usize,
    6463            8 :         compact: bool,
    6464            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6465            8 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6466            8 : 
    6467            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6468            8 :         let mut blknum = 0;
    6469            8 : 
    6470            8 :         // Enforce that key range is monotonously increasing
    6471            8 :         let mut keyspace = KeySpaceAccum::new();
    6472            8 : 
    6473            8 :         let cancel = CancellationToken::new();
    6474            8 : 
    6475            8 :         for _ in 0..repeat {
    6476          400 :             for _ in 0..key_count {
    6477      4000000 :                 test_key.field6 = blknum;
    6478      4000000 :                 let mut writer = timeline.writer().await;
    6479      4000000 :                 writer
    6480      4000000 :                     .put(
    6481      4000000 :                         test_key,
    6482      4000000 :                         lsn,
    6483      4000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6484      4000000 :                         ctx,
    6485      4000000 :                     )
    6486      4000000 :                     .await?;
    6487      4000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6488      4000000 :                 writer.finish_write(lsn);
    6489      4000000 :                 drop(writer);
    6490      4000000 : 
    6491      4000000 :                 keyspace.add_key(test_key);
    6492      4000000 : 
    6493      4000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6494      4000000 :                 blknum += 1;
    6495              :             }
    6496              : 
    6497          400 :             timeline.freeze_and_flush().await?;
    6498          400 :             if compact {
    6499              :                 // this requires timeline to be &Arc<Timeline>
    6500          200 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6501          200 :             }
    6502              : 
    6503              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6504              :             // originally was.
    6505          400 :             let res = tenant
    6506          400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6507          400 :                 .await?;
    6508              : 
    6509          400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6510              :         }
    6511              : 
    6512            8 :         Ok(inserted)
    6513            8 :     }
    6514              : 
    6515              :     //
    6516              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6517              :     // Repeat 50 times.
    6518              :     //
    6519              :     #[tokio::test]
    6520            2 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6521            2 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6522            2 :         let (tenant, ctx) = harness.load().await;
    6523            2 :         let tline = tenant
    6524            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6525            2 :             .await?;
    6526            2 : 
    6527            2 :         let lsn = Lsn(0x10);
    6528            2 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6529            2 : 
    6530            2 :         Ok(())
    6531            2 :     }
    6532              : 
    6533              :     // Test the vectored get real implementation against a simple sequential implementation.
    6534              :     //
    6535              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6536              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6537              :     // grow to the right on the X axis.
    6538              :     //                       [Delta]
    6539              :     //                 [Delta]
    6540              :     //           [Delta]
    6541              :     //    [Delta]
    6542              :     // ------------ Image ---------------
    6543              :     //
    6544              :     // After layer generation we pick the ranges to query as follows:
    6545              :     // 1. The beginning of each delta layer
    6546              :     // 2. At the seam between two adjacent delta layers
    6547              :     //
    6548              :     // There's one major downside to this test: delta layers only contains images,
    6549              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6550              :     #[tokio::test]
    6551            2 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6552            2 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6553            2 :         let (tenant, ctx) = harness.load().await;
    6554            2 :         let tline = tenant
    6555            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6556            2 :             .await?;
    6557            2 : 
    6558            2 :         let lsn = Lsn(0x10);
    6559            2 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6560            2 : 
    6561            2 :         let guard = tline.layers.read().await;
    6562            2 :         let lm = guard.layer_map()?;
    6563            2 : 
    6564            2 :         lm.dump(true, &ctx).await?;
    6565            2 : 
    6566            2 :         let mut reads = Vec::new();
    6567            2 :         let mut prev = None;
    6568           12 :         lm.iter_historic_layers().for_each(|desc| {
    6569           12 :             if !desc.is_delta() {
    6570            2 :                 prev = Some(desc.clone());
    6571            2 :                 return;
    6572           10 :             }
    6573           10 : 
    6574           10 :             let start = desc.key_range.start;
    6575           10 :             let end = desc
    6576           10 :                 .key_range
    6577           10 :                 .start
    6578           10 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6579           10 :             reads.push(KeySpace {
    6580           10 :                 ranges: vec![start..end],
    6581           10 :             });
    6582            2 : 
    6583           10 :             if let Some(prev) = &prev {
    6584           10 :                 if !prev.is_delta() {
    6585           10 :                     return;
    6586            2 :                 }
    6587            0 : 
    6588            0 :                 let first_range = Key {
    6589            0 :                     field6: prev.key_range.end.field6 - 4,
    6590            0 :                     ..prev.key_range.end
    6591            0 :                 }..prev.key_range.end;
    6592            0 : 
    6593            0 :                 let second_range = desc.key_range.start..Key {
    6594            0 :                     field6: desc.key_range.start.field6 + 4,
    6595            0 :                     ..desc.key_range.start
    6596            0 :                 };
    6597            0 : 
    6598            0 :                 reads.push(KeySpace {
    6599            0 :                     ranges: vec![first_range, second_range],
    6600            0 :                 });
    6601            2 :             };
    6602            2 : 
    6603            2 :             prev = Some(desc.clone());
    6604           12 :         });
    6605            2 : 
    6606            2 :         drop(guard);
    6607            2 : 
    6608            2 :         // Pick a big LSN such that we query over all the changes.
    6609            2 :         let reads_lsn = Lsn(u64::MAX - 1);
    6610            2 : 
    6611           12 :         for read in reads {
    6612           10 :             info!("Doing vectored read on {:?}", read);
    6613            2 : 
    6614           10 :             let vectored_res = tline
    6615           10 :                 .get_vectored_impl(
    6616           10 :                     read.clone(),
    6617           10 :                     reads_lsn,
    6618           10 :                     &mut ValuesReconstructState::new(),
    6619           10 :                     &ctx,
    6620           10 :                 )
    6621           10 :                 .await;
    6622            2 : 
    6623           10 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6624           10 :             let mut expect_missing = false;
    6625           10 :             let mut key = read.start().unwrap();
    6626          330 :             while key != read.end().unwrap() {
    6627          320 :                 if let Some(lsns) = inserted.get(&key) {
    6628          320 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6629          320 :                     match expected_lsn {
    6630          320 :                         Some(lsn) => {
    6631          320 :                             expected_lsns.insert(key, *lsn);
    6632          320 :                         }
    6633            2 :                         None => {
    6634            2 :                             expect_missing = true;
    6635            0 :                             break;
    6636            2 :                         }
    6637            2 :                     }
    6638            2 :                 } else {
    6639            2 :                     expect_missing = true;
    6640            0 :                     break;
    6641            2 :                 }
    6642            2 : 
    6643          320 :                 key = key.next();
    6644            2 :             }
    6645            2 : 
    6646           10 :             if expect_missing {
    6647            2 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6648            2 :             } else {
    6649          320 :                 for (key, image) in vectored_res? {
    6650          320 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6651          320 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6652          320 :                     assert_eq!(image?, expected_image);
    6653            2 :                 }
    6654            2 :             }
    6655            2 :         }
    6656            2 : 
    6657            2 :         Ok(())
    6658            2 :     }
    6659              : 
    6660              :     #[tokio::test]
    6661            2 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6662            2 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6663            2 : 
    6664            2 :         let (tenant, ctx) = harness.load().await;
    6665            2 :         let tline = tenant
    6666            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6667            2 :             .await?;
    6668            2 :         let tline = tline.raw_timeline().unwrap();
    6669            2 : 
    6670            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6671            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6672            2 :         modification.set_lsn(Lsn(0x1008))?;
    6673            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6674            2 :         modification.commit(&ctx).await?;
    6675            2 : 
    6676            2 :         let child_timeline_id = TimelineId::generate();
    6677            2 :         tenant
    6678            2 :             .branch_timeline_test(
    6679            2 :                 tline,
    6680            2 :                 child_timeline_id,
    6681            2 :                 Some(tline.get_last_record_lsn()),
    6682            2 :                 &ctx,
    6683            2 :             )
    6684            2 :             .await?;
    6685            2 : 
    6686            2 :         let child_timeline = tenant
    6687            2 :             .get_timeline(child_timeline_id, true)
    6688            2 :             .expect("Should have the branched timeline");
    6689            2 : 
    6690            2 :         let aux_keyspace = KeySpace {
    6691            2 :             ranges: vec![NON_INHERITED_RANGE],
    6692            2 :         };
    6693            2 :         let read_lsn = child_timeline.get_last_record_lsn();
    6694            2 : 
    6695            2 :         let vectored_res = child_timeline
    6696            2 :             .get_vectored_impl(
    6697            2 :                 aux_keyspace.clone(),
    6698            2 :                 read_lsn,
    6699            2 :                 &mut ValuesReconstructState::new(),
    6700            2 :                 &ctx,
    6701            2 :             )
    6702            2 :             .await;
    6703            2 : 
    6704            2 :         let images = vectored_res?;
    6705            2 :         assert!(images.is_empty());
    6706            2 :         Ok(())
    6707            2 :     }
    6708              : 
    6709              :     // Test that vectored get handles layer gaps correctly
    6710              :     // by advancing into the next ancestor timeline if required.
    6711              :     //
    6712              :     // The test generates timelines that look like the diagram below.
    6713              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6714              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6715              :     //
    6716              :     // ```
    6717              :     //-------------------------------+
    6718              :     //                          ...  |
    6719              :     //               [   L1   ]      |
    6720              :     //     [ / L1   ]                | Child Timeline
    6721              :     // ...                           |
    6722              :     // ------------------------------+
    6723              :     //     [ X L1   ]                | Parent Timeline
    6724              :     // ------------------------------+
    6725              :     // ```
    6726              :     #[tokio::test]
    6727            2 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6728            2 :         let tenant_conf = TenantConf {
    6729            2 :             // Make compaction deterministic
    6730            2 :             gc_period: Duration::ZERO,
    6731            2 :             compaction_period: Duration::ZERO,
    6732            2 :             // Encourage creation of L1 layers
    6733            2 :             checkpoint_distance: 16 * 1024,
    6734            2 :             compaction_target_size: 8 * 1024,
    6735            2 :             ..TenantConf::default()
    6736            2 :         };
    6737            2 : 
    6738            2 :         let harness = TenantHarness::create_custom(
    6739            2 :             "test_get_vectored_key_gap",
    6740            2 :             tenant_conf,
    6741            2 :             TenantId::generate(),
    6742            2 :             ShardIdentity::unsharded(),
    6743            2 :             Generation::new(0xdeadbeef),
    6744            2 :         )
    6745            2 :         .await?;
    6746            2 :         let (tenant, ctx) = harness.load().await;
    6747            2 : 
    6748            2 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6749            2 :         let gap_at_key = current_key.add(100);
    6750            2 :         let mut current_lsn = Lsn(0x10);
    6751            2 : 
    6752            2 :         const KEY_COUNT: usize = 10_000;
    6753            2 : 
    6754            2 :         let timeline_id = TimelineId::generate();
    6755            2 :         let current_timeline = tenant
    6756            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6757            2 :             .await?;
    6758            2 : 
    6759            2 :         current_lsn += 0x100;
    6760            2 : 
    6761            2 :         let mut writer = current_timeline.writer().await;
    6762            2 :         writer
    6763            2 :             .put(
    6764            2 :                 gap_at_key,
    6765            2 :                 current_lsn,
    6766            2 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6767            2 :                 &ctx,
    6768            2 :             )
    6769            2 :             .await?;
    6770            2 :         writer.finish_write(current_lsn);
    6771            2 :         drop(writer);
    6772            2 : 
    6773            2 :         let mut latest_lsns = HashMap::new();
    6774            2 :         latest_lsns.insert(gap_at_key, current_lsn);
    6775            2 : 
    6776            2 :         current_timeline.freeze_and_flush().await?;
    6777            2 : 
    6778            2 :         let child_timeline_id = TimelineId::generate();
    6779            2 : 
    6780            2 :         tenant
    6781            2 :             .branch_timeline_test(
    6782            2 :                 &current_timeline,
    6783            2 :                 child_timeline_id,
    6784            2 :                 Some(current_lsn),
    6785            2 :                 &ctx,
    6786            2 :             )
    6787            2 :             .await?;
    6788            2 :         let child_timeline = tenant
    6789            2 :             .get_timeline(child_timeline_id, true)
    6790            2 :             .expect("Should have the branched timeline");
    6791            2 : 
    6792        20002 :         for i in 0..KEY_COUNT {
    6793        20000 :             if current_key == gap_at_key {
    6794            2 :                 current_key = current_key.next();
    6795            2 :                 continue;
    6796        19998 :             }
    6797        19998 : 
    6798        19998 :             current_lsn += 0x10;
    6799            2 : 
    6800        19998 :             let mut writer = child_timeline.writer().await;
    6801        19998 :             writer
    6802        19998 :                 .put(
    6803        19998 :                     current_key,
    6804        19998 :                     current_lsn,
    6805        19998 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6806        19998 :                     &ctx,
    6807        19998 :                 )
    6808        19998 :                 .await?;
    6809        19998 :             writer.finish_write(current_lsn);
    6810        19998 :             drop(writer);
    6811        19998 : 
    6812        19998 :             latest_lsns.insert(current_key, current_lsn);
    6813        19998 :             current_key = current_key.next();
    6814        19998 : 
    6815        19998 :             // Flush every now and then to encourage layer file creation.
    6816        19998 :             if i % 500 == 0 {
    6817           40 :                 child_timeline.freeze_and_flush().await?;
    6818        19958 :             }
    6819            2 :         }
    6820            2 : 
    6821            2 :         child_timeline.freeze_and_flush().await?;
    6822            2 :         let mut flags = EnumSet::new();
    6823            2 :         flags.insert(CompactFlags::ForceRepartition);
    6824            2 :         child_timeline
    6825            2 :             .compact(&CancellationToken::new(), flags, &ctx)
    6826            2 :             .await?;
    6827            2 : 
    6828            2 :         let key_near_end = {
    6829            2 :             let mut tmp = current_key;
    6830            2 :             tmp.field6 -= 10;
    6831            2 :             tmp
    6832            2 :         };
    6833            2 : 
    6834            2 :         let key_near_gap = {
    6835            2 :             let mut tmp = gap_at_key;
    6836            2 :             tmp.field6 -= 10;
    6837            2 :             tmp
    6838            2 :         };
    6839            2 : 
    6840            2 :         let read = KeySpace {
    6841            2 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6842            2 :         };
    6843            2 :         let results = child_timeline
    6844            2 :             .get_vectored_impl(
    6845            2 :                 read.clone(),
    6846            2 :                 current_lsn,
    6847            2 :                 &mut ValuesReconstructState::new(),
    6848            2 :                 &ctx,
    6849            2 :             )
    6850            2 :             .await?;
    6851            2 : 
    6852           44 :         for (key, img_res) in results {
    6853           42 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6854           42 :             assert_eq!(img_res?, expected);
    6855            2 :         }
    6856            2 : 
    6857            2 :         Ok(())
    6858            2 :     }
    6859              : 
    6860              :     // Test that vectored get descends into ancestor timelines correctly and
    6861              :     // does not return an image that's newer than requested.
    6862              :     //
    6863              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6864              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6865              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6866              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6867              :     // order to avoid returning an image that's too new. The test below constructs such
    6868              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6869              :     // ```
    6870              :     //    LSN
    6871              :     //     ^
    6872              :     //     |
    6873              :     //     |
    6874              :     // 500 | --------------------------------------> branch point
    6875              :     // 400 |        X
    6876              :     // 300 |        X
    6877              :     // 200 | --------------------------------------> requested lsn
    6878              :     // 100 |        X
    6879              :     //     |---------------------------------------> Key
    6880              :     //              |
    6881              :     //              ------> requested key
    6882              :     //
    6883              :     // Legend:
    6884              :     // * X - page images
    6885              :     // ```
    6886              :     #[tokio::test]
    6887            2 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6888            2 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6889            2 :         let (tenant, ctx) = harness.load().await;
    6890            2 : 
    6891            2 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6892            2 :         let end_key = start_key.add(1000);
    6893            2 :         let child_gap_at_key = start_key.add(500);
    6894            2 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6895            2 : 
    6896            2 :         let mut current_lsn = Lsn(0x10);
    6897            2 : 
    6898            2 :         let timeline_id = TimelineId::generate();
    6899            2 :         let parent_timeline = tenant
    6900            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6901            2 :             .await?;
    6902            2 : 
    6903            2 :         current_lsn += 0x100;
    6904            2 : 
    6905            8 :         for _ in 0..3 {
    6906            6 :             let mut key = start_key;
    6907         6006 :             while key < end_key {
    6908         6000 :                 current_lsn += 0x10;
    6909         6000 : 
    6910         6000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6911            2 : 
    6912         6000 :                 let mut writer = parent_timeline.writer().await;
    6913         6000 :                 writer
    6914         6000 :                     .put(
    6915         6000 :                         key,
    6916         6000 :                         current_lsn,
    6917         6000 :                         &Value::Image(test_img(&image_value)),
    6918         6000 :                         &ctx,
    6919         6000 :                     )
    6920         6000 :                     .await?;
    6921         6000 :                 writer.finish_write(current_lsn);
    6922         6000 : 
    6923         6000 :                 if key == child_gap_at_key {
    6924            6 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6925         5994 :                 }
    6926            2 : 
    6927         6000 :                 key = key.next();
    6928            2 :             }
    6929            2 : 
    6930            6 :             parent_timeline.freeze_and_flush().await?;
    6931            2 :         }
    6932            2 : 
    6933            2 :         let child_timeline_id = TimelineId::generate();
    6934            2 : 
    6935            2 :         let child_timeline = tenant
    6936            2 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6937            2 :             .await?;
    6938            2 : 
    6939            2 :         let mut key = start_key;
    6940         2002 :         while key < end_key {
    6941         2000 :             if key == child_gap_at_key {
    6942            2 :                 key = key.next();
    6943            2 :                 continue;
    6944         1998 :             }
    6945         1998 : 
    6946         1998 :             current_lsn += 0x10;
    6947            2 : 
    6948         1998 :             let mut writer = child_timeline.writer().await;
    6949         1998 :             writer
    6950         1998 :                 .put(
    6951         1998 :                     key,
    6952         1998 :                     current_lsn,
    6953         1998 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6954         1998 :                     &ctx,
    6955         1998 :                 )
    6956         1998 :                 .await?;
    6957         1998 :             writer.finish_write(current_lsn);
    6958         1998 : 
    6959         1998 :             key = key.next();
    6960            2 :         }
    6961            2 : 
    6962            2 :         child_timeline.freeze_and_flush().await?;
    6963            2 : 
    6964            2 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6965            2 :         let mut query_lsns = Vec::new();
    6966            6 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6967           36 :             for offset in lsn_offsets {
    6968           30 :                 query_lsns.push(Lsn(image_lsn
    6969           30 :                     .0
    6970           30 :                     .checked_add_signed(offset)
    6971           30 :                     .expect("Shouldn't overflow")));
    6972           30 :             }
    6973            2 :         }
    6974            2 : 
    6975           32 :         for query_lsn in query_lsns {
    6976           30 :             let results = child_timeline
    6977           30 :                 .get_vectored_impl(
    6978           30 :                     KeySpace {
    6979           30 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6980           30 :                     },
    6981           30 :                     query_lsn,
    6982           30 :                     &mut ValuesReconstructState::new(),
    6983           30 :                     &ctx,
    6984           30 :                 )
    6985           30 :                 .await;
    6986            2 : 
    6987           30 :             let expected_item = parent_gap_lsns
    6988           30 :                 .iter()
    6989           30 :                 .rev()
    6990           68 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6991           30 : 
    6992           30 :             info!(
    6993            2 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6994            2 :                 query_lsn, expected_item
    6995            2 :             );
    6996            2 : 
    6997           30 :             match expected_item {
    6998           26 :                 Some((_, img_value)) => {
    6999           26 :                     let key_results = results.expect("No vectored get error expected");
    7000           26 :                     let key_result = &key_results[&child_gap_at_key];
    7001           26 :                     let returned_img = key_result
    7002           26 :                         .as_ref()
    7003           26 :                         .expect("No page reconstruct error expected");
    7004           26 : 
    7005           26 :                     info!(
    7006            2 :                         "Vectored read at LSN {} returned image {}",
    7007            0 :                         query_lsn,
    7008            0 :                         std::str::from_utf8(returned_img)?
    7009            2 :                     );
    7010           26 :                     assert_eq!(*returned_img, test_img(img_value));
    7011            2 :                 }
    7012            2 :                 None => {
    7013            4 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7014            2 :                 }
    7015            2 :             }
    7016            2 :         }
    7017            2 : 
    7018            2 :         Ok(())
    7019            2 :     }
    7020              : 
    7021              :     #[tokio::test]
    7022            2 :     async fn test_random_updates() -> anyhow::Result<()> {
    7023            2 :         let names_algorithms = [
    7024            2 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7025            2 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7026            2 :         ];
    7027            6 :         for (name, algorithm) in names_algorithms {
    7028            4 :             test_random_updates_algorithm(name, algorithm).await?;
    7029            2 :         }
    7030            2 :         Ok(())
    7031            2 :     }
    7032              : 
    7033            4 :     async fn test_random_updates_algorithm(
    7034            4 :         name: &'static str,
    7035            4 :         compaction_algorithm: CompactionAlgorithm,
    7036            4 :     ) -> anyhow::Result<()> {
    7037            4 :         let mut harness = TenantHarness::create(name).await?;
    7038            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7039            4 :             kind: compaction_algorithm,
    7040            4 :         };
    7041            4 :         let (tenant, ctx) = harness.load().await;
    7042            4 :         let tline = tenant
    7043            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7044            4 :             .await?;
    7045              : 
    7046              :         const NUM_KEYS: usize = 1000;
    7047            4 :         let cancel = CancellationToken::new();
    7048            4 : 
    7049            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7050            4 :         let mut test_key_end = test_key;
    7051            4 :         test_key_end.field6 = NUM_KEYS as u32;
    7052            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7053            4 : 
    7054            4 :         let mut keyspace = KeySpaceAccum::new();
    7055            4 : 
    7056            4 :         // Track when each page was last modified. Used to assert that
    7057            4 :         // a read sees the latest page version.
    7058            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7059            4 : 
    7060            4 :         let mut lsn = Lsn(0x10);
    7061              :         #[allow(clippy::needless_range_loop)]
    7062         4004 :         for blknum in 0..NUM_KEYS {
    7063         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7064         4000 :             test_key.field6 = blknum as u32;
    7065         4000 :             let mut writer = tline.writer().await;
    7066         4000 :             writer
    7067         4000 :                 .put(
    7068         4000 :                     test_key,
    7069         4000 :                     lsn,
    7070         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7071         4000 :                     &ctx,
    7072         4000 :                 )
    7073         4000 :                 .await?;
    7074         4000 :             writer.finish_write(lsn);
    7075         4000 :             updated[blknum] = lsn;
    7076         4000 :             drop(writer);
    7077         4000 : 
    7078         4000 :             keyspace.add_key(test_key);
    7079              :         }
    7080              : 
    7081          204 :         for _ in 0..50 {
    7082       200200 :             for _ in 0..NUM_KEYS {
    7083       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7084       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7085       200000 :                 test_key.field6 = blknum as u32;
    7086       200000 :                 let mut writer = tline.writer().await;
    7087       200000 :                 writer
    7088       200000 :                     .put(
    7089       200000 :                         test_key,
    7090       200000 :                         lsn,
    7091       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7092       200000 :                         &ctx,
    7093       200000 :                     )
    7094       200000 :                     .await?;
    7095       200000 :                 writer.finish_write(lsn);
    7096       200000 :                 drop(writer);
    7097       200000 :                 updated[blknum] = lsn;
    7098              :             }
    7099              : 
    7100              :             // Read all the blocks
    7101       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7102       200000 :                 test_key.field6 = blknum as u32;
    7103       200000 :                 assert_eq!(
    7104       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7105       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7106              :                 );
    7107              :             }
    7108              : 
    7109              :             // Perform a cycle of flush, and GC
    7110          200 :             tline.freeze_and_flush().await?;
    7111          200 :             tenant
    7112          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7113          200 :                 .await?;
    7114              :         }
    7115              : 
    7116            4 :         Ok(())
    7117            4 :     }
    7118              : 
    7119              :     #[tokio::test]
    7120            2 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7121            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7122            2 :             .await?
    7123            2 :             .load()
    7124            2 :             .await;
    7125            2 :         let mut tline = tenant
    7126            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7127            2 :             .await?;
    7128            2 : 
    7129            2 :         const NUM_KEYS: usize = 1000;
    7130            2 : 
    7131            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7132            2 : 
    7133            2 :         let mut keyspace = KeySpaceAccum::new();
    7134            2 : 
    7135            2 :         let cancel = CancellationToken::new();
    7136            2 : 
    7137            2 :         // Track when each page was last modified. Used to assert that
    7138            2 :         // a read sees the latest page version.
    7139            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7140            2 : 
    7141            2 :         let mut lsn = Lsn(0x10);
    7142            2 :         #[allow(clippy::needless_range_loop)]
    7143         2002 :         for blknum in 0..NUM_KEYS {
    7144         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7145         2000 :             test_key.field6 = blknum as u32;
    7146         2000 :             let mut writer = tline.writer().await;
    7147         2000 :             writer
    7148         2000 :                 .put(
    7149         2000 :                     test_key,
    7150         2000 :                     lsn,
    7151         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7152         2000 :                     &ctx,
    7153         2000 :                 )
    7154         2000 :                 .await?;
    7155         2000 :             writer.finish_write(lsn);
    7156         2000 :             updated[blknum] = lsn;
    7157         2000 :             drop(writer);
    7158         2000 : 
    7159         2000 :             keyspace.add_key(test_key);
    7160            2 :         }
    7161            2 : 
    7162          102 :         for _ in 0..50 {
    7163          100 :             let new_tline_id = TimelineId::generate();
    7164          100 :             tenant
    7165          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7166          100 :                 .await?;
    7167          100 :             tline = tenant
    7168          100 :                 .get_timeline(new_tline_id, true)
    7169          100 :                 .expect("Should have the branched timeline");
    7170            2 : 
    7171       100100 :             for _ in 0..NUM_KEYS {
    7172       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7173       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7174       100000 :                 test_key.field6 = blknum as u32;
    7175       100000 :                 let mut writer = tline.writer().await;
    7176       100000 :                 writer
    7177       100000 :                     .put(
    7178       100000 :                         test_key,
    7179       100000 :                         lsn,
    7180       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7181       100000 :                         &ctx,
    7182       100000 :                     )
    7183       100000 :                     .await?;
    7184       100000 :                 println!("updating {} at {}", blknum, lsn);
    7185       100000 :                 writer.finish_write(lsn);
    7186       100000 :                 drop(writer);
    7187       100000 :                 updated[blknum] = lsn;
    7188            2 :             }
    7189            2 : 
    7190            2 :             // Read all the blocks
    7191       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7192       100000 :                 test_key.field6 = blknum as u32;
    7193       100000 :                 assert_eq!(
    7194       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7195       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7196            2 :                 );
    7197            2 :             }
    7198            2 : 
    7199            2 :             // Perform a cycle of flush, compact, and GC
    7200          100 :             tline.freeze_and_flush().await?;
    7201          100 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7202          100 :             tenant
    7203          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7204          100 :                 .await?;
    7205            2 :         }
    7206            2 : 
    7207            2 :         Ok(())
    7208            2 :     }
    7209              : 
    7210              :     #[tokio::test]
    7211            2 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7212            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7213            2 :             .await?
    7214            2 :             .load()
    7215            2 :             .await;
    7216            2 :         let mut tline = tenant
    7217            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7218            2 :             .await?;
    7219            2 : 
    7220            2 :         const NUM_KEYS: usize = 100;
    7221            2 :         const NUM_TLINES: usize = 50;
    7222            2 : 
    7223            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7224            2 :         // Track page mutation lsns across different timelines.
    7225            2 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7226            2 : 
    7227            2 :         let mut lsn = Lsn(0x10);
    7228            2 : 
    7229            2 :         #[allow(clippy::needless_range_loop)]
    7230          102 :         for idx in 0..NUM_TLINES {
    7231          100 :             let new_tline_id = TimelineId::generate();
    7232          100 :             tenant
    7233          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7234          100 :                 .await?;
    7235          100 :             tline = tenant
    7236          100 :                 .get_timeline(new_tline_id, true)
    7237          100 :                 .expect("Should have the branched timeline");
    7238            2 : 
    7239        10100 :             for _ in 0..NUM_KEYS {
    7240        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    7241        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7242        10000 :                 test_key.field6 = blknum as u32;
    7243        10000 :                 let mut writer = tline.writer().await;
    7244        10000 :                 writer
    7245        10000 :                     .put(
    7246        10000 :                         test_key,
    7247        10000 :                         lsn,
    7248        10000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7249        10000 :                         &ctx,
    7250        10000 :                     )
    7251        10000 :                     .await?;
    7252        10000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7253        10000 :                 writer.finish_write(lsn);
    7254        10000 :                 drop(writer);
    7255        10000 :                 updated[idx][blknum] = lsn;
    7256            2 :             }
    7257            2 :         }
    7258            2 : 
    7259            2 :         // Read pages from leaf timeline across all ancestors.
    7260          100 :         for (idx, lsns) in updated.iter().enumerate() {
    7261        10000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7262            2 :                 // Skip empty mutations.
    7263        10000 :                 if lsn.0 == 0 {
    7264         3656 :                     continue;
    7265         6344 :                 }
    7266         6344 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7267         6344 :                 test_key.field6 = blknum as u32;
    7268         6344 :                 assert_eq!(
    7269         6344 :                     tline.get(test_key, *lsn, &ctx).await?,
    7270         6344 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7271            2 :                 );
    7272            2 :             }
    7273            2 :         }
    7274            2 :         Ok(())
    7275            2 :     }
    7276              : 
    7277              :     #[tokio::test]
    7278            2 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7279            2 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7280            2 :             .await?
    7281            2 :             .load()
    7282            2 :             .await;
    7283            2 : 
    7284            2 :         let initdb_lsn = Lsn(0x20);
    7285            2 :         let utline = tenant
    7286            2 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7287            2 :             .await?;
    7288            2 :         let tline = utline.raw_timeline().unwrap();
    7289            2 : 
    7290            2 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7291            2 :         tline.maybe_spawn_flush_loop();
    7292            2 : 
    7293            2 :         // Make sure the timeline has the minimum set of required keys for operation.
    7294            2 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7295            2 :         // Except if you `put` at `initdb_lsn`.
    7296            2 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7297            2 :         // It uses `repartition()`, which assumes some keys to be present.
    7298            2 :         // Let's make sure the test timeline can handle that case.
    7299            2 :         {
    7300            2 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7301            2 :             assert_eq!(
    7302            2 :                 timeline::FlushLoopState::Running {
    7303            2 :                     expect_initdb_optimization: false,
    7304            2 :                     initdb_optimization_count: 0,
    7305            2 :                 },
    7306            2 :                 *state
    7307            2 :             );
    7308            2 :             *state = timeline::FlushLoopState::Running {
    7309            2 :                 expect_initdb_optimization: true,
    7310            2 :                 initdb_optimization_count: 0,
    7311            2 :             };
    7312            2 :         }
    7313            2 : 
    7314            2 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7315            2 :         // As explained above, the optimization requires some keys to be present.
    7316            2 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7317            2 :         // This is what `create_test_timeline` does, by the way.
    7318            2 :         let mut modification = tline.begin_modification(initdb_lsn);
    7319            2 :         modification
    7320            2 :             .init_empty_test_timeline()
    7321            2 :             .context("init_empty_test_timeline")?;
    7322            2 :         modification
    7323            2 :             .commit(&ctx)
    7324            2 :             .await
    7325            2 :             .context("commit init_empty_test_timeline modification")?;
    7326            2 : 
    7327            2 :         // Do the flush. The flush code will check the expectations that we set above.
    7328            2 :         tline.freeze_and_flush().await?;
    7329            2 : 
    7330            2 :         // assert freeze_and_flush exercised the initdb optimization
    7331            2 :         {
    7332            2 :             let state = tline.flush_loop_state.lock().unwrap();
    7333            2 :             let timeline::FlushLoopState::Running {
    7334            2 :                 expect_initdb_optimization,
    7335            2 :                 initdb_optimization_count,
    7336            2 :             } = *state
    7337            2 :             else {
    7338            2 :                 panic!("unexpected state: {:?}", *state);
    7339            2 :             };
    7340            2 :             assert!(expect_initdb_optimization);
    7341            2 :             assert!(initdb_optimization_count > 0);
    7342            2 :         }
    7343            2 :         Ok(())
    7344            2 :     }
    7345              : 
    7346              :     #[tokio::test]
    7347            2 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7348            2 :         let name = "test_create_guard_crash";
    7349            2 :         let harness = TenantHarness::create(name).await?;
    7350            2 :         {
    7351            2 :             let (tenant, ctx) = harness.load().await;
    7352            2 :             let tline = tenant
    7353            2 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7354            2 :                 .await?;
    7355            2 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7356            2 :             let raw_tline = tline.raw_timeline().unwrap();
    7357            2 :             raw_tline
    7358            2 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7359            2 :                 .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
    7360            2 :                 .await;
    7361            2 :             std::mem::forget(tline);
    7362            2 :         }
    7363            2 : 
    7364            2 :         let (tenant, _) = harness.load().await;
    7365            2 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7366            2 :             Ok(_) => panic!("timeline should've been removed during load"),
    7367            2 :             Err(e) => {
    7368            2 :                 assert_eq!(
    7369            2 :                     e,
    7370            2 :                     GetTimelineError::NotFound {
    7371            2 :                         tenant_id: tenant.tenant_shard_id,
    7372            2 :                         timeline_id: TIMELINE_ID,
    7373            2 :                     }
    7374            2 :                 )
    7375            2 :             }
    7376            2 :         }
    7377            2 : 
    7378            2 :         assert!(!harness
    7379            2 :             .conf
    7380            2 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7381            2 :             .exists());
    7382            2 : 
    7383            2 :         Ok(())
    7384            2 :     }
    7385              : 
    7386              :     #[tokio::test]
    7387            2 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7388            2 :         let names_algorithms = [
    7389            2 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7390            2 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7391            2 :         ];
    7392            6 :         for (name, algorithm) in names_algorithms {
    7393            4 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7394            2 :         }
    7395            2 :         Ok(())
    7396            2 :     }
    7397              : 
    7398            4 :     async fn test_read_at_max_lsn_algorithm(
    7399            4 :         name: &'static str,
    7400            4 :         compaction_algorithm: CompactionAlgorithm,
    7401            4 :     ) -> anyhow::Result<()> {
    7402            4 :         let mut harness = TenantHarness::create(name).await?;
    7403            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7404            4 :             kind: compaction_algorithm,
    7405            4 :         };
    7406            4 :         let (tenant, ctx) = harness.load().await;
    7407            4 :         let tline = tenant
    7408            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7409            4 :             .await?;
    7410              : 
    7411            4 :         let lsn = Lsn(0x10);
    7412            4 :         let compact = false;
    7413            4 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7414              : 
    7415            4 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7416            4 :         let read_lsn = Lsn(u64::MAX - 1);
    7417              : 
    7418            4 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7419            4 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7420              : 
    7421            4 :         Ok(())
    7422            4 :     }
    7423              : 
    7424              :     #[tokio::test]
    7425            2 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7426            2 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7427            2 :         let (tenant, ctx) = harness.load().await;
    7428            2 :         let tline = tenant
    7429            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7430            2 :             .await?;
    7431            2 : 
    7432            2 :         const NUM_KEYS: usize = 1000;
    7433            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7434            2 : 
    7435            2 :         let cancel = CancellationToken::new();
    7436            2 : 
    7437            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7438            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7439            2 :         let mut test_key = base_key;
    7440            2 : 
    7441            2 :         // Track when each page was last modified. Used to assert that
    7442            2 :         // a read sees the latest page version.
    7443            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7444            2 : 
    7445            2 :         let mut lsn = Lsn(0x10);
    7446            2 :         #[allow(clippy::needless_range_loop)]
    7447         2002 :         for blknum in 0..NUM_KEYS {
    7448         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7449         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7450         2000 :             let mut writer = tline.writer().await;
    7451         2000 :             writer
    7452         2000 :                 .put(
    7453         2000 :                     test_key,
    7454         2000 :                     lsn,
    7455         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7456         2000 :                     &ctx,
    7457         2000 :                 )
    7458         2000 :                 .await?;
    7459         2000 :             writer.finish_write(lsn);
    7460         2000 :             updated[blknum] = lsn;
    7461         2000 :             drop(writer);
    7462            2 :         }
    7463            2 : 
    7464            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7465            2 : 
    7466           24 :         for iter in 0..=10 {
    7467            2 :             // Read all the blocks
    7468        22000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7469        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7470        22000 :                 assert_eq!(
    7471        22000 :                     tline.get(test_key, lsn, &ctx).await?,
    7472        22000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7473            2 :                 );
    7474            2 :             }
    7475            2 : 
    7476           22 :             let mut cnt = 0;
    7477        22000 :             for (key, value) in tline
    7478           22 :                 .get_vectored_impl(
    7479           22 :                     keyspace.clone(),
    7480           22 :                     lsn,
    7481           22 :                     &mut ValuesReconstructState::default(),
    7482           22 :                     &ctx,
    7483           22 :                 )
    7484           22 :                 .await?
    7485            2 :             {
    7486        22000 :                 let blknum = key.field6 as usize;
    7487        22000 :                 let value = value?;
    7488        22000 :                 assert!(blknum % STEP == 0);
    7489        22000 :                 let blknum = blknum / STEP;
    7490        22000 :                 assert_eq!(
    7491        22000 :                     value,
    7492        22000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7493        22000 :                 );
    7494        22000 :                 cnt += 1;
    7495            2 :             }
    7496            2 : 
    7497           22 :             assert_eq!(cnt, NUM_KEYS);
    7498            2 : 
    7499        22022 :             for _ in 0..NUM_KEYS {
    7500        22000 :                 lsn = Lsn(lsn.0 + 0x10);
    7501        22000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7502        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7503        22000 :                 let mut writer = tline.writer().await;
    7504        22000 :                 writer
    7505        22000 :                     .put(
    7506        22000 :                         test_key,
    7507        22000 :                         lsn,
    7508        22000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7509        22000 :                         &ctx,
    7510        22000 :                     )
    7511        22000 :                     .await?;
    7512        22000 :                 writer.finish_write(lsn);
    7513        22000 :                 drop(writer);
    7514        22000 :                 updated[blknum] = lsn;
    7515            2 :             }
    7516            2 : 
    7517            2 :             // Perform two cycles of flush, compact, and GC
    7518           66 :             for round in 0..2 {
    7519           44 :                 tline.freeze_and_flush().await?;
    7520           44 :                 tline
    7521           44 :                     .compact(
    7522           44 :                         &cancel,
    7523           44 :                         if iter % 5 == 0 && round == 0 {
    7524            6 :                             let mut flags = EnumSet::new();
    7525            6 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7526            6 :                             flags.insert(CompactFlags::ForceRepartition);
    7527            6 :                             flags
    7528            2 :                         } else {
    7529           38 :                             EnumSet::empty()
    7530            2 :                         },
    7531           44 :                         &ctx,
    7532           44 :                     )
    7533           44 :                     .await?;
    7534           44 :                 tenant
    7535           44 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7536           44 :                     .await?;
    7537            2 :             }
    7538            2 :         }
    7539            2 : 
    7540            2 :         Ok(())
    7541            2 :     }
    7542              : 
    7543              :     #[tokio::test]
    7544            2 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7545            2 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7546            2 :         let (tenant, ctx) = harness.load().await;
    7547            2 :         let tline = tenant
    7548            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7549            2 :             .await?;
    7550            2 : 
    7551            2 :         let cancel = CancellationToken::new();
    7552            2 : 
    7553            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7554            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7555            2 :         let test_key = base_key;
    7556            2 :         let mut lsn = Lsn(0x10);
    7557            2 : 
    7558           42 :         for _ in 0..20 {
    7559           40 :             lsn = Lsn(lsn.0 + 0x10);
    7560           40 :             let mut writer = tline.writer().await;
    7561           40 :             writer
    7562           40 :                 .put(
    7563           40 :                     test_key,
    7564           40 :                     lsn,
    7565           40 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7566           40 :                     &ctx,
    7567           40 :                 )
    7568           40 :                 .await?;
    7569           40 :             writer.finish_write(lsn);
    7570           40 :             drop(writer);
    7571           40 :             tline.freeze_and_flush().await?; // force create a delta layer
    7572            2 :         }
    7573            2 : 
    7574            2 :         let before_num_l0_delta_files =
    7575            2 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7576            2 : 
    7577            2 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7578            2 : 
    7579            2 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7580            2 : 
    7581            2 :         assert!(after_num_l0_delta_files < before_num_l0_delta_files, "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}");
    7582            2 : 
    7583            2 :         assert_eq!(
    7584            2 :             tline.get(test_key, lsn, &ctx).await?,
    7585            2 :             test_img(&format!("{} at {}", 0, lsn))
    7586            2 :         );
    7587            2 : 
    7588            2 :         Ok(())
    7589            2 :     }
    7590              : 
    7591              :     #[tokio::test]
    7592            2 :     async fn test_aux_file_e2e() {
    7593            2 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7594            2 : 
    7595            2 :         let (tenant, ctx) = harness.load().await;
    7596            2 : 
    7597            2 :         let mut lsn = Lsn(0x08);
    7598            2 : 
    7599            2 :         let tline: Arc<Timeline> = tenant
    7600            2 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7601            2 :             .await
    7602            2 :             .unwrap();
    7603            2 : 
    7604            2 :         {
    7605            2 :             lsn += 8;
    7606            2 :             let mut modification = tline.begin_modification(lsn);
    7607            2 :             modification
    7608            2 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7609            2 :                 .await
    7610            2 :                 .unwrap();
    7611            2 :             modification.commit(&ctx).await.unwrap();
    7612            2 :         }
    7613            2 : 
    7614            2 :         // we can read everything from the storage
    7615            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7616            2 :         assert_eq!(
    7617            2 :             files.get("pg_logical/mappings/test1"),
    7618            2 :             Some(&bytes::Bytes::from_static(b"first"))
    7619            2 :         );
    7620            2 : 
    7621            2 :         {
    7622            2 :             lsn += 8;
    7623            2 :             let mut modification = tline.begin_modification(lsn);
    7624            2 :             modification
    7625            2 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7626            2 :                 .await
    7627            2 :                 .unwrap();
    7628            2 :             modification.commit(&ctx).await.unwrap();
    7629            2 :         }
    7630            2 : 
    7631            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7632            2 :         assert_eq!(
    7633            2 :             files.get("pg_logical/mappings/test2"),
    7634            2 :             Some(&bytes::Bytes::from_static(b"second"))
    7635            2 :         );
    7636            2 : 
    7637            2 :         let child = tenant
    7638            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7639            2 :             .await
    7640            2 :             .unwrap();
    7641            2 : 
    7642            2 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    7643            2 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7644            2 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7645            2 :     }
    7646              : 
    7647              :     #[tokio::test]
    7648            2 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7649            2 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7650            2 :         let (tenant, ctx) = harness.load().await;
    7651            2 :         let tline = tenant
    7652            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7653            2 :             .await?;
    7654            2 : 
    7655            2 :         const NUM_KEYS: usize = 1000;
    7656            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7657            2 : 
    7658            2 :         let cancel = CancellationToken::new();
    7659            2 : 
    7660            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7661            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7662            2 :         let mut test_key = base_key;
    7663            2 :         let mut lsn = Lsn(0x10);
    7664            2 : 
    7665            8 :         async fn scan_with_statistics(
    7666            8 :             tline: &Timeline,
    7667            8 :             keyspace: &KeySpace,
    7668            8 :             lsn: Lsn,
    7669            8 :             ctx: &RequestContext,
    7670            8 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7671            8 :             let mut reconstruct_state = ValuesReconstructState::default();
    7672            8 :             let res = tline
    7673            8 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7674            8 :                 .await?;
    7675            8 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7676            8 :         }
    7677            2 : 
    7678            2 :         #[allow(clippy::needless_range_loop)]
    7679         2002 :         for blknum in 0..NUM_KEYS {
    7680         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7681         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7682         2000 :             let mut writer = tline.writer().await;
    7683         2000 :             writer
    7684         2000 :                 .put(
    7685         2000 :                     test_key,
    7686         2000 :                     lsn,
    7687         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7688         2000 :                     &ctx,
    7689         2000 :                 )
    7690         2000 :                 .await?;
    7691         2000 :             writer.finish_write(lsn);
    7692         2000 :             drop(writer);
    7693            2 :         }
    7694            2 : 
    7695            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7696            2 : 
    7697           22 :         for iter in 1..=10 {
    7698        20020 :             for _ in 0..NUM_KEYS {
    7699        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7700        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7701        20000 :                 test_key.field6 = (blknum * STEP) as u32;
    7702        20000 :                 let mut writer = tline.writer().await;
    7703        20000 :                 writer
    7704        20000 :                     .put(
    7705        20000 :                         test_key,
    7706        20000 :                         lsn,
    7707        20000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7708        20000 :                         &ctx,
    7709        20000 :                     )
    7710        20000 :                     .await?;
    7711        20000 :                 writer.finish_write(lsn);
    7712        20000 :                 drop(writer);
    7713            2 :             }
    7714            2 : 
    7715           20 :             tline.freeze_and_flush().await?;
    7716            2 : 
    7717           20 :             if iter % 5 == 0 {
    7718            4 :                 let (_, before_delta_file_accessed) =
    7719            4 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7720            4 :                 tline
    7721            4 :                     .compact(
    7722            4 :                         &cancel,
    7723            4 :                         {
    7724            4 :                             let mut flags = EnumSet::new();
    7725            4 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7726            4 :                             flags.insert(CompactFlags::ForceRepartition);
    7727            4 :                             flags
    7728            4 :                         },
    7729            4 :                         &ctx,
    7730            4 :                     )
    7731            4 :                     .await?;
    7732            4 :                 let (_, after_delta_file_accessed) =
    7733            4 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7734            4 :                 assert!(after_delta_file_accessed < before_delta_file_accessed, "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}");
    7735            2 :                 // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
    7736            4 :                 assert!(
    7737            4 :                     after_delta_file_accessed <= 2,
    7738            2 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7739            2 :                 );
    7740           16 :             }
    7741            2 :         }
    7742            2 : 
    7743            2 :         Ok(())
    7744            2 :     }
    7745              : 
    7746              :     #[tokio::test]
    7747            2 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7748            2 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7749            2 :         let (tenant, ctx) = harness.load().await;
    7750            2 : 
    7751            2 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7752            2 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7753            2 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7754            2 : 
    7755            2 :         let tline = tenant
    7756            2 :             .create_test_timeline_with_layers(
    7757            2 :                 TIMELINE_ID,
    7758            2 :                 Lsn(0x10),
    7759            2 :                 DEFAULT_PG_VERSION,
    7760            2 :                 &ctx,
    7761            2 :                 Vec::new(), // delta layers
    7762            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7763            2 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7764            2 :             )
    7765            2 :             .await?;
    7766            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7767            2 : 
    7768            2 :         let child = tenant
    7769            2 :             .branch_timeline_test_with_layers(
    7770            2 :                 &tline,
    7771            2 :                 NEW_TIMELINE_ID,
    7772            2 :                 Some(Lsn(0x20)),
    7773            2 :                 &ctx,
    7774            2 :                 Vec::new(), // delta layers
    7775            2 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7776            2 :                 Lsn(0x30),
    7777            2 :             )
    7778            2 :             .await
    7779            2 :             .unwrap();
    7780            2 : 
    7781            2 :         let lsn = Lsn(0x30);
    7782            2 : 
    7783            2 :         // test vectored get on parent timeline
    7784            2 :         assert_eq!(
    7785            2 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7786            2 :             Some(test_img("data key 1"))
    7787            2 :         );
    7788            2 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7789            2 :             .await
    7790            2 :             .unwrap_err()
    7791            2 :             .is_missing_key_error());
    7792            2 :         assert!(
    7793            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7794            2 :                 .await
    7795            2 :                 .unwrap_err()
    7796            2 :                 .is_missing_key_error()
    7797            2 :         );
    7798            2 : 
    7799            2 :         // test vectored get on child timeline
    7800            2 :         assert_eq!(
    7801            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7802            2 :             Some(test_img("data key 1"))
    7803            2 :         );
    7804            2 :         assert_eq!(
    7805            2 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7806            2 :             Some(test_img("data key 2"))
    7807            2 :         );
    7808            2 :         assert!(
    7809            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7810            2 :                 .await
    7811            2 :                 .unwrap_err()
    7812            2 :                 .is_missing_key_error()
    7813            2 :         );
    7814            2 : 
    7815            2 :         Ok(())
    7816            2 :     }
    7817              : 
    7818              :     #[tokio::test]
    7819            2 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7820            2 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7821            2 :         let (tenant, ctx) = harness.load().await;
    7822            2 : 
    7823            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7824            2 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7825            2 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7826            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7827            2 : 
    7828            2 :         let tline = tenant
    7829            2 :             .create_test_timeline_with_layers(
    7830            2 :                 TIMELINE_ID,
    7831            2 :                 Lsn(0x10),
    7832            2 :                 DEFAULT_PG_VERSION,
    7833            2 :                 &ctx,
    7834            2 :                 Vec::new(), // delta layers
    7835            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
    7836            2 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7837            2 :             )
    7838            2 :             .await?;
    7839            2 : 
    7840            2 :         let child = tenant
    7841            2 :             .branch_timeline_test_with_layers(
    7842            2 :                 &tline,
    7843            2 :                 NEW_TIMELINE_ID,
    7844            2 :                 Some(Lsn(0x20)),
    7845            2 :                 &ctx,
    7846            2 :                 Vec::new(), // delta layers
    7847            2 :                 vec![(
    7848            2 :                     Lsn(0x30),
    7849            2 :                     vec![(base_key_child, test_img("metadata key 2"))],
    7850            2 :                 )], // image layers
    7851            2 :                 Lsn(0x30),
    7852            2 :             )
    7853            2 :             .await
    7854            2 :             .unwrap();
    7855            2 : 
    7856            2 :         let lsn = Lsn(0x30);
    7857            2 : 
    7858            2 :         // test vectored get on parent timeline
    7859            2 :         assert_eq!(
    7860            2 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7861            2 :             Some(test_img("metadata key 1"))
    7862            2 :         );
    7863            2 :         assert_eq!(
    7864            2 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7865            2 :             None
    7866            2 :         );
    7867            2 :         assert_eq!(
    7868            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7869            2 :             None
    7870            2 :         );
    7871            2 : 
    7872            2 :         // test vectored get on child timeline
    7873            2 :         assert_eq!(
    7874            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7875            2 :             None
    7876            2 :         );
    7877            2 :         assert_eq!(
    7878            2 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7879            2 :             Some(test_img("metadata key 2"))
    7880            2 :         );
    7881            2 :         assert_eq!(
    7882            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7883            2 :             None
    7884            2 :         );
    7885            2 : 
    7886            2 :         Ok(())
    7887            2 :     }
    7888              : 
    7889           36 :     async fn get_vectored_impl_wrapper(
    7890           36 :         tline: &Arc<Timeline>,
    7891           36 :         key: Key,
    7892           36 :         lsn: Lsn,
    7893           36 :         ctx: &RequestContext,
    7894           36 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7895           36 :         let mut reconstruct_state = ValuesReconstructState::new();
    7896           36 :         let mut res = tline
    7897           36 :             .get_vectored_impl(
    7898           36 :                 KeySpace::single(key..key.next()),
    7899           36 :                 lsn,
    7900           36 :                 &mut reconstruct_state,
    7901           36 :                 ctx,
    7902           36 :             )
    7903           36 :             .await?;
    7904           30 :         Ok(res.pop_last().map(|(k, v)| {
    7905           18 :             assert_eq!(k, key);
    7906           18 :             v.unwrap()
    7907           30 :         }))
    7908           36 :     }
    7909              : 
    7910              :     #[tokio::test]
    7911            2 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    7912            2 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    7913            2 :         let (tenant, ctx) = harness.load().await;
    7914            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7915            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7916            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7917            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7918            2 : 
    7919            2 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    7920            2 :         // Lsn 0x30 key0, key3, no key1+key2
    7921            2 :         // Lsn 0x20 key1+key2 tomestones
    7922            2 :         // Lsn 0x10 key1 in image, key2 in delta
    7923            2 :         let tline = tenant
    7924            2 :             .create_test_timeline_with_layers(
    7925            2 :                 TIMELINE_ID,
    7926            2 :                 Lsn(0x10),
    7927            2 :                 DEFAULT_PG_VERSION,
    7928            2 :                 &ctx,
    7929            2 :                 // delta layers
    7930            2 :                 vec![
    7931            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7932            2 :                         Lsn(0x10)..Lsn(0x20),
    7933            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7934            2 :                     ),
    7935            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7936            2 :                         Lsn(0x20)..Lsn(0x30),
    7937            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7938            2 :                     ),
    7939            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7940            2 :                         Lsn(0x20)..Lsn(0x30),
    7941            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7942            2 :                     ),
    7943            2 :                 ],
    7944            2 :                 // image layers
    7945            2 :                 vec![
    7946            2 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    7947            2 :                     (
    7948            2 :                         Lsn(0x30),
    7949            2 :                         vec![
    7950            2 :                             (key0, test_img("metadata key 0")),
    7951            2 :                             (key3, test_img("metadata key 3")),
    7952            2 :                         ],
    7953            2 :                     ),
    7954            2 :                 ],
    7955            2 :                 Lsn(0x30),
    7956            2 :             )
    7957            2 :             .await?;
    7958            2 : 
    7959            2 :         let lsn = Lsn(0x30);
    7960            2 :         let old_lsn = Lsn(0x20);
    7961            2 : 
    7962            2 :         assert_eq!(
    7963            2 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    7964            2 :             Some(test_img("metadata key 0"))
    7965            2 :         );
    7966            2 :         assert_eq!(
    7967            2 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    7968            2 :             None,
    7969            2 :         );
    7970            2 :         assert_eq!(
    7971            2 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    7972            2 :             None,
    7973            2 :         );
    7974            2 :         assert_eq!(
    7975            2 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    7976            2 :             Some(Bytes::new()),
    7977            2 :         );
    7978            2 :         assert_eq!(
    7979            2 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    7980            2 :             Some(Bytes::new()),
    7981            2 :         );
    7982            2 :         assert_eq!(
    7983            2 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    7984            2 :             Some(test_img("metadata key 3"))
    7985            2 :         );
    7986            2 : 
    7987            2 :         Ok(())
    7988            2 :     }
    7989              : 
    7990              :     #[tokio::test]
    7991            2 :     async fn test_metadata_tombstone_image_creation() {
    7992            2 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    7993            2 :             .await
    7994            2 :             .unwrap();
    7995            2 :         let (tenant, ctx) = harness.load().await;
    7996            2 : 
    7997            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7998            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7999            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8000            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8001            2 : 
    8002            2 :         let tline = tenant
    8003            2 :             .create_test_timeline_with_layers(
    8004            2 :                 TIMELINE_ID,
    8005            2 :                 Lsn(0x10),
    8006            2 :                 DEFAULT_PG_VERSION,
    8007            2 :                 &ctx,
    8008            2 :                 // delta layers
    8009            2 :                 vec![
    8010            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8011            2 :                         Lsn(0x10)..Lsn(0x20),
    8012            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8013            2 :                     ),
    8014            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8015            2 :                         Lsn(0x20)..Lsn(0x30),
    8016            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8017            2 :                     ),
    8018            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8019            2 :                         Lsn(0x20)..Lsn(0x30),
    8020            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8021            2 :                     ),
    8022            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8023            2 :                         Lsn(0x30)..Lsn(0x40),
    8024            2 :                         vec![
    8025            2 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8026            2 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8027            2 :                         ],
    8028            2 :                     ),
    8029            2 :                 ],
    8030            2 :                 // image layers
    8031            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8032            2 :                 Lsn(0x40),
    8033            2 :             )
    8034            2 :             .await
    8035            2 :             .unwrap();
    8036            2 : 
    8037            2 :         let cancel = CancellationToken::new();
    8038            2 : 
    8039            2 :         tline
    8040            2 :             .compact(
    8041            2 :                 &cancel,
    8042            2 :                 {
    8043            2 :                     let mut flags = EnumSet::new();
    8044            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8045            2 :                     flags.insert(CompactFlags::ForceRepartition);
    8046            2 :                     flags
    8047            2 :                 },
    8048            2 :                 &ctx,
    8049            2 :             )
    8050            2 :             .await
    8051            2 :             .unwrap();
    8052            2 : 
    8053            2 :         // Image layers are created at last_record_lsn
    8054            2 :         let images = tline
    8055            2 :             .inspect_image_layers(Lsn(0x40), &ctx)
    8056            2 :             .await
    8057            2 :             .unwrap()
    8058            2 :             .into_iter()
    8059           18 :             .filter(|(k, _)| k.is_metadata_key())
    8060            2 :             .collect::<Vec<_>>();
    8061            2 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8062            2 :     }
    8063              : 
    8064              :     #[tokio::test]
    8065            2 :     async fn test_metadata_tombstone_empty_image_creation() {
    8066            2 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8067            2 :             .await
    8068            2 :             .unwrap();
    8069            2 :         let (tenant, ctx) = harness.load().await;
    8070            2 : 
    8071            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8072            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8073            2 : 
    8074            2 :         let tline = tenant
    8075            2 :             .create_test_timeline_with_layers(
    8076            2 :                 TIMELINE_ID,
    8077            2 :                 Lsn(0x10),
    8078            2 :                 DEFAULT_PG_VERSION,
    8079            2 :                 &ctx,
    8080            2 :                 // delta layers
    8081            2 :                 vec![
    8082            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8083            2 :                         Lsn(0x10)..Lsn(0x20),
    8084            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8085            2 :                     ),
    8086            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8087            2 :                         Lsn(0x20)..Lsn(0x30),
    8088            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8089            2 :                     ),
    8090            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8091            2 :                         Lsn(0x20)..Lsn(0x30),
    8092            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8093            2 :                     ),
    8094            2 :                 ],
    8095            2 :                 // image layers
    8096            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8097            2 :                 Lsn(0x30),
    8098            2 :             )
    8099            2 :             .await
    8100            2 :             .unwrap();
    8101            2 : 
    8102            2 :         let cancel = CancellationToken::new();
    8103            2 : 
    8104            2 :         tline
    8105            2 :             .compact(
    8106            2 :                 &cancel,
    8107            2 :                 {
    8108            2 :                     let mut flags = EnumSet::new();
    8109            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8110            2 :                     flags.insert(CompactFlags::ForceRepartition);
    8111            2 :                     flags
    8112            2 :                 },
    8113            2 :                 &ctx,
    8114            2 :             )
    8115            2 :             .await
    8116            2 :             .unwrap();
    8117            2 : 
    8118            2 :         // Image layers are created at last_record_lsn
    8119            2 :         let images = tline
    8120            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8121            2 :             .await
    8122            2 :             .unwrap()
    8123            2 :             .into_iter()
    8124           14 :             .filter(|(k, _)| k.is_metadata_key())
    8125            2 :             .collect::<Vec<_>>();
    8126            2 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8127            2 :     }
    8128              : 
    8129              :     #[tokio::test]
    8130            2 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8131            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8132            2 :         let (tenant, ctx) = harness.load().await;
    8133            2 : 
    8134          102 :         fn get_key(id: u32) -> Key {
    8135          102 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8136          102 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8137          102 :             key.field6 = id;
    8138          102 :             key
    8139          102 :         }
    8140            2 : 
    8141            2 :         // We create
    8142            2 :         // - one bottom-most image layer,
    8143            2 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8144            2 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8145            2 :         // - a delta layer D3 above the horizon.
    8146            2 :         //
    8147            2 :         //                             | D3 |
    8148            2 :         //  | D1 |
    8149            2 :         // -|    |-- gc horizon -----------------
    8150            2 :         //  |    |                | D2 |
    8151            2 :         // --------- img layer ------------------
    8152            2 :         //
    8153            2 :         // What we should expact from this compaction is:
    8154            2 :         //                             | D3 |
    8155            2 :         //  | Part of D1 |
    8156            2 :         // --------- img layer with D1+D2 at GC horizon------------------
    8157            2 : 
    8158            2 :         // img layer at 0x10
    8159            2 :         let img_layer = (0..10)
    8160           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8161            2 :             .collect_vec();
    8162            2 : 
    8163            2 :         let delta1 = vec![
    8164            2 :             (
    8165            2 :                 get_key(1),
    8166            2 :                 Lsn(0x20),
    8167            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    8168            2 :             ),
    8169            2 :             (
    8170            2 :                 get_key(2),
    8171            2 :                 Lsn(0x30),
    8172            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    8173            2 :             ),
    8174            2 :             (
    8175            2 :                 get_key(3),
    8176            2 :                 Lsn(0x40),
    8177            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    8178            2 :             ),
    8179            2 :         ];
    8180            2 :         let delta2 = vec![
    8181            2 :             (
    8182            2 :                 get_key(5),
    8183            2 :                 Lsn(0x20),
    8184            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    8185            2 :             ),
    8186            2 :             (
    8187            2 :                 get_key(6),
    8188            2 :                 Lsn(0x20),
    8189            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    8190            2 :             ),
    8191            2 :         ];
    8192            2 :         let delta3 = vec![
    8193            2 :             (
    8194            2 :                 get_key(8),
    8195            2 :                 Lsn(0x48),
    8196            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    8197            2 :             ),
    8198            2 :             (
    8199            2 :                 get_key(9),
    8200            2 :                 Lsn(0x48),
    8201            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    8202            2 :             ),
    8203            2 :         ];
    8204            2 : 
    8205            2 :         let tline = tenant
    8206            2 :             .create_test_timeline_with_layers(
    8207            2 :                 TIMELINE_ID,
    8208            2 :                 Lsn(0x10),
    8209            2 :                 DEFAULT_PG_VERSION,
    8210            2 :                 &ctx,
    8211            2 :                 vec![
    8212            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8213            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8214            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8215            2 :                 ], // delta layers
    8216            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8217            2 :                 Lsn(0x50),
    8218            2 :             )
    8219            2 :             .await?;
    8220            2 :         {
    8221            2 :             tline
    8222            2 :                 .latest_gc_cutoff_lsn
    8223            2 :                 .lock_for_write()
    8224            2 :                 .store_and_unlock(Lsn(0x30))
    8225            2 :                 .wait()
    8226            2 :                 .await;
    8227            2 :             // Update GC info
    8228            2 :             let mut guard = tline.gc_info.write().unwrap();
    8229            2 :             guard.cutoffs.time = Lsn(0x30);
    8230            2 :             guard.cutoffs.space = Lsn(0x30);
    8231            2 :         }
    8232            2 : 
    8233            2 :         let expected_result = [
    8234            2 :             Bytes::from_static(b"value 0@0x10"),
    8235            2 :             Bytes::from_static(b"value 1@0x20"),
    8236            2 :             Bytes::from_static(b"value 2@0x30"),
    8237            2 :             Bytes::from_static(b"value 3@0x40"),
    8238            2 :             Bytes::from_static(b"value 4@0x10"),
    8239            2 :             Bytes::from_static(b"value 5@0x20"),
    8240            2 :             Bytes::from_static(b"value 6@0x20"),
    8241            2 :             Bytes::from_static(b"value 7@0x10"),
    8242            2 :             Bytes::from_static(b"value 8@0x48"),
    8243            2 :             Bytes::from_static(b"value 9@0x48"),
    8244            2 :         ];
    8245            2 : 
    8246           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8247           20 :             assert_eq!(
    8248           20 :                 tline
    8249           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8250           20 :                     .await
    8251           20 :                     .unwrap(),
    8252            2 :                 expected
    8253            2 :             );
    8254            2 :         }
    8255            2 : 
    8256            2 :         let cancel = CancellationToken::new();
    8257            2 :         tline
    8258            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8259            2 :             .await
    8260            2 :             .unwrap();
    8261            2 : 
    8262           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8263           20 :             assert_eq!(
    8264           20 :                 tline
    8265           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8266           20 :                     .await
    8267           20 :                     .unwrap(),
    8268            2 :                 expected
    8269            2 :             );
    8270            2 :         }
    8271            2 : 
    8272            2 :         // Check if the image layer at the GC horizon contains exactly what we want
    8273            2 :         let image_at_gc_horizon = tline
    8274            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8275            2 :             .await
    8276            2 :             .unwrap()
    8277            2 :             .into_iter()
    8278           34 :             .filter(|(k, _)| k.is_metadata_key())
    8279            2 :             .collect::<Vec<_>>();
    8280            2 : 
    8281            2 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8282            2 :         let expected_result = [
    8283            2 :             Bytes::from_static(b"value 0@0x10"),
    8284            2 :             Bytes::from_static(b"value 1@0x20"),
    8285            2 :             Bytes::from_static(b"value 2@0x30"),
    8286            2 :             Bytes::from_static(b"value 3@0x10"),
    8287            2 :             Bytes::from_static(b"value 4@0x10"),
    8288            2 :             Bytes::from_static(b"value 5@0x20"),
    8289            2 :             Bytes::from_static(b"value 6@0x20"),
    8290            2 :             Bytes::from_static(b"value 7@0x10"),
    8291            2 :             Bytes::from_static(b"value 8@0x10"),
    8292            2 :             Bytes::from_static(b"value 9@0x10"),
    8293            2 :         ];
    8294           22 :         for idx in 0..10 {
    8295           20 :             assert_eq!(
    8296           20 :                 image_at_gc_horizon[idx],
    8297           20 :                 (get_key(idx as u32), expected_result[idx].clone())
    8298           20 :             );
    8299            2 :         }
    8300            2 : 
    8301            2 :         // Check if old layers are removed / new layers have the expected LSN
    8302            2 :         let all_layers = inspect_and_sort(&tline, None).await;
    8303            2 :         assert_eq!(
    8304            2 :             all_layers,
    8305            2 :             vec![
    8306            2 :                 // Image layer at GC horizon
    8307            2 :                 PersistentLayerKey {
    8308            2 :                     key_range: Key::MIN..Key::MAX,
    8309            2 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8310            2 :                     is_delta: false
    8311            2 :                 },
    8312            2 :                 // The delta layer below the horizon
    8313            2 :                 PersistentLayerKey {
    8314            2 :                     key_range: get_key(3)..get_key(4),
    8315            2 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8316            2 :                     is_delta: true
    8317            2 :                 },
    8318            2 :                 // The delta3 layer that should not be picked for the compaction
    8319            2 :                 PersistentLayerKey {
    8320            2 :                     key_range: get_key(8)..get_key(10),
    8321            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8322            2 :                     is_delta: true
    8323            2 :                 }
    8324            2 :             ]
    8325            2 :         );
    8326            2 : 
    8327            2 :         // increase GC horizon and compact again
    8328            2 :         {
    8329            2 :             tline
    8330            2 :                 .latest_gc_cutoff_lsn
    8331            2 :                 .lock_for_write()
    8332            2 :                 .store_and_unlock(Lsn(0x40))
    8333            2 :                 .wait()
    8334            2 :                 .await;
    8335            2 :             // Update GC info
    8336            2 :             let mut guard = tline.gc_info.write().unwrap();
    8337            2 :             guard.cutoffs.time = Lsn(0x40);
    8338            2 :             guard.cutoffs.space = Lsn(0x40);
    8339            2 :         }
    8340            2 :         tline
    8341            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8342            2 :             .await
    8343            2 :             .unwrap();
    8344            2 : 
    8345            2 :         Ok(())
    8346            2 :     }
    8347              : 
    8348              :     #[cfg(feature = "testing")]
    8349              :     #[tokio::test]
    8350            2 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8351            2 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8352            2 :         let (tenant, ctx) = harness.load().await;
    8353            2 : 
    8354           24 :         fn get_key(id: u32) -> Key {
    8355           24 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8356           24 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8357           24 :             key.field6 = id;
    8358           24 :             key
    8359           24 :         }
    8360            2 : 
    8361            2 :         let delta1 = vec![
    8362            2 :             (
    8363            2 :                 get_key(1),
    8364            2 :                 Lsn(0x20),
    8365            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8366            2 :             ),
    8367            2 :             (
    8368            2 :                 get_key(1),
    8369            2 :                 Lsn(0x30),
    8370            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8371            2 :             ),
    8372            2 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8373            2 :             (
    8374            2 :                 get_key(2),
    8375            2 :                 Lsn(0x20),
    8376            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8377            2 :             ),
    8378            2 :             (
    8379            2 :                 get_key(2),
    8380            2 :                 Lsn(0x30),
    8381            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8382            2 :             ),
    8383            2 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8384            2 :             (
    8385            2 :                 get_key(3),
    8386            2 :                 Lsn(0x20),
    8387            2 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8388            2 :             ),
    8389            2 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8390            2 :             (
    8391            2 :                 get_key(4),
    8392            2 :                 Lsn(0x20),
    8393            2 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8394            2 :             ),
    8395            2 :         ];
    8396            2 :         let image1 = vec![(get_key(1), "0x10".into())];
    8397            2 : 
    8398            2 :         let tline = tenant
    8399            2 :             .create_test_timeline_with_layers(
    8400            2 :                 TIMELINE_ID,
    8401            2 :                 Lsn(0x10),
    8402            2 :                 DEFAULT_PG_VERSION,
    8403            2 :                 &ctx,
    8404            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8405            2 :                     Lsn(0x10)..Lsn(0x40),
    8406            2 :                     delta1,
    8407            2 :                 )], // delta layers
    8408            2 :                 vec![(Lsn(0x10), image1)], // image layers
    8409            2 :                 Lsn(0x50),
    8410            2 :             )
    8411            2 :             .await?;
    8412            2 : 
    8413            2 :         assert_eq!(
    8414            2 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8415            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8416            2 :         );
    8417            2 :         assert_eq!(
    8418            2 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8419            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8420            2 :         );
    8421            2 : 
    8422            2 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8423            2 : 
    8424            2 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8425            2 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8426            2 : 
    8427            2 :         Ok(())
    8428            2 :     }
    8429              : 
    8430              :     #[tokio::test(start_paused = true)]
    8431            2 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8432            2 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8433            2 :             .await
    8434            2 :             .unwrap()
    8435            2 :             .load()
    8436            2 :             .await;
    8437            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8438            2 :         // initial transition into AttachedSingle.
    8439            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8440            2 :         tokio::time::resume();
    8441            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8442            2 : 
    8443            2 :         let end_lsn = Lsn(0x100);
    8444            2 :         let image_layers = (0x20..=0x90)
    8445            2 :             .step_by(0x10)
    8446           16 :             .map(|n| {
    8447           16 :                 (
    8448           16 :                     Lsn(n),
    8449           16 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8450           16 :                 )
    8451           16 :             })
    8452            2 :             .collect();
    8453            2 : 
    8454            2 :         let timeline = tenant
    8455            2 :             .create_test_timeline_with_layers(
    8456            2 :                 TIMELINE_ID,
    8457            2 :                 Lsn(0x10),
    8458            2 :                 DEFAULT_PG_VERSION,
    8459            2 :                 &ctx,
    8460            2 :                 Vec::new(),
    8461            2 :                 image_layers,
    8462            2 :                 end_lsn,
    8463            2 :             )
    8464            2 :             .await?;
    8465            2 : 
    8466            2 :         let leased_lsns = [0x30, 0x50, 0x70];
    8467            2 :         let mut leases = Vec::new();
    8468            6 :         leased_lsns.iter().for_each(|n| {
    8469            6 :             leases.push(
    8470            6 :                 timeline
    8471            6 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8472            6 :                     .expect("lease request should succeed"),
    8473            6 :             );
    8474            6 :         });
    8475            2 : 
    8476            2 :         let updated_lease_0 = timeline
    8477            2 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8478            2 :             .expect("lease renewal should succeed");
    8479            2 :         assert_eq!(
    8480            2 :             updated_lease_0.valid_until, leases[0].valid_until,
    8481            2 :             " Renewing with shorter lease should not change the lease."
    8482            2 :         );
    8483            2 : 
    8484            2 :         let updated_lease_1 = timeline
    8485            2 :             .renew_lsn_lease(
    8486            2 :                 Lsn(leased_lsns[1]),
    8487            2 :                 timeline.get_lsn_lease_length() * 2,
    8488            2 :                 &ctx,
    8489            2 :             )
    8490            2 :             .expect("lease renewal should succeed");
    8491            2 :         assert!(
    8492            2 :             updated_lease_1.valid_until > leases[1].valid_until,
    8493            2 :             "Renewing with a long lease should renew lease with later expiration time."
    8494            2 :         );
    8495            2 : 
    8496            2 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8497            2 :         info!(
    8498            2 :             "latest_gc_cutoff_lsn: {}",
    8499            0 :             *timeline.get_latest_gc_cutoff_lsn()
    8500            2 :         );
    8501            2 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8502            2 : 
    8503            2 :         let res = tenant
    8504            2 :             .gc_iteration(
    8505            2 :                 Some(TIMELINE_ID),
    8506            2 :                 0,
    8507            2 :                 Duration::ZERO,
    8508            2 :                 &CancellationToken::new(),
    8509            2 :                 &ctx,
    8510            2 :             )
    8511            2 :             .await
    8512            2 :             .unwrap();
    8513            2 : 
    8514            2 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8515            2 :         // 0/10: initdb layer
    8516            2 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8517            2 :         assert_eq!(res.layers_needed_by_leases, 7);
    8518            2 :         // Keeping 0/90 b/c it is the latest layer.
    8519            2 :         assert_eq!(res.layers_not_updated, 1);
    8520            2 :         // Removed 0/80.
    8521            2 :         assert_eq!(res.layers_removed, 1);
    8522            2 : 
    8523            2 :         // Make lease on a already GC-ed LSN.
    8524            2 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8525            2 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    8526            2 :         timeline
    8527            2 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8528            2 :             .expect_err("lease request on GC-ed LSN should fail");
    8529            2 : 
    8530            2 :         // Should still be able to renew a currently valid lease
    8531            2 :         // Assumption: original lease to is still valid for 0/50.
    8532            2 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8533            2 :         timeline
    8534            2 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8535            2 :             .expect("lease renewal with validation should succeed");
    8536            2 : 
    8537            2 :         Ok(())
    8538            2 :     }
    8539              : 
    8540              :     #[cfg(feature = "testing")]
    8541              :     #[tokio::test]
    8542            2 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8543            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8544            2 :             "test_simple_bottom_most_compaction_deltas_1",
    8545            2 :             false,
    8546            2 :         )
    8547            2 :         .await
    8548            2 :     }
    8549              : 
    8550              :     #[cfg(feature = "testing")]
    8551              :     #[tokio::test]
    8552            2 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8553            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8554            2 :             "test_simple_bottom_most_compaction_deltas_2",
    8555            2 :             true,
    8556            2 :         )
    8557            2 :         .await
    8558            2 :     }
    8559              : 
    8560              :     #[cfg(feature = "testing")]
    8561            4 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8562            4 :         test_name: &'static str,
    8563            4 :         use_delta_bottom_layer: bool,
    8564            4 :     ) -> anyhow::Result<()> {
    8565            4 :         let harness = TenantHarness::create(test_name).await?;
    8566            4 :         let (tenant, ctx) = harness.load().await;
    8567              : 
    8568          276 :         fn get_key(id: u32) -> Key {
    8569          276 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8570          276 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8571          276 :             key.field6 = id;
    8572          276 :             key
    8573          276 :         }
    8574              : 
    8575              :         // We create
    8576              :         // - one bottom-most image layer,
    8577              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8578              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8579              :         // - a delta layer D3 above the horizon.
    8580              :         //
    8581              :         //                             | D3 |
    8582              :         //  | D1 |
    8583              :         // -|    |-- gc horizon -----------------
    8584              :         //  |    |                | D2 |
    8585              :         // --------- img layer ------------------
    8586              :         //
    8587              :         // What we should expact from this compaction is:
    8588              :         //                             | D3 |
    8589              :         //  | Part of D1 |
    8590              :         // --------- img layer with D1+D2 at GC horizon------------------
    8591              : 
    8592              :         // img layer at 0x10
    8593            4 :         let img_layer = (0..10)
    8594           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8595            4 :             .collect_vec();
    8596            4 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8597            4 :         let delta4 = (0..10)
    8598           40 :             .map(|id| {
    8599           40 :                 (
    8600           40 :                     get_key(id),
    8601           40 :                     Lsn(0x08),
    8602           40 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8603           40 :                 )
    8604           40 :             })
    8605            4 :             .collect_vec();
    8606            4 : 
    8607            4 :         let delta1 = vec![
    8608            4 :             (
    8609            4 :                 get_key(1),
    8610            4 :                 Lsn(0x20),
    8611            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8612            4 :             ),
    8613            4 :             (
    8614            4 :                 get_key(2),
    8615            4 :                 Lsn(0x30),
    8616            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8617            4 :             ),
    8618            4 :             (
    8619            4 :                 get_key(3),
    8620            4 :                 Lsn(0x28),
    8621            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8622            4 :             ),
    8623            4 :             (
    8624            4 :                 get_key(3),
    8625            4 :                 Lsn(0x30),
    8626            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8627            4 :             ),
    8628            4 :             (
    8629            4 :                 get_key(3),
    8630            4 :                 Lsn(0x40),
    8631            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8632            4 :             ),
    8633            4 :         ];
    8634            4 :         let delta2 = vec![
    8635            4 :             (
    8636            4 :                 get_key(5),
    8637            4 :                 Lsn(0x20),
    8638            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8639            4 :             ),
    8640            4 :             (
    8641            4 :                 get_key(6),
    8642            4 :                 Lsn(0x20),
    8643            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8644            4 :             ),
    8645            4 :         ];
    8646            4 :         let delta3 = vec![
    8647            4 :             (
    8648            4 :                 get_key(8),
    8649            4 :                 Lsn(0x48),
    8650            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8651            4 :             ),
    8652            4 :             (
    8653            4 :                 get_key(9),
    8654            4 :                 Lsn(0x48),
    8655            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8656            4 :             ),
    8657            4 :         ];
    8658              : 
    8659            4 :         let tline = if use_delta_bottom_layer {
    8660            2 :             tenant
    8661            2 :                 .create_test_timeline_with_layers(
    8662            2 :                     TIMELINE_ID,
    8663            2 :                     Lsn(0x08),
    8664            2 :                     DEFAULT_PG_VERSION,
    8665            2 :                     &ctx,
    8666            2 :                     vec![
    8667            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8668            2 :                             Lsn(0x08)..Lsn(0x10),
    8669            2 :                             delta4,
    8670            2 :                         ),
    8671            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8672            2 :                             Lsn(0x20)..Lsn(0x48),
    8673            2 :                             delta1,
    8674            2 :                         ),
    8675            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8676            2 :                             Lsn(0x20)..Lsn(0x48),
    8677            2 :                             delta2,
    8678            2 :                         ),
    8679            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8680            2 :                             Lsn(0x48)..Lsn(0x50),
    8681            2 :                             delta3,
    8682            2 :                         ),
    8683            2 :                     ], // delta layers
    8684            2 :                     vec![], // image layers
    8685            2 :                     Lsn(0x50),
    8686            2 :                 )
    8687            2 :                 .await?
    8688              :         } else {
    8689            2 :             tenant
    8690            2 :                 .create_test_timeline_with_layers(
    8691            2 :                     TIMELINE_ID,
    8692            2 :                     Lsn(0x10),
    8693            2 :                     DEFAULT_PG_VERSION,
    8694            2 :                     &ctx,
    8695            2 :                     vec![
    8696            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8697            2 :                             Lsn(0x10)..Lsn(0x48),
    8698            2 :                             delta1,
    8699            2 :                         ),
    8700            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8701            2 :                             Lsn(0x10)..Lsn(0x48),
    8702            2 :                             delta2,
    8703            2 :                         ),
    8704            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8705            2 :                             Lsn(0x48)..Lsn(0x50),
    8706            2 :                             delta3,
    8707            2 :                         ),
    8708            2 :                     ], // delta layers
    8709            2 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8710            2 :                     Lsn(0x50),
    8711            2 :                 )
    8712            2 :                 .await?
    8713              :         };
    8714              :         {
    8715            4 :             tline
    8716            4 :                 .latest_gc_cutoff_lsn
    8717            4 :                 .lock_for_write()
    8718            4 :                 .store_and_unlock(Lsn(0x30))
    8719            4 :                 .wait()
    8720            4 :                 .await;
    8721              :             // Update GC info
    8722            4 :             let mut guard = tline.gc_info.write().unwrap();
    8723            4 :             *guard = GcInfo {
    8724            4 :                 retain_lsns: vec![],
    8725            4 :                 cutoffs: GcCutoffs {
    8726            4 :                     time: Lsn(0x30),
    8727            4 :                     space: Lsn(0x30),
    8728            4 :                 },
    8729            4 :                 leases: Default::default(),
    8730            4 :                 within_ancestor_pitr: false,
    8731            4 :             };
    8732            4 :         }
    8733            4 : 
    8734            4 :         let expected_result = [
    8735            4 :             Bytes::from_static(b"value 0@0x10"),
    8736            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8737            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8738            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8739            4 :             Bytes::from_static(b"value 4@0x10"),
    8740            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8741            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8742            4 :             Bytes::from_static(b"value 7@0x10"),
    8743            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8744            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8745            4 :         ];
    8746            4 : 
    8747            4 :         let expected_result_at_gc_horizon = [
    8748            4 :             Bytes::from_static(b"value 0@0x10"),
    8749            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8750            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8751            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8752            4 :             Bytes::from_static(b"value 4@0x10"),
    8753            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8754            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8755            4 :             Bytes::from_static(b"value 7@0x10"),
    8756            4 :             Bytes::from_static(b"value 8@0x10"),
    8757            4 :             Bytes::from_static(b"value 9@0x10"),
    8758            4 :         ];
    8759              : 
    8760           44 :         for idx in 0..10 {
    8761           40 :             assert_eq!(
    8762           40 :                 tline
    8763           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8764           40 :                     .await
    8765           40 :                     .unwrap(),
    8766           40 :                 &expected_result[idx]
    8767              :             );
    8768           40 :             assert_eq!(
    8769           40 :                 tline
    8770           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8771           40 :                     .await
    8772           40 :                     .unwrap(),
    8773           40 :                 &expected_result_at_gc_horizon[idx]
    8774              :             );
    8775              :         }
    8776              : 
    8777            4 :         let cancel = CancellationToken::new();
    8778            4 :         tline
    8779            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8780            4 :             .await
    8781            4 :             .unwrap();
    8782              : 
    8783           44 :         for idx in 0..10 {
    8784           40 :             assert_eq!(
    8785           40 :                 tline
    8786           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8787           40 :                     .await
    8788           40 :                     .unwrap(),
    8789           40 :                 &expected_result[idx]
    8790              :             );
    8791           40 :             assert_eq!(
    8792           40 :                 tline
    8793           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8794           40 :                     .await
    8795           40 :                     .unwrap(),
    8796           40 :                 &expected_result_at_gc_horizon[idx]
    8797              :             );
    8798              :         }
    8799              : 
    8800              :         // increase GC horizon and compact again
    8801              :         {
    8802            4 :             tline
    8803            4 :                 .latest_gc_cutoff_lsn
    8804            4 :                 .lock_for_write()
    8805            4 :                 .store_and_unlock(Lsn(0x40))
    8806            4 :                 .wait()
    8807            4 :                 .await;
    8808              :             // Update GC info
    8809            4 :             let mut guard = tline.gc_info.write().unwrap();
    8810            4 :             guard.cutoffs.time = Lsn(0x40);
    8811            4 :             guard.cutoffs.space = Lsn(0x40);
    8812            4 :         }
    8813            4 :         tline
    8814            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8815            4 :             .await
    8816            4 :             .unwrap();
    8817            4 : 
    8818            4 :         Ok(())
    8819            4 :     }
    8820              : 
    8821              :     #[cfg(feature = "testing")]
    8822              :     #[tokio::test]
    8823            2 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8824            2 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8825            2 :         let (tenant, ctx) = harness.load().await;
    8826            2 :         let tline = tenant
    8827            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8828            2 :             .await?;
    8829            2 :         tline.force_advance_lsn(Lsn(0x70));
    8830            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8831            2 :         let history = vec![
    8832            2 :             (
    8833            2 :                 key,
    8834            2 :                 Lsn(0x10),
    8835            2 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8836            2 :             ),
    8837            2 :             (
    8838            2 :                 key,
    8839            2 :                 Lsn(0x20),
    8840            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8841            2 :             ),
    8842            2 :             (
    8843            2 :                 key,
    8844            2 :                 Lsn(0x30),
    8845            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8846            2 :             ),
    8847            2 :             (
    8848            2 :                 key,
    8849            2 :                 Lsn(0x40),
    8850            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8851            2 :             ),
    8852            2 :             (
    8853            2 :                 key,
    8854            2 :                 Lsn(0x50),
    8855            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8856            2 :             ),
    8857            2 :             (
    8858            2 :                 key,
    8859            2 :                 Lsn(0x60),
    8860            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8861            2 :             ),
    8862            2 :             (
    8863            2 :                 key,
    8864            2 :                 Lsn(0x70),
    8865            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8866            2 :             ),
    8867            2 :             (
    8868            2 :                 key,
    8869            2 :                 Lsn(0x80),
    8870            2 :                 Value::Image(Bytes::copy_from_slice(
    8871            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8872            2 :                 )),
    8873            2 :             ),
    8874            2 :             (
    8875            2 :                 key,
    8876            2 :                 Lsn(0x90),
    8877            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8878            2 :             ),
    8879            2 :         ];
    8880            2 :         let res = tline
    8881            2 :             .generate_key_retention(
    8882            2 :                 key,
    8883            2 :                 &history,
    8884            2 :                 Lsn(0x60),
    8885            2 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8886            2 :                 3,
    8887            2 :                 None,
    8888            2 :             )
    8889            2 :             .await
    8890            2 :             .unwrap();
    8891            2 :         let expected_res = KeyHistoryRetention {
    8892            2 :             below_horizon: vec![
    8893            2 :                 (
    8894            2 :                     Lsn(0x20),
    8895            2 :                     KeyLogAtLsn(vec![(
    8896            2 :                         Lsn(0x20),
    8897            2 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8898            2 :                     )]),
    8899            2 :                 ),
    8900            2 :                 (
    8901            2 :                     Lsn(0x40),
    8902            2 :                     KeyLogAtLsn(vec![
    8903            2 :                         (
    8904            2 :                             Lsn(0x30),
    8905            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8906            2 :                         ),
    8907            2 :                         (
    8908            2 :                             Lsn(0x40),
    8909            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8910            2 :                         ),
    8911            2 :                     ]),
    8912            2 :                 ),
    8913            2 :                 (
    8914            2 :                     Lsn(0x50),
    8915            2 :                     KeyLogAtLsn(vec![(
    8916            2 :                         Lsn(0x50),
    8917            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    8918            2 :                     )]),
    8919            2 :                 ),
    8920            2 :                 (
    8921            2 :                     Lsn(0x60),
    8922            2 :                     KeyLogAtLsn(vec![(
    8923            2 :                         Lsn(0x60),
    8924            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8925            2 :                     )]),
    8926            2 :                 ),
    8927            2 :             ],
    8928            2 :             above_horizon: KeyLogAtLsn(vec![
    8929            2 :                 (
    8930            2 :                     Lsn(0x70),
    8931            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8932            2 :                 ),
    8933            2 :                 (
    8934            2 :                     Lsn(0x80),
    8935            2 :                     Value::Image(Bytes::copy_from_slice(
    8936            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8937            2 :                     )),
    8938            2 :                 ),
    8939            2 :                 (
    8940            2 :                     Lsn(0x90),
    8941            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8942            2 :                 ),
    8943            2 :             ]),
    8944            2 :         };
    8945            2 :         assert_eq!(res, expected_res);
    8946            2 : 
    8947            2 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    8948            2 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    8949            2 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    8950            2 :         // For example, we have
    8951            2 :         // ```plain
    8952            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    8953            2 :         // ```
    8954            2 :         // Now the GC horizon moves up, and we have
    8955            2 :         // ```plain
    8956            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    8957            2 :         // ```
    8958            2 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    8959            2 :         // We will end up with
    8960            2 :         // ```plain
    8961            2 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    8962            2 :         // ```
    8963            2 :         // Now we run the GC-compaction, and this key does not have a full history.
    8964            2 :         // We should be able to handle this partial history and drop everything before the
    8965            2 :         // gc_horizon image.
    8966            2 : 
    8967            2 :         let history = vec![
    8968            2 :             (
    8969            2 :                 key,
    8970            2 :                 Lsn(0x20),
    8971            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8972            2 :             ),
    8973            2 :             (
    8974            2 :                 key,
    8975            2 :                 Lsn(0x30),
    8976            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8977            2 :             ),
    8978            2 :             (
    8979            2 :                 key,
    8980            2 :                 Lsn(0x40),
    8981            2 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8982            2 :             ),
    8983            2 :             (
    8984            2 :                 key,
    8985            2 :                 Lsn(0x50),
    8986            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8987            2 :             ),
    8988            2 :             (
    8989            2 :                 key,
    8990            2 :                 Lsn(0x60),
    8991            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8992            2 :             ),
    8993            2 :             (
    8994            2 :                 key,
    8995            2 :                 Lsn(0x70),
    8996            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8997            2 :             ),
    8998            2 :             (
    8999            2 :                 key,
    9000            2 :                 Lsn(0x80),
    9001            2 :                 Value::Image(Bytes::copy_from_slice(
    9002            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9003            2 :                 )),
    9004            2 :             ),
    9005            2 :             (
    9006            2 :                 key,
    9007            2 :                 Lsn(0x90),
    9008            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9009            2 :             ),
    9010            2 :         ];
    9011            2 :         let res = tline
    9012            2 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9013            2 :             .await
    9014            2 :             .unwrap();
    9015            2 :         let expected_res = KeyHistoryRetention {
    9016            2 :             below_horizon: vec![
    9017            2 :                 (
    9018            2 :                     Lsn(0x40),
    9019            2 :                     KeyLogAtLsn(vec![(
    9020            2 :                         Lsn(0x40),
    9021            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9022            2 :                     )]),
    9023            2 :                 ),
    9024            2 :                 (
    9025            2 :                     Lsn(0x50),
    9026            2 :                     KeyLogAtLsn(vec![(
    9027            2 :                         Lsn(0x50),
    9028            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9029            2 :                     )]),
    9030            2 :                 ),
    9031            2 :                 (
    9032            2 :                     Lsn(0x60),
    9033            2 :                     KeyLogAtLsn(vec![(
    9034            2 :                         Lsn(0x60),
    9035            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9036            2 :                     )]),
    9037            2 :                 ),
    9038            2 :             ],
    9039            2 :             above_horizon: KeyLogAtLsn(vec![
    9040            2 :                 (
    9041            2 :                     Lsn(0x70),
    9042            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9043            2 :                 ),
    9044            2 :                 (
    9045            2 :                     Lsn(0x80),
    9046            2 :                     Value::Image(Bytes::copy_from_slice(
    9047            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9048            2 :                     )),
    9049            2 :                 ),
    9050            2 :                 (
    9051            2 :                     Lsn(0x90),
    9052            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9053            2 :                 ),
    9054            2 :             ]),
    9055            2 :         };
    9056            2 :         assert_eq!(res, expected_res);
    9057            2 : 
    9058            2 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9059            2 :         // the ancestor image in the test case.
    9060            2 : 
    9061            2 :         let history = vec![
    9062            2 :             (
    9063            2 :                 key,
    9064            2 :                 Lsn(0x20),
    9065            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9066            2 :             ),
    9067            2 :             (
    9068            2 :                 key,
    9069            2 :                 Lsn(0x30),
    9070            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9071            2 :             ),
    9072            2 :             (
    9073            2 :                 key,
    9074            2 :                 Lsn(0x40),
    9075            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9076            2 :             ),
    9077            2 :             (
    9078            2 :                 key,
    9079            2 :                 Lsn(0x70),
    9080            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9081            2 :             ),
    9082            2 :         ];
    9083            2 :         let res = tline
    9084            2 :             .generate_key_retention(
    9085            2 :                 key,
    9086            2 :                 &history,
    9087            2 :                 Lsn(0x60),
    9088            2 :                 &[],
    9089            2 :                 3,
    9090            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9091            2 :             )
    9092            2 :             .await
    9093            2 :             .unwrap();
    9094            2 :         let expected_res = KeyHistoryRetention {
    9095            2 :             below_horizon: vec![(
    9096            2 :                 Lsn(0x60),
    9097            2 :                 KeyLogAtLsn(vec![(
    9098            2 :                     Lsn(0x60),
    9099            2 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9100            2 :                 )]),
    9101            2 :             )],
    9102            2 :             above_horizon: KeyLogAtLsn(vec![(
    9103            2 :                 Lsn(0x70),
    9104            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9105            2 :             )]),
    9106            2 :         };
    9107            2 :         assert_eq!(res, expected_res);
    9108            2 : 
    9109            2 :         let history = vec![
    9110            2 :             (
    9111            2 :                 key,
    9112            2 :                 Lsn(0x20),
    9113            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9114            2 :             ),
    9115            2 :             (
    9116            2 :                 key,
    9117            2 :                 Lsn(0x40),
    9118            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9119            2 :             ),
    9120            2 :             (
    9121            2 :                 key,
    9122            2 :                 Lsn(0x60),
    9123            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9124            2 :             ),
    9125            2 :             (
    9126            2 :                 key,
    9127            2 :                 Lsn(0x70),
    9128            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9129            2 :             ),
    9130            2 :         ];
    9131            2 :         let res = tline
    9132            2 :             .generate_key_retention(
    9133            2 :                 key,
    9134            2 :                 &history,
    9135            2 :                 Lsn(0x60),
    9136            2 :                 &[Lsn(0x30)],
    9137            2 :                 3,
    9138            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9139            2 :             )
    9140            2 :             .await
    9141            2 :             .unwrap();
    9142            2 :         let expected_res = KeyHistoryRetention {
    9143            2 :             below_horizon: vec![
    9144            2 :                 (
    9145            2 :                     Lsn(0x30),
    9146            2 :                     KeyLogAtLsn(vec![(
    9147            2 :                         Lsn(0x20),
    9148            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9149            2 :                     )]),
    9150            2 :                 ),
    9151            2 :                 (
    9152            2 :                     Lsn(0x60),
    9153            2 :                     KeyLogAtLsn(vec![(
    9154            2 :                         Lsn(0x60),
    9155            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9156            2 :                     )]),
    9157            2 :                 ),
    9158            2 :             ],
    9159            2 :             above_horizon: KeyLogAtLsn(vec![(
    9160            2 :                 Lsn(0x70),
    9161            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9162            2 :             )]),
    9163            2 :         };
    9164            2 :         assert_eq!(res, expected_res);
    9165            2 : 
    9166            2 :         Ok(())
    9167            2 :     }
    9168              : 
    9169              :     #[cfg(feature = "testing")]
    9170              :     #[tokio::test]
    9171            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9172            2 :         let harness =
    9173            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9174            2 :         let (tenant, ctx) = harness.load().await;
    9175            2 : 
    9176          518 :         fn get_key(id: u32) -> Key {
    9177          518 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9178          518 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9179          518 :             key.field6 = id;
    9180          518 :             key
    9181          518 :         }
    9182            2 : 
    9183            2 :         let img_layer = (0..10)
    9184           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9185            2 :             .collect_vec();
    9186            2 : 
    9187            2 :         let delta1 = vec![
    9188            2 :             (
    9189            2 :                 get_key(1),
    9190            2 :                 Lsn(0x20),
    9191            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9192            2 :             ),
    9193            2 :             (
    9194            2 :                 get_key(2),
    9195            2 :                 Lsn(0x30),
    9196            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9197            2 :             ),
    9198            2 :             (
    9199            2 :                 get_key(3),
    9200            2 :                 Lsn(0x28),
    9201            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9202            2 :             ),
    9203            2 :             (
    9204            2 :                 get_key(3),
    9205            2 :                 Lsn(0x30),
    9206            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9207            2 :             ),
    9208            2 :             (
    9209            2 :                 get_key(3),
    9210            2 :                 Lsn(0x40),
    9211            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9212            2 :             ),
    9213            2 :         ];
    9214            2 :         let delta2 = vec![
    9215            2 :             (
    9216            2 :                 get_key(5),
    9217            2 :                 Lsn(0x20),
    9218            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9219            2 :             ),
    9220            2 :             (
    9221            2 :                 get_key(6),
    9222            2 :                 Lsn(0x20),
    9223            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9224            2 :             ),
    9225            2 :         ];
    9226            2 :         let delta3 = vec![
    9227            2 :             (
    9228            2 :                 get_key(8),
    9229            2 :                 Lsn(0x48),
    9230            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9231            2 :             ),
    9232            2 :             (
    9233            2 :                 get_key(9),
    9234            2 :                 Lsn(0x48),
    9235            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9236            2 :             ),
    9237            2 :         ];
    9238            2 : 
    9239            2 :         let tline = tenant
    9240            2 :             .create_test_timeline_with_layers(
    9241            2 :                 TIMELINE_ID,
    9242            2 :                 Lsn(0x10),
    9243            2 :                 DEFAULT_PG_VERSION,
    9244            2 :                 &ctx,
    9245            2 :                 vec![
    9246            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9247            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9248            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9249            2 :                 ], // delta layers
    9250            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9251            2 :                 Lsn(0x50),
    9252            2 :             )
    9253            2 :             .await?;
    9254            2 :         {
    9255            2 :             tline
    9256            2 :                 .latest_gc_cutoff_lsn
    9257            2 :                 .lock_for_write()
    9258            2 :                 .store_and_unlock(Lsn(0x30))
    9259            2 :                 .wait()
    9260            2 :                 .await;
    9261            2 :             // Update GC info
    9262            2 :             let mut guard = tline.gc_info.write().unwrap();
    9263            2 :             *guard = GcInfo {
    9264            2 :                 retain_lsns: vec![
    9265            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9266            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9267            2 :                 ],
    9268            2 :                 cutoffs: GcCutoffs {
    9269            2 :                     time: Lsn(0x30),
    9270            2 :                     space: Lsn(0x30),
    9271            2 :                 },
    9272            2 :                 leases: Default::default(),
    9273            2 :                 within_ancestor_pitr: false,
    9274            2 :             };
    9275            2 :         }
    9276            2 : 
    9277            2 :         let expected_result = [
    9278            2 :             Bytes::from_static(b"value 0@0x10"),
    9279            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9280            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9281            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9282            2 :             Bytes::from_static(b"value 4@0x10"),
    9283            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9284            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9285            2 :             Bytes::from_static(b"value 7@0x10"),
    9286            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9287            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9288            2 :         ];
    9289            2 : 
    9290            2 :         let expected_result_at_gc_horizon = [
    9291            2 :             Bytes::from_static(b"value 0@0x10"),
    9292            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9293            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9294            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9295            2 :             Bytes::from_static(b"value 4@0x10"),
    9296            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9297            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9298            2 :             Bytes::from_static(b"value 7@0x10"),
    9299            2 :             Bytes::from_static(b"value 8@0x10"),
    9300            2 :             Bytes::from_static(b"value 9@0x10"),
    9301            2 :         ];
    9302            2 : 
    9303            2 :         let expected_result_at_lsn_20 = [
    9304            2 :             Bytes::from_static(b"value 0@0x10"),
    9305            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9306            2 :             Bytes::from_static(b"value 2@0x10"),
    9307            2 :             Bytes::from_static(b"value 3@0x10"),
    9308            2 :             Bytes::from_static(b"value 4@0x10"),
    9309            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9310            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9311            2 :             Bytes::from_static(b"value 7@0x10"),
    9312            2 :             Bytes::from_static(b"value 8@0x10"),
    9313            2 :             Bytes::from_static(b"value 9@0x10"),
    9314            2 :         ];
    9315            2 : 
    9316            2 :         let expected_result_at_lsn_10 = [
    9317            2 :             Bytes::from_static(b"value 0@0x10"),
    9318            2 :             Bytes::from_static(b"value 1@0x10"),
    9319            2 :             Bytes::from_static(b"value 2@0x10"),
    9320            2 :             Bytes::from_static(b"value 3@0x10"),
    9321            2 :             Bytes::from_static(b"value 4@0x10"),
    9322            2 :             Bytes::from_static(b"value 5@0x10"),
    9323            2 :             Bytes::from_static(b"value 6@0x10"),
    9324            2 :             Bytes::from_static(b"value 7@0x10"),
    9325            2 :             Bytes::from_static(b"value 8@0x10"),
    9326            2 :             Bytes::from_static(b"value 9@0x10"),
    9327            2 :         ];
    9328            2 : 
    9329           12 :         let verify_result = || async {
    9330           12 :             let gc_horizon = {
    9331           12 :                 let gc_info = tline.gc_info.read().unwrap();
    9332           12 :                 gc_info.cutoffs.time
    9333            2 :             };
    9334          132 :             for idx in 0..10 {
    9335          120 :                 assert_eq!(
    9336          120 :                     tline
    9337          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9338          120 :                         .await
    9339          120 :                         .unwrap(),
    9340          120 :                     &expected_result[idx]
    9341            2 :                 );
    9342          120 :                 assert_eq!(
    9343          120 :                     tline
    9344          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9345          120 :                         .await
    9346          120 :                         .unwrap(),
    9347          120 :                     &expected_result_at_gc_horizon[idx]
    9348            2 :                 );
    9349          120 :                 assert_eq!(
    9350          120 :                     tline
    9351          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9352          120 :                         .await
    9353          120 :                         .unwrap(),
    9354          120 :                     &expected_result_at_lsn_20[idx]
    9355            2 :                 );
    9356          120 :                 assert_eq!(
    9357          120 :                     tline
    9358          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9359          120 :                         .await
    9360          120 :                         .unwrap(),
    9361          120 :                     &expected_result_at_lsn_10[idx]
    9362            2 :                 );
    9363            2 :             }
    9364           24 :         };
    9365            2 : 
    9366            2 :         verify_result().await;
    9367            2 : 
    9368            2 :         let cancel = CancellationToken::new();
    9369            2 :         let mut dryrun_flags = EnumSet::new();
    9370            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9371            2 : 
    9372            2 :         tline
    9373            2 :             .compact_with_gc(
    9374            2 :                 &cancel,
    9375            2 :                 CompactOptions {
    9376            2 :                     flags: dryrun_flags,
    9377            2 :                     ..Default::default()
    9378            2 :                 },
    9379            2 :                 &ctx,
    9380            2 :             )
    9381            2 :             .await
    9382            2 :             .unwrap();
    9383            2 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9384            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9385            2 :         verify_result().await;
    9386            2 : 
    9387            2 :         tline
    9388            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9389            2 :             .await
    9390            2 :             .unwrap();
    9391            2 :         verify_result().await;
    9392            2 : 
    9393            2 :         // compact again
    9394            2 :         tline
    9395            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9396            2 :             .await
    9397            2 :             .unwrap();
    9398            2 :         verify_result().await;
    9399            2 : 
    9400            2 :         // increase GC horizon and compact again
    9401            2 :         {
    9402            2 :             tline
    9403            2 :                 .latest_gc_cutoff_lsn
    9404            2 :                 .lock_for_write()
    9405            2 :                 .store_and_unlock(Lsn(0x38))
    9406            2 :                 .wait()
    9407            2 :                 .await;
    9408            2 :             // Update GC info
    9409            2 :             let mut guard = tline.gc_info.write().unwrap();
    9410            2 :             guard.cutoffs.time = Lsn(0x38);
    9411            2 :             guard.cutoffs.space = Lsn(0x38);
    9412            2 :         }
    9413            2 :         tline
    9414            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9415            2 :             .await
    9416            2 :             .unwrap();
    9417            2 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9418            2 : 
    9419            2 :         // not increasing the GC horizon and compact again
    9420            2 :         tline
    9421            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9422            2 :             .await
    9423            2 :             .unwrap();
    9424            2 :         verify_result().await;
    9425            2 : 
    9426            2 :         Ok(())
    9427            2 :     }
    9428              : 
    9429              :     #[cfg(feature = "testing")]
    9430              :     #[tokio::test]
    9431            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9432            2 :     {
    9433            2 :         let harness =
    9434            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9435            2 :                 .await?;
    9436            2 :         let (tenant, ctx) = harness.load().await;
    9437            2 : 
    9438          352 :         fn get_key(id: u32) -> Key {
    9439          352 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9440          352 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9441          352 :             key.field6 = id;
    9442          352 :             key
    9443          352 :         }
    9444            2 : 
    9445            2 :         let img_layer = (0..10)
    9446           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9447            2 :             .collect_vec();
    9448            2 : 
    9449            2 :         let delta1 = vec![
    9450            2 :             (
    9451            2 :                 get_key(1),
    9452            2 :                 Lsn(0x20),
    9453            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9454            2 :             ),
    9455            2 :             (
    9456            2 :                 get_key(1),
    9457            2 :                 Lsn(0x28),
    9458            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9459            2 :             ),
    9460            2 :         ];
    9461            2 :         let delta2 = vec![
    9462            2 :             (
    9463            2 :                 get_key(1),
    9464            2 :                 Lsn(0x30),
    9465            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9466            2 :             ),
    9467            2 :             (
    9468            2 :                 get_key(1),
    9469            2 :                 Lsn(0x38),
    9470            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9471            2 :             ),
    9472            2 :         ];
    9473            2 :         let delta3 = vec![
    9474            2 :             (
    9475            2 :                 get_key(8),
    9476            2 :                 Lsn(0x48),
    9477            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9478            2 :             ),
    9479            2 :             (
    9480            2 :                 get_key(9),
    9481            2 :                 Lsn(0x48),
    9482            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9483            2 :             ),
    9484            2 :         ];
    9485            2 : 
    9486            2 :         let tline = tenant
    9487            2 :             .create_test_timeline_with_layers(
    9488            2 :                 TIMELINE_ID,
    9489            2 :                 Lsn(0x10),
    9490            2 :                 DEFAULT_PG_VERSION,
    9491            2 :                 &ctx,
    9492            2 :                 vec![
    9493            2 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9494            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9495            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9496            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9497            2 :                 ], // delta layers
    9498            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9499            2 :                 Lsn(0x50),
    9500            2 :             )
    9501            2 :             .await?;
    9502            2 :         {
    9503            2 :             tline
    9504            2 :                 .latest_gc_cutoff_lsn
    9505            2 :                 .lock_for_write()
    9506            2 :                 .store_and_unlock(Lsn(0x30))
    9507            2 :                 .wait()
    9508            2 :                 .await;
    9509            2 :             // Update GC info
    9510            2 :             let mut guard = tline.gc_info.write().unwrap();
    9511            2 :             *guard = GcInfo {
    9512            2 :                 retain_lsns: vec![
    9513            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9514            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9515            2 :                 ],
    9516            2 :                 cutoffs: GcCutoffs {
    9517            2 :                     time: Lsn(0x30),
    9518            2 :                     space: Lsn(0x30),
    9519            2 :                 },
    9520            2 :                 leases: Default::default(),
    9521            2 :                 within_ancestor_pitr: false,
    9522            2 :             };
    9523            2 :         }
    9524            2 : 
    9525            2 :         let expected_result = [
    9526            2 :             Bytes::from_static(b"value 0@0x10"),
    9527            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9528            2 :             Bytes::from_static(b"value 2@0x10"),
    9529            2 :             Bytes::from_static(b"value 3@0x10"),
    9530            2 :             Bytes::from_static(b"value 4@0x10"),
    9531            2 :             Bytes::from_static(b"value 5@0x10"),
    9532            2 :             Bytes::from_static(b"value 6@0x10"),
    9533            2 :             Bytes::from_static(b"value 7@0x10"),
    9534            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9535            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9536            2 :         ];
    9537            2 : 
    9538            2 :         let expected_result_at_gc_horizon = [
    9539            2 :             Bytes::from_static(b"value 0@0x10"),
    9540            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9541            2 :             Bytes::from_static(b"value 2@0x10"),
    9542            2 :             Bytes::from_static(b"value 3@0x10"),
    9543            2 :             Bytes::from_static(b"value 4@0x10"),
    9544            2 :             Bytes::from_static(b"value 5@0x10"),
    9545            2 :             Bytes::from_static(b"value 6@0x10"),
    9546            2 :             Bytes::from_static(b"value 7@0x10"),
    9547            2 :             Bytes::from_static(b"value 8@0x10"),
    9548            2 :             Bytes::from_static(b"value 9@0x10"),
    9549            2 :         ];
    9550            2 : 
    9551            2 :         let expected_result_at_lsn_20 = [
    9552            2 :             Bytes::from_static(b"value 0@0x10"),
    9553            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9554            2 :             Bytes::from_static(b"value 2@0x10"),
    9555            2 :             Bytes::from_static(b"value 3@0x10"),
    9556            2 :             Bytes::from_static(b"value 4@0x10"),
    9557            2 :             Bytes::from_static(b"value 5@0x10"),
    9558            2 :             Bytes::from_static(b"value 6@0x10"),
    9559            2 :             Bytes::from_static(b"value 7@0x10"),
    9560            2 :             Bytes::from_static(b"value 8@0x10"),
    9561            2 :             Bytes::from_static(b"value 9@0x10"),
    9562            2 :         ];
    9563            2 : 
    9564            2 :         let expected_result_at_lsn_10 = [
    9565            2 :             Bytes::from_static(b"value 0@0x10"),
    9566            2 :             Bytes::from_static(b"value 1@0x10"),
    9567            2 :             Bytes::from_static(b"value 2@0x10"),
    9568            2 :             Bytes::from_static(b"value 3@0x10"),
    9569            2 :             Bytes::from_static(b"value 4@0x10"),
    9570            2 :             Bytes::from_static(b"value 5@0x10"),
    9571            2 :             Bytes::from_static(b"value 6@0x10"),
    9572            2 :             Bytes::from_static(b"value 7@0x10"),
    9573            2 :             Bytes::from_static(b"value 8@0x10"),
    9574            2 :             Bytes::from_static(b"value 9@0x10"),
    9575            2 :         ];
    9576            2 : 
    9577            8 :         let verify_result = || async {
    9578            8 :             let gc_horizon = {
    9579            8 :                 let gc_info = tline.gc_info.read().unwrap();
    9580            8 :                 gc_info.cutoffs.time
    9581            2 :             };
    9582           88 :             for idx in 0..10 {
    9583           80 :                 assert_eq!(
    9584           80 :                     tline
    9585           80 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9586           80 :                         .await
    9587           80 :                         .unwrap(),
    9588           80 :                     &expected_result[idx]
    9589            2 :                 );
    9590           80 :                 assert_eq!(
    9591           80 :                     tline
    9592           80 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9593           80 :                         .await
    9594           80 :                         .unwrap(),
    9595           80 :                     &expected_result_at_gc_horizon[idx]
    9596            2 :                 );
    9597           80 :                 assert_eq!(
    9598           80 :                     tline
    9599           80 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9600           80 :                         .await
    9601           80 :                         .unwrap(),
    9602           80 :                     &expected_result_at_lsn_20[idx]
    9603            2 :                 );
    9604           80 :                 assert_eq!(
    9605           80 :                     tline
    9606           80 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9607           80 :                         .await
    9608           80 :                         .unwrap(),
    9609           80 :                     &expected_result_at_lsn_10[idx]
    9610            2 :                 );
    9611            2 :             }
    9612           16 :         };
    9613            2 : 
    9614            2 :         verify_result().await;
    9615            2 : 
    9616            2 :         let cancel = CancellationToken::new();
    9617            2 :         let mut dryrun_flags = EnumSet::new();
    9618            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9619            2 : 
    9620            2 :         tline
    9621            2 :             .compact_with_gc(
    9622            2 :                 &cancel,
    9623            2 :                 CompactOptions {
    9624            2 :                     flags: dryrun_flags,
    9625            2 :                     ..Default::default()
    9626            2 :                 },
    9627            2 :                 &ctx,
    9628            2 :             )
    9629            2 :             .await
    9630            2 :             .unwrap();
    9631            2 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9632            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9633            2 :         verify_result().await;
    9634            2 : 
    9635            2 :         tline
    9636            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9637            2 :             .await
    9638            2 :             .unwrap();
    9639            2 :         verify_result().await;
    9640            2 : 
    9641            2 :         // compact again
    9642            2 :         tline
    9643            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9644            2 :             .await
    9645            2 :             .unwrap();
    9646            2 :         verify_result().await;
    9647            2 : 
    9648            2 :         Ok(())
    9649            2 :     }
    9650              : 
    9651              :     #[cfg(feature = "testing")]
    9652              :     #[tokio::test]
    9653            2 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9654            2 :         use models::CompactLsnRange;
    9655            2 : 
    9656            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9657            2 :         let (tenant, ctx) = harness.load().await;
    9658            2 : 
    9659          166 :         fn get_key(id: u32) -> Key {
    9660          166 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9661          166 :             key.field6 = id;
    9662          166 :             key
    9663          166 :         }
    9664            2 : 
    9665            2 :         let img_layer = (0..10)
    9666           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9667            2 :             .collect_vec();
    9668            2 : 
    9669            2 :         let delta1 = vec![
    9670            2 :             (
    9671            2 :                 get_key(1),
    9672            2 :                 Lsn(0x20),
    9673            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9674            2 :             ),
    9675            2 :             (
    9676            2 :                 get_key(2),
    9677            2 :                 Lsn(0x30),
    9678            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9679            2 :             ),
    9680            2 :             (
    9681            2 :                 get_key(3),
    9682            2 :                 Lsn(0x28),
    9683            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9684            2 :             ),
    9685            2 :             (
    9686            2 :                 get_key(3),
    9687            2 :                 Lsn(0x30),
    9688            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9689            2 :             ),
    9690            2 :             (
    9691            2 :                 get_key(3),
    9692            2 :                 Lsn(0x40),
    9693            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9694            2 :             ),
    9695            2 :         ];
    9696            2 :         let delta2 = vec![
    9697            2 :             (
    9698            2 :                 get_key(5),
    9699            2 :                 Lsn(0x20),
    9700            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9701            2 :             ),
    9702            2 :             (
    9703            2 :                 get_key(6),
    9704            2 :                 Lsn(0x20),
    9705            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9706            2 :             ),
    9707            2 :         ];
    9708            2 :         let delta3 = vec![
    9709            2 :             (
    9710            2 :                 get_key(8),
    9711            2 :                 Lsn(0x48),
    9712            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9713            2 :             ),
    9714            2 :             (
    9715            2 :                 get_key(9),
    9716            2 :                 Lsn(0x48),
    9717            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9718            2 :             ),
    9719            2 :         ];
    9720            2 : 
    9721            2 :         let parent_tline = tenant
    9722            2 :             .create_test_timeline_with_layers(
    9723            2 :                 TIMELINE_ID,
    9724            2 :                 Lsn(0x10),
    9725            2 :                 DEFAULT_PG_VERSION,
    9726            2 :                 &ctx,
    9727            2 :                 vec![],                       // delta layers
    9728            2 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9729            2 :                 Lsn(0x18),
    9730            2 :             )
    9731            2 :             .await?;
    9732            2 : 
    9733            2 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9734            2 : 
    9735            2 :         let branch_tline = tenant
    9736            2 :             .branch_timeline_test_with_layers(
    9737            2 :                 &parent_tline,
    9738            2 :                 NEW_TIMELINE_ID,
    9739            2 :                 Some(Lsn(0x18)),
    9740            2 :                 &ctx,
    9741            2 :                 vec![
    9742            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9743            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9744            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9745            2 :                 ], // delta layers
    9746            2 :                 vec![], // image layers
    9747            2 :                 Lsn(0x50),
    9748            2 :             )
    9749            2 :             .await?;
    9750            2 : 
    9751            2 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9752            2 : 
    9753            2 :         {
    9754            2 :             parent_tline
    9755            2 :                 .latest_gc_cutoff_lsn
    9756            2 :                 .lock_for_write()
    9757            2 :                 .store_and_unlock(Lsn(0x10))
    9758            2 :                 .wait()
    9759            2 :                 .await;
    9760            2 :             // Update GC info
    9761            2 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9762            2 :             *guard = GcInfo {
    9763            2 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9764            2 :                 cutoffs: GcCutoffs {
    9765            2 :                     time: Lsn(0x10),
    9766            2 :                     space: Lsn(0x10),
    9767            2 :                 },
    9768            2 :                 leases: Default::default(),
    9769            2 :                 within_ancestor_pitr: false,
    9770            2 :             };
    9771            2 :         }
    9772            2 : 
    9773            2 :         {
    9774            2 :             branch_tline
    9775            2 :                 .latest_gc_cutoff_lsn
    9776            2 :                 .lock_for_write()
    9777            2 :                 .store_and_unlock(Lsn(0x50))
    9778            2 :                 .wait()
    9779            2 :                 .await;
    9780            2 :             // Update GC info
    9781            2 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9782            2 :             *guard = GcInfo {
    9783            2 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9784            2 :                 cutoffs: GcCutoffs {
    9785            2 :                     time: Lsn(0x50),
    9786            2 :                     space: Lsn(0x50),
    9787            2 :                 },
    9788            2 :                 leases: Default::default(),
    9789            2 :                 within_ancestor_pitr: false,
    9790            2 :             };
    9791            2 :         }
    9792            2 : 
    9793            2 :         let expected_result_at_gc_horizon = [
    9794            2 :             Bytes::from_static(b"value 0@0x10"),
    9795            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9796            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9797            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9798            2 :             Bytes::from_static(b"value 4@0x10"),
    9799            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9800            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9801            2 :             Bytes::from_static(b"value 7@0x10"),
    9802            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9803            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9804            2 :         ];
    9805            2 : 
    9806            2 :         let expected_result_at_lsn_40 = [
    9807            2 :             Bytes::from_static(b"value 0@0x10"),
    9808            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9809            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9810            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9811            2 :             Bytes::from_static(b"value 4@0x10"),
    9812            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9813            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9814            2 :             Bytes::from_static(b"value 7@0x10"),
    9815            2 :             Bytes::from_static(b"value 8@0x10"),
    9816            2 :             Bytes::from_static(b"value 9@0x10"),
    9817            2 :         ];
    9818            2 : 
    9819            6 :         let verify_result = || async {
    9820           66 :             for idx in 0..10 {
    9821           60 :                 assert_eq!(
    9822           60 :                     branch_tline
    9823           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9824           60 :                         .await
    9825           60 :                         .unwrap(),
    9826           60 :                     &expected_result_at_gc_horizon[idx]
    9827            2 :                 );
    9828           60 :                 assert_eq!(
    9829           60 :                     branch_tline
    9830           60 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9831           60 :                         .await
    9832           60 :                         .unwrap(),
    9833           60 :                     &expected_result_at_lsn_40[idx]
    9834            2 :                 );
    9835            2 :             }
    9836           12 :         };
    9837            2 : 
    9838            2 :         verify_result().await;
    9839            2 : 
    9840            2 :         let cancel = CancellationToken::new();
    9841            2 :         branch_tline
    9842            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9843            2 :             .await
    9844            2 :             .unwrap();
    9845            2 : 
    9846            2 :         verify_result().await;
    9847            2 : 
    9848            2 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
    9849            2 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
    9850            2 :         branch_tline
    9851            2 :             .compact_with_gc(
    9852            2 :                 &cancel,
    9853            2 :                 CompactOptions {
    9854            2 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
    9855            2 :                     ..Default::default()
    9856            2 :                 },
    9857            2 :                 &ctx,
    9858            2 :             )
    9859            2 :             .await
    9860            2 :             .unwrap();
    9861            2 : 
    9862            2 :         verify_result().await;
    9863            2 : 
    9864            2 :         Ok(())
    9865            2 :     }
    9866              : 
    9867              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9868              :     // Create an image arrangement where we have to read at different LSN ranges
    9869              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9870              :     // a delta layer. Like so:
    9871              :     //
    9872              :     //     A      B
    9873              :     // +----------------+ -> delta_layer
    9874              :     // |                |                           ^ lsn
    9875              :     // |       =========|-> nested_image_layer      |
    9876              :     // |       C        |                           |
    9877              :     // +----------------+                           |
    9878              :     // ======== -> baseline_image_layer             +-------> key
    9879              :     //
    9880              :     //
    9881              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9882              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9883              :     #[cfg(feature = "testing")]
    9884              :     #[tokio::test]
    9885            2 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9886            2 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9887            2 :         let (tenant, ctx) = harness.load().await;
    9888            2 : 
    9889            2 :         let will_init_keys = [2, 6];
    9890           44 :         fn get_key(id: u32) -> Key {
    9891           44 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9892           44 :             key.field6 = id;
    9893           44 :             key
    9894           44 :         }
    9895            2 : 
    9896            2 :         let mut expected_key_values = HashMap::new();
    9897            2 : 
    9898            2 :         let baseline_image_layer_lsn = Lsn(0x10);
    9899            2 :         let mut baseline_img_layer = Vec::new();
    9900           12 :         for i in 0..5 {
    9901           10 :             let key = get_key(i);
    9902           10 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
    9903           10 : 
    9904           10 :             let removed = expected_key_values.insert(key, value.clone());
    9905           10 :             assert!(removed.is_none());
    9906            2 : 
    9907           10 :             baseline_img_layer.push((key, Bytes::from(value)));
    9908            2 :         }
    9909            2 : 
    9910            2 :         let nested_image_layer_lsn = Lsn(0x50);
    9911            2 :         let mut nested_img_layer = Vec::new();
    9912           12 :         for i in 5..10 {
    9913           10 :             let key = get_key(i);
    9914           10 :             let value = format!("value {i}@{nested_image_layer_lsn}");
    9915           10 : 
    9916           10 :             let removed = expected_key_values.insert(key, value.clone());
    9917           10 :             assert!(removed.is_none());
    9918            2 : 
    9919           10 :             nested_img_layer.push((key, Bytes::from(value)));
    9920            2 :         }
    9921            2 : 
    9922            2 :         let mut delta_layer_spec = Vec::default();
    9923            2 :         let delta_layer_start_lsn = Lsn(0x20);
    9924            2 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
    9925            2 : 
    9926           22 :         for i in 0..10 {
    9927           20 :             let key = get_key(i);
    9928           20 :             let key_in_nested = nested_img_layer
    9929           20 :                 .iter()
    9930           80 :                 .any(|(key_with_img, _)| *key_with_img == key);
    9931           20 :             let lsn = {
    9932           20 :                 if key_in_nested {
    9933           10 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
    9934            2 :                 } else {
    9935           10 :                     delta_layer_start_lsn
    9936            2 :                 }
    9937            2 :             };
    9938            2 : 
    9939           20 :             let will_init = will_init_keys.contains(&i);
    9940           20 :             if will_init {
    9941            4 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
    9942            4 : 
    9943            4 :                 expected_key_values.insert(key, "".to_string());
    9944           16 :             } else {
    9945           16 :                 let delta = format!("@{lsn}");
    9946           16 :                 delta_layer_spec.push((
    9947           16 :                     key,
    9948           16 :                     lsn,
    9949           16 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
    9950           16 :                 ));
    9951           16 : 
    9952           16 :                 expected_key_values
    9953           16 :                     .get_mut(&key)
    9954           16 :                     .expect("An image exists for each key")
    9955           16 :                     .push_str(delta.as_str());
    9956           16 :             }
    9957           20 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
    9958            2 :         }
    9959            2 : 
    9960            2 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
    9961            2 : 
    9962            2 :         assert!(
    9963            2 :             nested_image_layer_lsn > delta_layer_start_lsn
    9964            2 :                 && nested_image_layer_lsn < delta_layer_end_lsn
    9965            2 :         );
    9966            2 : 
    9967            2 :         let tline = tenant
    9968            2 :             .create_test_timeline_with_layers(
    9969            2 :                 TIMELINE_ID,
    9970            2 :                 baseline_image_layer_lsn,
    9971            2 :                 DEFAULT_PG_VERSION,
    9972            2 :                 &ctx,
    9973            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9974            2 :                     delta_layer_start_lsn..delta_layer_end_lsn,
    9975            2 :                     delta_layer_spec,
    9976            2 :                 )], // delta layers
    9977            2 :                 vec![
    9978            2 :                     (baseline_image_layer_lsn, baseline_img_layer),
    9979            2 :                     (nested_image_layer_lsn, nested_img_layer),
    9980            2 :                 ], // image layers
    9981            2 :                 delta_layer_end_lsn,
    9982            2 :             )
    9983            2 :             .await?;
    9984            2 : 
    9985            2 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
    9986            2 :         let results = tline
    9987            2 :             .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
    9988            2 :             .await
    9989            2 :             .expect("No vectored errors");
    9990           22 :         for (key, res) in results {
    9991           20 :             let value = res.expect("No key errors");
    9992           20 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
    9993           20 :             assert_eq!(value, Bytes::from(expected_value));
    9994            2 :         }
    9995            2 : 
    9996            2 :         Ok(())
    9997            2 :     }
    9998              : 
    9999          214 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10000          214 :         (
   10001          214 :             k1.is_delta,
   10002          214 :             k1.key_range.start,
   10003          214 :             k1.key_range.end,
   10004          214 :             k1.lsn_range.start,
   10005          214 :             k1.lsn_range.end,
   10006          214 :         )
   10007          214 :             .cmp(&(
   10008          214 :                 k2.is_delta,
   10009          214 :                 k2.key_range.start,
   10010          214 :                 k2.key_range.end,
   10011          214 :                 k2.lsn_range.start,
   10012          214 :                 k2.lsn_range.end,
   10013          214 :             ))
   10014          214 :     }
   10015              : 
   10016           24 :     async fn inspect_and_sort(
   10017           24 :         tline: &Arc<Timeline>,
   10018           24 :         filter: Option<std::ops::Range<Key>>,
   10019           24 :     ) -> Vec<PersistentLayerKey> {
   10020           24 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10021           24 :         if let Some(filter) = filter {
   10022          108 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10023           22 :         }
   10024           24 :         all_layers.sort_by(sort_layer_key);
   10025           24 :         all_layers
   10026           24 :     }
   10027              : 
   10028              :     #[cfg(feature = "testing")]
   10029           22 :     fn check_layer_map_key_eq(
   10030           22 :         mut left: Vec<PersistentLayerKey>,
   10031           22 :         mut right: Vec<PersistentLayerKey>,
   10032           22 :     ) {
   10033           22 :         left.sort_by(sort_layer_key);
   10034           22 :         right.sort_by(sort_layer_key);
   10035           22 :         if left != right {
   10036            0 :             eprintln!("---LEFT---");
   10037            0 :             for left in left.iter() {
   10038            0 :                 eprintln!("{}", left);
   10039            0 :             }
   10040            0 :             eprintln!("---RIGHT---");
   10041            0 :             for right in right.iter() {
   10042            0 :                 eprintln!("{}", right);
   10043            0 :             }
   10044            0 :             assert_eq!(left, right);
   10045           22 :         }
   10046           22 :     }
   10047              : 
   10048              :     #[cfg(feature = "testing")]
   10049              :     #[tokio::test]
   10050            2 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10051            2 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10052            2 :         let (tenant, ctx) = harness.load().await;
   10053            2 : 
   10054          182 :         fn get_key(id: u32) -> Key {
   10055          182 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10056          182 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10057          182 :             key.field6 = id;
   10058          182 :             key
   10059          182 :         }
   10060            2 : 
   10061            2 :         // img layer at 0x10
   10062            2 :         let img_layer = (0..10)
   10063           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10064            2 :             .collect_vec();
   10065            2 : 
   10066            2 :         let delta1 = vec![
   10067            2 :             (
   10068            2 :                 get_key(1),
   10069            2 :                 Lsn(0x20),
   10070            2 :                 Value::Image(Bytes::from("value 1@0x20")),
   10071            2 :             ),
   10072            2 :             (
   10073            2 :                 get_key(2),
   10074            2 :                 Lsn(0x30),
   10075            2 :                 Value::Image(Bytes::from("value 2@0x30")),
   10076            2 :             ),
   10077            2 :             (
   10078            2 :                 get_key(3),
   10079            2 :                 Lsn(0x40),
   10080            2 :                 Value::Image(Bytes::from("value 3@0x40")),
   10081            2 :             ),
   10082            2 :         ];
   10083            2 :         let delta2 = vec![
   10084            2 :             (
   10085            2 :                 get_key(5),
   10086            2 :                 Lsn(0x20),
   10087            2 :                 Value::Image(Bytes::from("value 5@0x20")),
   10088            2 :             ),
   10089            2 :             (
   10090            2 :                 get_key(6),
   10091            2 :                 Lsn(0x20),
   10092            2 :                 Value::Image(Bytes::from("value 6@0x20")),
   10093            2 :             ),
   10094            2 :         ];
   10095            2 :         let delta3 = vec![
   10096            2 :             (
   10097            2 :                 get_key(8),
   10098            2 :                 Lsn(0x48),
   10099            2 :                 Value::Image(Bytes::from("value 8@0x48")),
   10100            2 :             ),
   10101            2 :             (
   10102            2 :                 get_key(9),
   10103            2 :                 Lsn(0x48),
   10104            2 :                 Value::Image(Bytes::from("value 9@0x48")),
   10105            2 :             ),
   10106            2 :         ];
   10107            2 : 
   10108            2 :         let tline = tenant
   10109            2 :             .create_test_timeline_with_layers(
   10110            2 :                 TIMELINE_ID,
   10111            2 :                 Lsn(0x10),
   10112            2 :                 DEFAULT_PG_VERSION,
   10113            2 :                 &ctx,
   10114            2 :                 vec![
   10115            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10116            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10117            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10118            2 :                 ], // delta layers
   10119            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10120            2 :                 Lsn(0x50),
   10121            2 :             )
   10122            2 :             .await?;
   10123            2 : 
   10124            2 :         {
   10125            2 :             tline
   10126            2 :                 .latest_gc_cutoff_lsn
   10127            2 :                 .lock_for_write()
   10128            2 :                 .store_and_unlock(Lsn(0x30))
   10129            2 :                 .wait()
   10130            2 :                 .await;
   10131            2 :             // Update GC info
   10132            2 :             let mut guard = tline.gc_info.write().unwrap();
   10133            2 :             *guard = GcInfo {
   10134            2 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10135            2 :                 cutoffs: GcCutoffs {
   10136            2 :                     time: Lsn(0x30),
   10137            2 :                     space: Lsn(0x30),
   10138            2 :                 },
   10139            2 :                 leases: Default::default(),
   10140            2 :                 within_ancestor_pitr: false,
   10141            2 :             };
   10142            2 :         }
   10143            2 : 
   10144            2 :         let cancel = CancellationToken::new();
   10145            2 : 
   10146            2 :         // Do a partial compaction on key range 0..2
   10147            2 :         tline
   10148            2 :             .compact_with_gc(
   10149            2 :                 &cancel,
   10150            2 :                 CompactOptions {
   10151            2 :                     flags: EnumSet::new(),
   10152            2 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10153            2 :                     ..Default::default()
   10154            2 :                 },
   10155            2 :                 &ctx,
   10156            2 :             )
   10157            2 :             .await
   10158            2 :             .unwrap();
   10159            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10160            2 :         check_layer_map_key_eq(
   10161            2 :             all_layers,
   10162            2 :             vec![
   10163            2 :                 // newly-generated image layer for the partial compaction range 0-2
   10164            2 :                 PersistentLayerKey {
   10165            2 :                     key_range: get_key(0)..get_key(2),
   10166            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10167            2 :                     is_delta: false,
   10168            2 :                 },
   10169            2 :                 PersistentLayerKey {
   10170            2 :                     key_range: get_key(0)..get_key(10),
   10171            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10172            2 :                     is_delta: false,
   10173            2 :                 },
   10174            2 :                 // delta1 is split and the second part is rewritten
   10175            2 :                 PersistentLayerKey {
   10176            2 :                     key_range: get_key(2)..get_key(4),
   10177            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10178            2 :                     is_delta: true,
   10179            2 :                 },
   10180            2 :                 PersistentLayerKey {
   10181            2 :                     key_range: get_key(5)..get_key(7),
   10182            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10183            2 :                     is_delta: true,
   10184            2 :                 },
   10185            2 :                 PersistentLayerKey {
   10186            2 :                     key_range: get_key(8)..get_key(10),
   10187            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10188            2 :                     is_delta: true,
   10189            2 :                 },
   10190            2 :             ],
   10191            2 :         );
   10192            2 : 
   10193            2 :         // Do a partial compaction on key range 2..4
   10194            2 :         tline
   10195            2 :             .compact_with_gc(
   10196            2 :                 &cancel,
   10197            2 :                 CompactOptions {
   10198            2 :                     flags: EnumSet::new(),
   10199            2 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10200            2 :                     ..Default::default()
   10201            2 :                 },
   10202            2 :                 &ctx,
   10203            2 :             )
   10204            2 :             .await
   10205            2 :             .unwrap();
   10206            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10207            2 :         check_layer_map_key_eq(
   10208            2 :             all_layers,
   10209            2 :             vec![
   10210            2 :                 PersistentLayerKey {
   10211            2 :                     key_range: get_key(0)..get_key(2),
   10212            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10213            2 :                     is_delta: false,
   10214            2 :                 },
   10215            2 :                 PersistentLayerKey {
   10216            2 :                     key_range: get_key(0)..get_key(10),
   10217            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10218            2 :                     is_delta: false,
   10219            2 :                 },
   10220            2 :                 // image layer generated for the compaction range 2-4
   10221            2 :                 PersistentLayerKey {
   10222            2 :                     key_range: get_key(2)..get_key(4),
   10223            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10224            2 :                     is_delta: false,
   10225            2 :                 },
   10226            2 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10227            2 :                 PersistentLayerKey {
   10228            2 :                     key_range: get_key(2)..get_key(4),
   10229            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10230            2 :                     is_delta: true,
   10231            2 :                 },
   10232            2 :                 PersistentLayerKey {
   10233            2 :                     key_range: get_key(5)..get_key(7),
   10234            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10235            2 :                     is_delta: true,
   10236            2 :                 },
   10237            2 :                 PersistentLayerKey {
   10238            2 :                     key_range: get_key(8)..get_key(10),
   10239            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10240            2 :                     is_delta: true,
   10241            2 :                 },
   10242            2 :             ],
   10243            2 :         );
   10244            2 : 
   10245            2 :         // Do a partial compaction on key range 4..9
   10246            2 :         tline
   10247            2 :             .compact_with_gc(
   10248            2 :                 &cancel,
   10249            2 :                 CompactOptions {
   10250            2 :                     flags: EnumSet::new(),
   10251            2 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10252            2 :                     ..Default::default()
   10253            2 :                 },
   10254            2 :                 &ctx,
   10255            2 :             )
   10256            2 :             .await
   10257            2 :             .unwrap();
   10258            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10259            2 :         check_layer_map_key_eq(
   10260            2 :             all_layers,
   10261            2 :             vec![
   10262            2 :                 PersistentLayerKey {
   10263            2 :                     key_range: get_key(0)..get_key(2),
   10264            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10265            2 :                     is_delta: false,
   10266            2 :                 },
   10267            2 :                 PersistentLayerKey {
   10268            2 :                     key_range: get_key(0)..get_key(10),
   10269            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10270            2 :                     is_delta: false,
   10271            2 :                 },
   10272            2 :                 PersistentLayerKey {
   10273            2 :                     key_range: get_key(2)..get_key(4),
   10274            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10275            2 :                     is_delta: false,
   10276            2 :                 },
   10277            2 :                 PersistentLayerKey {
   10278            2 :                     key_range: get_key(2)..get_key(4),
   10279            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10280            2 :                     is_delta: true,
   10281            2 :                 },
   10282            2 :                 // image layer generated for this compaction range
   10283            2 :                 PersistentLayerKey {
   10284            2 :                     key_range: get_key(4)..get_key(9),
   10285            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10286            2 :                     is_delta: false,
   10287            2 :                 },
   10288            2 :                 PersistentLayerKey {
   10289            2 :                     key_range: get_key(8)..get_key(10),
   10290            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10291            2 :                     is_delta: true,
   10292            2 :                 },
   10293            2 :             ],
   10294            2 :         );
   10295            2 : 
   10296            2 :         // Do a partial compaction on key range 9..10
   10297            2 :         tline
   10298            2 :             .compact_with_gc(
   10299            2 :                 &cancel,
   10300            2 :                 CompactOptions {
   10301            2 :                     flags: EnumSet::new(),
   10302            2 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10303            2 :                     ..Default::default()
   10304            2 :                 },
   10305            2 :                 &ctx,
   10306            2 :             )
   10307            2 :             .await
   10308            2 :             .unwrap();
   10309            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10310            2 :         check_layer_map_key_eq(
   10311            2 :             all_layers,
   10312            2 :             vec![
   10313            2 :                 PersistentLayerKey {
   10314            2 :                     key_range: get_key(0)..get_key(2),
   10315            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10316            2 :                     is_delta: false,
   10317            2 :                 },
   10318            2 :                 PersistentLayerKey {
   10319            2 :                     key_range: get_key(0)..get_key(10),
   10320            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10321            2 :                     is_delta: false,
   10322            2 :                 },
   10323            2 :                 PersistentLayerKey {
   10324            2 :                     key_range: get_key(2)..get_key(4),
   10325            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10326            2 :                     is_delta: false,
   10327            2 :                 },
   10328            2 :                 PersistentLayerKey {
   10329            2 :                     key_range: get_key(2)..get_key(4),
   10330            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10331            2 :                     is_delta: true,
   10332            2 :                 },
   10333            2 :                 PersistentLayerKey {
   10334            2 :                     key_range: get_key(4)..get_key(9),
   10335            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10336            2 :                     is_delta: false,
   10337            2 :                 },
   10338            2 :                 // image layer generated for the compaction range
   10339            2 :                 PersistentLayerKey {
   10340            2 :                     key_range: get_key(9)..get_key(10),
   10341            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10342            2 :                     is_delta: false,
   10343            2 :                 },
   10344            2 :                 PersistentLayerKey {
   10345            2 :                     key_range: get_key(8)..get_key(10),
   10346            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10347            2 :                     is_delta: true,
   10348            2 :                 },
   10349            2 :             ],
   10350            2 :         );
   10351            2 : 
   10352            2 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10353            2 :         tline
   10354            2 :             .compact_with_gc(
   10355            2 :                 &cancel,
   10356            2 :                 CompactOptions {
   10357            2 :                     flags: EnumSet::new(),
   10358            2 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10359            2 :                     ..Default::default()
   10360            2 :                 },
   10361            2 :                 &ctx,
   10362            2 :             )
   10363            2 :             .await
   10364            2 :             .unwrap();
   10365            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10366            2 :         check_layer_map_key_eq(
   10367            2 :             all_layers,
   10368            2 :             vec![
   10369            2 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10370            2 :                 PersistentLayerKey {
   10371            2 :                     key_range: get_key(0)..get_key(10),
   10372            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10373            2 :                     is_delta: false,
   10374            2 :                 },
   10375            2 :                 PersistentLayerKey {
   10376            2 :                     key_range: get_key(2)..get_key(4),
   10377            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10378            2 :                     is_delta: true,
   10379            2 :                 },
   10380            2 :                 PersistentLayerKey {
   10381            2 :                     key_range: get_key(8)..get_key(10),
   10382            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10383            2 :                     is_delta: true,
   10384            2 :                 },
   10385            2 :             ],
   10386            2 :         );
   10387            2 :         Ok(())
   10388            2 :     }
   10389              : 
   10390              :     #[cfg(feature = "testing")]
   10391              :     #[tokio::test]
   10392            2 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10393            2 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10394            2 :             .await
   10395            2 :             .unwrap();
   10396            2 :         let (tenant, ctx) = harness.load().await;
   10397            2 :         let tline_parent = tenant
   10398            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10399            2 :             .await
   10400            2 :             .unwrap();
   10401            2 :         let tline_child = tenant
   10402            2 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10403            2 :             .await
   10404            2 :             .unwrap();
   10405            2 :         {
   10406            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10407            2 :             assert_eq!(
   10408            2 :                 gc_info_parent.retain_lsns,
   10409            2 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10410            2 :             );
   10411            2 :         }
   10412            2 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10413            2 :         tline_child
   10414            2 :             .remote_client
   10415            2 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10416            2 :             .unwrap();
   10417            2 :         tline_child.remote_client.wait_completion().await.unwrap();
   10418            2 :         offload_timeline(&tenant, &tline_child)
   10419            2 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10420            2 :             .await.unwrap();
   10421            2 :         let child_timeline_id = tline_child.timeline_id;
   10422            2 :         Arc::try_unwrap(tline_child).unwrap();
   10423            2 : 
   10424            2 :         {
   10425            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10426            2 :             assert_eq!(
   10427            2 :                 gc_info_parent.retain_lsns,
   10428            2 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10429            2 :             );
   10430            2 :         }
   10431            2 : 
   10432            2 :         tenant
   10433            2 :             .get_offloaded_timeline(child_timeline_id)
   10434            2 :             .unwrap()
   10435            2 :             .defuse_for_tenant_drop();
   10436            2 : 
   10437            2 :         Ok(())
   10438            2 :     }
   10439              : 
   10440              :     #[cfg(feature = "testing")]
   10441              :     #[tokio::test]
   10442            2 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10443            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10444            2 :         let (tenant, ctx) = harness.load().await;
   10445            2 : 
   10446          296 :         fn get_key(id: u32) -> Key {
   10447          296 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10448          296 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10449          296 :             key.field6 = id;
   10450          296 :             key
   10451          296 :         }
   10452            2 : 
   10453            2 :         let img_layer = (0..10)
   10454           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10455            2 :             .collect_vec();
   10456            2 : 
   10457            2 :         let delta1 = vec![(
   10458            2 :             get_key(1),
   10459            2 :             Lsn(0x20),
   10460            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10461            2 :         )];
   10462            2 :         let delta4 = vec![(
   10463            2 :             get_key(1),
   10464            2 :             Lsn(0x28),
   10465            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10466            2 :         )];
   10467            2 :         let delta2 = vec![
   10468            2 :             (
   10469            2 :                 get_key(1),
   10470            2 :                 Lsn(0x30),
   10471            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10472            2 :             ),
   10473            2 :             (
   10474            2 :                 get_key(1),
   10475            2 :                 Lsn(0x38),
   10476            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10477            2 :             ),
   10478            2 :         ];
   10479            2 :         let delta3 = vec![
   10480            2 :             (
   10481            2 :                 get_key(8),
   10482            2 :                 Lsn(0x48),
   10483            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10484            2 :             ),
   10485            2 :             (
   10486            2 :                 get_key(9),
   10487            2 :                 Lsn(0x48),
   10488            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10489            2 :             ),
   10490            2 :         ];
   10491            2 : 
   10492            2 :         let tline = tenant
   10493            2 :             .create_test_timeline_with_layers(
   10494            2 :                 TIMELINE_ID,
   10495            2 :                 Lsn(0x10),
   10496            2 :                 DEFAULT_PG_VERSION,
   10497            2 :                 &ctx,
   10498            2 :                 vec![
   10499            2 :                     // delta1/2/4 only contain a single key but multiple updates
   10500            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10501            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10502            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10503            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10504            2 :                 ], // delta layers
   10505            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10506            2 :                 Lsn(0x50),
   10507            2 :             )
   10508            2 :             .await?;
   10509            2 :         {
   10510            2 :             tline
   10511            2 :                 .latest_gc_cutoff_lsn
   10512            2 :                 .lock_for_write()
   10513            2 :                 .store_and_unlock(Lsn(0x30))
   10514            2 :                 .wait()
   10515            2 :                 .await;
   10516            2 :             // Update GC info
   10517            2 :             let mut guard = tline.gc_info.write().unwrap();
   10518            2 :             *guard = GcInfo {
   10519            2 :                 retain_lsns: vec![
   10520            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10521            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10522            2 :                 ],
   10523            2 :                 cutoffs: GcCutoffs {
   10524            2 :                     time: Lsn(0x30),
   10525            2 :                     space: Lsn(0x30),
   10526            2 :                 },
   10527            2 :                 leases: Default::default(),
   10528            2 :                 within_ancestor_pitr: false,
   10529            2 :             };
   10530            2 :         }
   10531            2 : 
   10532            2 :         let expected_result = [
   10533            2 :             Bytes::from_static(b"value 0@0x10"),
   10534            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10535            2 :             Bytes::from_static(b"value 2@0x10"),
   10536            2 :             Bytes::from_static(b"value 3@0x10"),
   10537            2 :             Bytes::from_static(b"value 4@0x10"),
   10538            2 :             Bytes::from_static(b"value 5@0x10"),
   10539            2 :             Bytes::from_static(b"value 6@0x10"),
   10540            2 :             Bytes::from_static(b"value 7@0x10"),
   10541            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10542            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10543            2 :         ];
   10544            2 : 
   10545            2 :         let expected_result_at_gc_horizon = [
   10546            2 :             Bytes::from_static(b"value 0@0x10"),
   10547            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10548            2 :             Bytes::from_static(b"value 2@0x10"),
   10549            2 :             Bytes::from_static(b"value 3@0x10"),
   10550            2 :             Bytes::from_static(b"value 4@0x10"),
   10551            2 :             Bytes::from_static(b"value 5@0x10"),
   10552            2 :             Bytes::from_static(b"value 6@0x10"),
   10553            2 :             Bytes::from_static(b"value 7@0x10"),
   10554            2 :             Bytes::from_static(b"value 8@0x10"),
   10555            2 :             Bytes::from_static(b"value 9@0x10"),
   10556            2 :         ];
   10557            2 : 
   10558            2 :         let expected_result_at_lsn_20 = [
   10559            2 :             Bytes::from_static(b"value 0@0x10"),
   10560            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10561            2 :             Bytes::from_static(b"value 2@0x10"),
   10562            2 :             Bytes::from_static(b"value 3@0x10"),
   10563            2 :             Bytes::from_static(b"value 4@0x10"),
   10564            2 :             Bytes::from_static(b"value 5@0x10"),
   10565            2 :             Bytes::from_static(b"value 6@0x10"),
   10566            2 :             Bytes::from_static(b"value 7@0x10"),
   10567            2 :             Bytes::from_static(b"value 8@0x10"),
   10568            2 :             Bytes::from_static(b"value 9@0x10"),
   10569            2 :         ];
   10570            2 : 
   10571            2 :         let expected_result_at_lsn_10 = [
   10572            2 :             Bytes::from_static(b"value 0@0x10"),
   10573            2 :             Bytes::from_static(b"value 1@0x10"),
   10574            2 :             Bytes::from_static(b"value 2@0x10"),
   10575            2 :             Bytes::from_static(b"value 3@0x10"),
   10576            2 :             Bytes::from_static(b"value 4@0x10"),
   10577            2 :             Bytes::from_static(b"value 5@0x10"),
   10578            2 :             Bytes::from_static(b"value 6@0x10"),
   10579            2 :             Bytes::from_static(b"value 7@0x10"),
   10580            2 :             Bytes::from_static(b"value 8@0x10"),
   10581            2 :             Bytes::from_static(b"value 9@0x10"),
   10582            2 :         ];
   10583            2 : 
   10584            6 :         let verify_result = || async {
   10585            6 :             let gc_horizon = {
   10586            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10587            6 :                 gc_info.cutoffs.time
   10588            2 :             };
   10589           66 :             for idx in 0..10 {
   10590           60 :                 assert_eq!(
   10591           60 :                     tline
   10592           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10593           60 :                         .await
   10594           60 :                         .unwrap(),
   10595           60 :                     &expected_result[idx]
   10596            2 :                 );
   10597           60 :                 assert_eq!(
   10598           60 :                     tline
   10599           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10600           60 :                         .await
   10601           60 :                         .unwrap(),
   10602           60 :                     &expected_result_at_gc_horizon[idx]
   10603            2 :                 );
   10604           60 :                 assert_eq!(
   10605           60 :                     tline
   10606           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10607           60 :                         .await
   10608           60 :                         .unwrap(),
   10609           60 :                     &expected_result_at_lsn_20[idx]
   10610            2 :                 );
   10611           60 :                 assert_eq!(
   10612           60 :                     tline
   10613           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10614           60 :                         .await
   10615           60 :                         .unwrap(),
   10616           60 :                     &expected_result_at_lsn_10[idx]
   10617            2 :                 );
   10618            2 :             }
   10619           12 :         };
   10620            2 : 
   10621            2 :         verify_result().await;
   10622            2 : 
   10623            2 :         let cancel = CancellationToken::new();
   10624            2 :         tline
   10625            2 :             .compact_with_gc(
   10626            2 :                 &cancel,
   10627            2 :                 CompactOptions {
   10628            2 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10629            2 :                     ..Default::default()
   10630            2 :                 },
   10631            2 :                 &ctx,
   10632            2 :             )
   10633            2 :             .await
   10634            2 :             .unwrap();
   10635            2 :         verify_result().await;
   10636            2 : 
   10637            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10638            2 :         check_layer_map_key_eq(
   10639            2 :             all_layers,
   10640            2 :             vec![
   10641            2 :                 // The original image layer, not compacted
   10642            2 :                 PersistentLayerKey {
   10643            2 :                     key_range: get_key(0)..get_key(10),
   10644            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10645            2 :                     is_delta: false,
   10646            2 :                 },
   10647            2 :                 // Delta layer below the specified above_lsn not compacted
   10648            2 :                 PersistentLayerKey {
   10649            2 :                     key_range: get_key(1)..get_key(2),
   10650            2 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10651            2 :                     is_delta: true,
   10652            2 :                 },
   10653            2 :                 // Delta layer compacted above the LSN
   10654            2 :                 PersistentLayerKey {
   10655            2 :                     key_range: get_key(1)..get_key(10),
   10656            2 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10657            2 :                     is_delta: true,
   10658            2 :                 },
   10659            2 :             ],
   10660            2 :         );
   10661            2 : 
   10662            2 :         // compact again
   10663            2 :         tline
   10664            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10665            2 :             .await
   10666            2 :             .unwrap();
   10667            2 :         verify_result().await;
   10668            2 : 
   10669            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10670            2 :         check_layer_map_key_eq(
   10671            2 :             all_layers,
   10672            2 :             vec![
   10673            2 :                 // The compacted image layer (full key range)
   10674            2 :                 PersistentLayerKey {
   10675            2 :                     key_range: Key::MIN..Key::MAX,
   10676            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10677            2 :                     is_delta: false,
   10678            2 :                 },
   10679            2 :                 // All other data in the delta layer
   10680            2 :                 PersistentLayerKey {
   10681            2 :                     key_range: get_key(1)..get_key(10),
   10682            2 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10683            2 :                     is_delta: true,
   10684            2 :                 },
   10685            2 :             ],
   10686            2 :         );
   10687            2 : 
   10688            2 :         Ok(())
   10689            2 :     }
   10690              : 
   10691              :     #[cfg(feature = "testing")]
   10692              :     #[tokio::test]
   10693            2 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   10694            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   10695            2 :         let (tenant, ctx) = harness.load().await;
   10696            2 : 
   10697          508 :         fn get_key(id: u32) -> Key {
   10698          508 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10699          508 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10700          508 :             key.field6 = id;
   10701          508 :             key
   10702          508 :         }
   10703            2 : 
   10704            2 :         let img_layer = (0..10)
   10705           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10706            2 :             .collect_vec();
   10707            2 : 
   10708            2 :         let delta1 = vec![(
   10709            2 :             get_key(1),
   10710            2 :             Lsn(0x20),
   10711            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10712            2 :         )];
   10713            2 :         let delta4 = vec![(
   10714            2 :             get_key(1),
   10715            2 :             Lsn(0x28),
   10716            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10717            2 :         )];
   10718            2 :         let delta2 = vec![
   10719            2 :             (
   10720            2 :                 get_key(1),
   10721            2 :                 Lsn(0x30),
   10722            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10723            2 :             ),
   10724            2 :             (
   10725            2 :                 get_key(1),
   10726            2 :                 Lsn(0x38),
   10727            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10728            2 :             ),
   10729            2 :         ];
   10730            2 :         let delta3 = vec![
   10731            2 :             (
   10732            2 :                 get_key(8),
   10733            2 :                 Lsn(0x48),
   10734            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10735            2 :             ),
   10736            2 :             (
   10737            2 :                 get_key(9),
   10738            2 :                 Lsn(0x48),
   10739            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10740            2 :             ),
   10741            2 :         ];
   10742            2 : 
   10743            2 :         let tline = tenant
   10744            2 :             .create_test_timeline_with_layers(
   10745            2 :                 TIMELINE_ID,
   10746            2 :                 Lsn(0x10),
   10747            2 :                 DEFAULT_PG_VERSION,
   10748            2 :                 &ctx,
   10749            2 :                 vec![
   10750            2 :                     // delta1/2/4 only contain a single key but multiple updates
   10751            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10752            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10753            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10754            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10755            2 :                 ], // delta layers
   10756            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10757            2 :                 Lsn(0x50),
   10758            2 :             )
   10759            2 :             .await?;
   10760            2 :         {
   10761            2 :             tline
   10762            2 :                 .latest_gc_cutoff_lsn
   10763            2 :                 .lock_for_write()
   10764            2 :                 .store_and_unlock(Lsn(0x30))
   10765            2 :                 .wait()
   10766            2 :                 .await;
   10767            2 :             // Update GC info
   10768            2 :             let mut guard = tline.gc_info.write().unwrap();
   10769            2 :             *guard = GcInfo {
   10770            2 :                 retain_lsns: vec![
   10771            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10772            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10773            2 :                 ],
   10774            2 :                 cutoffs: GcCutoffs {
   10775            2 :                     time: Lsn(0x30),
   10776            2 :                     space: Lsn(0x30),
   10777            2 :                 },
   10778            2 :                 leases: Default::default(),
   10779            2 :                 within_ancestor_pitr: false,
   10780            2 :             };
   10781            2 :         }
   10782            2 : 
   10783            2 :         let expected_result = [
   10784            2 :             Bytes::from_static(b"value 0@0x10"),
   10785            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10786            2 :             Bytes::from_static(b"value 2@0x10"),
   10787            2 :             Bytes::from_static(b"value 3@0x10"),
   10788            2 :             Bytes::from_static(b"value 4@0x10"),
   10789            2 :             Bytes::from_static(b"value 5@0x10"),
   10790            2 :             Bytes::from_static(b"value 6@0x10"),
   10791            2 :             Bytes::from_static(b"value 7@0x10"),
   10792            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10793            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10794            2 :         ];
   10795            2 : 
   10796            2 :         let expected_result_at_gc_horizon = [
   10797            2 :             Bytes::from_static(b"value 0@0x10"),
   10798            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10799            2 :             Bytes::from_static(b"value 2@0x10"),
   10800            2 :             Bytes::from_static(b"value 3@0x10"),
   10801            2 :             Bytes::from_static(b"value 4@0x10"),
   10802            2 :             Bytes::from_static(b"value 5@0x10"),
   10803            2 :             Bytes::from_static(b"value 6@0x10"),
   10804            2 :             Bytes::from_static(b"value 7@0x10"),
   10805            2 :             Bytes::from_static(b"value 8@0x10"),
   10806            2 :             Bytes::from_static(b"value 9@0x10"),
   10807            2 :         ];
   10808            2 : 
   10809            2 :         let expected_result_at_lsn_20 = [
   10810            2 :             Bytes::from_static(b"value 0@0x10"),
   10811            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10812            2 :             Bytes::from_static(b"value 2@0x10"),
   10813            2 :             Bytes::from_static(b"value 3@0x10"),
   10814            2 :             Bytes::from_static(b"value 4@0x10"),
   10815            2 :             Bytes::from_static(b"value 5@0x10"),
   10816            2 :             Bytes::from_static(b"value 6@0x10"),
   10817            2 :             Bytes::from_static(b"value 7@0x10"),
   10818            2 :             Bytes::from_static(b"value 8@0x10"),
   10819            2 :             Bytes::from_static(b"value 9@0x10"),
   10820            2 :         ];
   10821            2 : 
   10822            2 :         let expected_result_at_lsn_10 = [
   10823            2 :             Bytes::from_static(b"value 0@0x10"),
   10824            2 :             Bytes::from_static(b"value 1@0x10"),
   10825            2 :             Bytes::from_static(b"value 2@0x10"),
   10826            2 :             Bytes::from_static(b"value 3@0x10"),
   10827            2 :             Bytes::from_static(b"value 4@0x10"),
   10828            2 :             Bytes::from_static(b"value 5@0x10"),
   10829            2 :             Bytes::from_static(b"value 6@0x10"),
   10830            2 :             Bytes::from_static(b"value 7@0x10"),
   10831            2 :             Bytes::from_static(b"value 8@0x10"),
   10832            2 :             Bytes::from_static(b"value 9@0x10"),
   10833            2 :         ];
   10834            2 : 
   10835           10 :         let verify_result = || async {
   10836           10 :             let gc_horizon = {
   10837           10 :                 let gc_info = tline.gc_info.read().unwrap();
   10838           10 :                 gc_info.cutoffs.time
   10839            2 :             };
   10840          110 :             for idx in 0..10 {
   10841          100 :                 assert_eq!(
   10842          100 :                     tline
   10843          100 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10844          100 :                         .await
   10845          100 :                         .unwrap(),
   10846          100 :                     &expected_result[idx]
   10847            2 :                 );
   10848          100 :                 assert_eq!(
   10849          100 :                     tline
   10850          100 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10851          100 :                         .await
   10852          100 :                         .unwrap(),
   10853          100 :                     &expected_result_at_gc_horizon[idx]
   10854            2 :                 );
   10855          100 :                 assert_eq!(
   10856          100 :                     tline
   10857          100 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10858          100 :                         .await
   10859          100 :                         .unwrap(),
   10860          100 :                     &expected_result_at_lsn_20[idx]
   10861            2 :                 );
   10862          100 :                 assert_eq!(
   10863          100 :                     tline
   10864          100 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10865          100 :                         .await
   10866          100 :                         .unwrap(),
   10867          100 :                     &expected_result_at_lsn_10[idx]
   10868            2 :                 );
   10869            2 :             }
   10870           20 :         };
   10871            2 : 
   10872            2 :         verify_result().await;
   10873            2 : 
   10874            2 :         let cancel = CancellationToken::new();
   10875            2 : 
   10876            2 :         tline
   10877            2 :             .compact_with_gc(
   10878            2 :                 &cancel,
   10879            2 :                 CompactOptions {
   10880            2 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10881            2 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   10882            2 :                     ..Default::default()
   10883            2 :                 },
   10884            2 :                 &ctx,
   10885            2 :             )
   10886            2 :             .await
   10887            2 :             .unwrap();
   10888            2 :         verify_result().await;
   10889            2 : 
   10890            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10891            2 :         check_layer_map_key_eq(
   10892            2 :             all_layers,
   10893            2 :             vec![
   10894            2 :                 // The original image layer, not compacted
   10895            2 :                 PersistentLayerKey {
   10896            2 :                     key_range: get_key(0)..get_key(10),
   10897            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10898            2 :                     is_delta: false,
   10899            2 :                 },
   10900            2 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   10901            2 :                 // the layer 0x28-0x30 into one.
   10902            2 :                 PersistentLayerKey {
   10903            2 :                     key_range: get_key(1)..get_key(2),
   10904            2 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   10905            2 :                     is_delta: true,
   10906            2 :                 },
   10907            2 :                 // Above the upper bound and untouched
   10908            2 :                 PersistentLayerKey {
   10909            2 :                     key_range: get_key(1)..get_key(2),
   10910            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   10911            2 :                     is_delta: true,
   10912            2 :                 },
   10913            2 :                 // This layer is untouched
   10914            2 :                 PersistentLayerKey {
   10915            2 :                     key_range: get_key(8)..get_key(10),
   10916            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   10917            2 :                     is_delta: true,
   10918            2 :                 },
   10919            2 :             ],
   10920            2 :         );
   10921            2 : 
   10922            2 :         tline
   10923            2 :             .compact_with_gc(
   10924            2 :                 &cancel,
   10925            2 :                 CompactOptions {
   10926            2 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   10927            2 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   10928            2 :                     ..Default::default()
   10929            2 :                 },
   10930            2 :                 &ctx,
   10931            2 :             )
   10932            2 :             .await
   10933            2 :             .unwrap();
   10934            2 :         verify_result().await;
   10935            2 : 
   10936            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10937            2 :         check_layer_map_key_eq(
   10938            2 :             all_layers,
   10939            2 :             vec![
   10940            2 :                 // The original image layer, not compacted
   10941            2 :                 PersistentLayerKey {
   10942            2 :                     key_range: get_key(0)..get_key(10),
   10943            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10944            2 :                     is_delta: false,
   10945            2 :                 },
   10946            2 :                 // Not in the compaction key range, uncompacted
   10947            2 :                 PersistentLayerKey {
   10948            2 :                     key_range: get_key(1)..get_key(2),
   10949            2 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   10950            2 :                     is_delta: true,
   10951            2 :                 },
   10952            2 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   10953            2 :                 PersistentLayerKey {
   10954            2 :                     key_range: get_key(1)..get_key(2),
   10955            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   10956            2 :                     is_delta: true,
   10957            2 :                 },
   10958            2 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   10959            2 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   10960            2 :                 // becomes 0x50.
   10961            2 :                 PersistentLayerKey {
   10962            2 :                     key_range: get_key(8)..get_key(10),
   10963            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   10964            2 :                     is_delta: true,
   10965            2 :                 },
   10966            2 :             ],
   10967            2 :         );
   10968            2 : 
   10969            2 :         // compact again
   10970            2 :         tline
   10971            2 :             .compact_with_gc(
   10972            2 :                 &cancel,
   10973            2 :                 CompactOptions {
   10974            2 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   10975            2 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   10976            2 :                     ..Default::default()
   10977            2 :                 },
   10978            2 :                 &ctx,
   10979            2 :             )
   10980            2 :             .await
   10981            2 :             .unwrap();
   10982            2 :         verify_result().await;
   10983            2 : 
   10984            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10985            2 :         check_layer_map_key_eq(
   10986            2 :             all_layers,
   10987            2 :             vec![
   10988            2 :                 // The original image layer, not compacted
   10989            2 :                 PersistentLayerKey {
   10990            2 :                     key_range: get_key(0)..get_key(10),
   10991            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10992            2 :                     is_delta: false,
   10993            2 :                 },
   10994            2 :                 // The range gets compacted
   10995            2 :                 PersistentLayerKey {
   10996            2 :                     key_range: get_key(1)..get_key(2),
   10997            2 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   10998            2 :                     is_delta: true,
   10999            2 :                 },
   11000            2 :                 // Not touched during this iteration of compaction
   11001            2 :                 PersistentLayerKey {
   11002            2 :                     key_range: get_key(8)..get_key(10),
   11003            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11004            2 :                     is_delta: true,
   11005            2 :                 },
   11006            2 :             ],
   11007            2 :         );
   11008            2 : 
   11009            2 :         // final full compaction
   11010            2 :         tline
   11011            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11012            2 :             .await
   11013            2 :             .unwrap();
   11014            2 :         verify_result().await;
   11015            2 : 
   11016            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11017            2 :         check_layer_map_key_eq(
   11018            2 :             all_layers,
   11019            2 :             vec![
   11020            2 :                 // The compacted image layer (full key range)
   11021            2 :                 PersistentLayerKey {
   11022            2 :                     key_range: Key::MIN..Key::MAX,
   11023            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11024            2 :                     is_delta: false,
   11025            2 :                 },
   11026            2 :                 // All other data in the delta layer
   11027            2 :                 PersistentLayerKey {
   11028            2 :                     key_range: get_key(1)..get_key(10),
   11029            2 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11030            2 :                     is_delta: true,
   11031            2 :                 },
   11032            2 :             ],
   11033            2 :         );
   11034            2 : 
   11035            2 :         Ok(())
   11036            2 :     }
   11037              : }
        

Generated by: LCOV version 2.1-beta