LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 20b6afc7b7f34578dcaab2b3acdaecfe91cd8bf1.info Lines: 74.5 % 7503 5591
Test Date: 2024-11-25 17:48:16 Functions: 57.5 % 438 252

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use anyhow::{bail, Context};
      16              : use arc_swap::ArcSwap;
      17              : use camino::Utf8Path;
      18              : use camino::Utf8PathBuf;
      19              : use chrono::NaiveDateTime;
      20              : use enumset::EnumSet;
      21              : use futures::stream::FuturesUnordered;
      22              : use futures::StreamExt;
      23              : use pageserver_api::models;
      24              : use pageserver_api::models::LsnLease;
      25              : use pageserver_api::models::TimelineArchivalState;
      26              : use pageserver_api::models::TimelineState;
      27              : use pageserver_api::models::TopTenantShardItem;
      28              : use pageserver_api::models::WalRedoManagerStatus;
      29              : use pageserver_api::shard::ShardIdentity;
      30              : use pageserver_api::shard::ShardStripeSize;
      31              : use pageserver_api::shard::TenantShardId;
      32              : use remote_storage::DownloadError;
      33              : use remote_storage::GenericRemoteStorage;
      34              : use remote_storage::TimeoutOrCancel;
      35              : use remote_timeline_client::manifest::{
      36              :     OffloadedTimelineManifest, TenantManifest, LATEST_TENANT_MANIFEST_VERSION,
      37              : };
      38              : use remote_timeline_client::UploadQueueNotReadyError;
      39              : use std::collections::BTreeMap;
      40              : use std::fmt;
      41              : use std::future::Future;
      42              : use std::sync::atomic::AtomicBool;
      43              : use std::sync::Weak;
      44              : use std::time::SystemTime;
      45              : use storage_broker::BrokerClientChannel;
      46              : use timeline::import_pgdata;
      47              : use timeline::offload::offload_timeline;
      48              : use timeline::ShutdownMode;
      49              : use tokio::io::BufReader;
      50              : use tokio::sync::watch;
      51              : use tokio::task::JoinSet;
      52              : use tokio_util::sync::CancellationToken;
      53              : use tracing::*;
      54              : use upload_queue::NotInitialized;
      55              : use utils::backoff;
      56              : use utils::circuit_breaker::CircuitBreaker;
      57              : use utils::completion;
      58              : use utils::crashsafe::path_with_suffix_extension;
      59              : use utils::failpoint_support;
      60              : use utils::fs_ext;
      61              : use utils::pausable_failpoint;
      62              : use utils::sync::gate::Gate;
      63              : use utils::sync::gate::GateGuard;
      64              : use utils::timeout::timeout_cancellable;
      65              : use utils::timeout::TimeoutCancellableError;
      66              : use utils::zstd::create_zst_tarball;
      67              : use utils::zstd::extract_zst_tarball;
      68              : 
      69              : use self::config::AttachedLocationConfig;
      70              : use self::config::AttachmentMode;
      71              : use self::config::LocationConf;
      72              : use self::config::TenantConf;
      73              : use self::metadata::TimelineMetadata;
      74              : use self::mgr::GetActiveTenantError;
      75              : use self::mgr::GetTenantError;
      76              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      77              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      78              : use self::timeline::uninit::TimelineCreateGuard;
      79              : use self::timeline::uninit::TimelineExclusionError;
      80              : use self::timeline::uninit::UninitializedTimeline;
      81              : use self::timeline::EvictionTaskTenantState;
      82              : use self::timeline::GcCutoffs;
      83              : use self::timeline::TimelineDeleteProgress;
      84              : use self::timeline::TimelineResources;
      85              : use self::timeline::WaitLsnError;
      86              : use crate::config::PageServerConf;
      87              : use crate::context::{DownloadBehavior, RequestContext};
      88              : use crate::deletion_queue::DeletionQueueClient;
      89              : use crate::deletion_queue::DeletionQueueError;
      90              : use crate::import_datadir;
      91              : use crate::is_uninit_mark;
      92              : use crate::l0_flush::L0FlushGlobalState;
      93              : use crate::metrics::TENANT;
      94              : use crate::metrics::{
      95              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
      96              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
      97              : };
      98              : use crate::task_mgr;
      99              : use crate::task_mgr::TaskKind;
     100              : use crate::tenant::config::LocationMode;
     101              : use crate::tenant::config::TenantConfOpt;
     102              : use crate::tenant::gc_result::GcResult;
     103              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     104              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     105              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     106              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     107              : use crate::tenant::storage_layer::DeltaLayer;
     108              : use crate::tenant::storage_layer::ImageLayer;
     109              : use crate::walingest::WalLagCooldown;
     110              : use crate::walredo;
     111              : use crate::InitializationOrder;
     112              : use std::collections::hash_map::Entry;
     113              : use std::collections::HashMap;
     114              : use std::collections::HashSet;
     115              : use std::fmt::Debug;
     116              : use std::fmt::Display;
     117              : use std::fs;
     118              : use std::fs::File;
     119              : use std::sync::atomic::{AtomicU64, Ordering};
     120              : use std::sync::Arc;
     121              : use std::sync::Mutex;
     122              : use std::time::{Duration, Instant};
     123              : 
     124              : use crate::span;
     125              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     126              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     127              : use crate::virtual_file::VirtualFile;
     128              : use crate::walredo::PostgresRedoManager;
     129              : use crate::TEMP_FILE_SUFFIX;
     130              : use once_cell::sync::Lazy;
     131              : pub use pageserver_api::models::TenantState;
     132              : use tokio::sync::Semaphore;
     133              : 
     134            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     135              : use utils::{
     136              :     crashsafe,
     137              :     generation::Generation,
     138              :     id::TimelineId,
     139              :     lsn::{Lsn, RecordLsn},
     140              : };
     141              : 
     142              : pub mod blob_io;
     143              : pub mod block_io;
     144              : pub mod vectored_blob_io;
     145              : 
     146              : pub mod disk_btree;
     147              : pub(crate) mod ephemeral_file;
     148              : pub mod layer_map;
     149              : 
     150              : pub mod metadata;
     151              : pub mod remote_timeline_client;
     152              : pub mod storage_layer;
     153              : 
     154              : pub mod checks;
     155              : pub mod config;
     156              : pub mod mgr;
     157              : pub mod secondary;
     158              : pub mod tasks;
     159              : pub mod upload_queue;
     160              : 
     161              : pub(crate) mod timeline;
     162              : 
     163              : pub mod size;
     164              : 
     165              : mod gc_block;
     166              : mod gc_result;
     167              : pub(crate) mod throttle;
     168              : 
     169              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     170              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     171              : 
     172              : // re-export for use in walreceiver
     173              : pub use crate::tenant::timeline::WalReceiverInfo;
     174              : 
     175              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     176              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     177              : 
     178              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     179              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     180              : 
     181              : /// References to shared objects that are passed into each tenant, such
     182              : /// as the shared remote storage client and process initialization state.
     183              : #[derive(Clone)]
     184              : pub struct TenantSharedResources {
     185              :     pub broker_client: storage_broker::BrokerClientChannel,
     186              :     pub remote_storage: GenericRemoteStorage,
     187              :     pub deletion_queue_client: DeletionQueueClient,
     188              :     pub l0_flush_global_state: L0FlushGlobalState,
     189              : }
     190              : 
     191              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     192              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     193              : /// in this struct.
     194              : #[derive(Clone)]
     195              : pub(super) struct AttachedTenantConf {
     196              :     tenant_conf: TenantConfOpt,
     197              :     location: AttachedLocationConfig,
     198              :     /// The deadline before which we are blocked from GC so that
     199              :     /// leases have a chance to be renewed.
     200              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     201              : }
     202              : 
     203              : impl AttachedTenantConf {
     204          192 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     205              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     206              :         //
     207              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     208              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     209              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     210          192 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     211          192 :             Some(
     212          192 :                 tokio::time::Instant::now()
     213          192 :                     + tenant_conf
     214          192 :                         .lsn_lease_length
     215          192 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     216          192 :             )
     217              :         } else {
     218              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     219              :             // because we don't do GC in these modes.
     220            0 :             None
     221              :         };
     222              : 
     223          192 :         Self {
     224          192 :             tenant_conf,
     225          192 :             location,
     226          192 :             lsn_lease_deadline,
     227          192 :         }
     228          192 :     }
     229              : 
     230          192 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     231          192 :         match &location_conf.mode {
     232          192 :             LocationMode::Attached(attach_conf) => {
     233          192 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     234              :             }
     235              :             LocationMode::Secondary(_) => {
     236            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     237              :             }
     238              :         }
     239          192 :     }
     240              : 
     241          762 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     242          762 :         self.lsn_lease_deadline
     243          762 :             .map(|d| tokio::time::Instant::now() < d)
     244          762 :             .unwrap_or(false)
     245          762 :     }
     246              : }
     247              : struct TimelinePreload {
     248              :     timeline_id: TimelineId,
     249              :     client: RemoteTimelineClient,
     250              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     251              : }
     252              : 
     253              : pub(crate) struct TenantPreload {
     254              :     tenant_manifest: TenantManifest,
     255              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     256              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     257              : }
     258              : 
     259              : /// When we spawn a tenant, there is a special mode for tenant creation that
     260              : /// avoids trying to read anything from remote storage.
     261              : pub(crate) enum SpawnMode {
     262              :     /// Activate as soon as possible
     263              :     Eager,
     264              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     265              :     Lazy,
     266              : }
     267              : 
     268              : ///
     269              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     270              : ///
     271              : pub struct Tenant {
     272              :     // Global pageserver config parameters
     273              :     pub conf: &'static PageServerConf,
     274              : 
     275              :     /// The value creation timestamp, used to measure activation delay, see:
     276              :     /// <https://github.com/neondatabase/neon/issues/4025>
     277              :     constructed_at: Instant,
     278              : 
     279              :     state: watch::Sender<TenantState>,
     280              : 
     281              :     // Overridden tenant-specific config parameters.
     282              :     // We keep TenantConfOpt sturct here to preserve the information
     283              :     // about parameters that are not set.
     284              :     // This is necessary to allow global config updates.
     285              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     286              : 
     287              :     tenant_shard_id: TenantShardId,
     288              : 
     289              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     290              :     shard_identity: ShardIdentity,
     291              : 
     292              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     293              :     /// Does not change over the lifetime of the [`Tenant`] object.
     294              :     ///
     295              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     296              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     297              :     generation: Generation,
     298              : 
     299              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     300              : 
     301              :     /// During timeline creation, we first insert the TimelineId to the
     302              :     /// creating map, then `timelines`, then remove it from the creating map.
     303              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     304              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     305              : 
     306              :     /// Possibly offloaded and archived timelines
     307              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     308              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     309              : 
     310              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     311              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     312              :     /// each other (this could be optimized to coalesce writes if necessary).
     313              :     ///
     314              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     315              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     316              : 
     317              :     // This mutex prevents creation of new timelines during GC.
     318              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     319              :     // `timelines` mutex during all GC iteration
     320              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     321              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     322              :     // timeout...
     323              :     gc_cs: tokio::sync::Mutex<()>,
     324              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     325              : 
     326              :     // provides access to timeline data sitting in the remote storage
     327              :     pub(crate) remote_storage: GenericRemoteStorage,
     328              : 
     329              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     330              :     deletion_queue_client: DeletionQueueClient,
     331              : 
     332              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     333              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     334              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     335              : 
     336              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     337              : 
     338              :     /// Track repeated failures to compact, so that we can back off.
     339              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     340              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     341              : 
     342              :     /// If the tenant is in Activating state, notify this to encourage it
     343              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     344              :     /// background warmup.
     345              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     346              : 
     347              :     /// Time it took for the tenant to activate. Zero if not active yet.
     348              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     349              : 
     350              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     351              :     // Timelines' cancellation token.
     352              :     pub(crate) cancel: CancellationToken,
     353              : 
     354              :     // Users of the Tenant such as the page service must take this Gate to avoid
     355              :     // trying to use a Tenant which is shutting down.
     356              :     pub(crate) gate: Gate,
     357              : 
     358              :     /// Throttle applied at the top of [`Timeline::get`].
     359              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     360              :     pub(crate) timeline_get_throttle:
     361              :         Arc<throttle::Throttle<crate::metrics::tenant_throttling::TimelineGet>>,
     362              : 
     363              :     /// An ongoing timeline detach concurrency limiter.
     364              :     ///
     365              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     366              :     /// to have two running at the same time. A different one can be started if an earlier one
     367              :     /// has failed for whatever reason.
     368              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     369              : 
     370              :     /// `index_part.json` based gc blocking reason tracking.
     371              :     ///
     372              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     373              :     /// proceeding.
     374              :     pub(crate) gc_block: gc_block::GcBlock,
     375              : 
     376              :     l0_flush_global_state: L0FlushGlobalState,
     377              : }
     378              : impl std::fmt::Debug for Tenant {
     379            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     380            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     381            0 :     }
     382              : }
     383              : 
     384              : pub(crate) enum WalRedoManager {
     385              :     Prod(WalredoManagerId, PostgresRedoManager),
     386              :     #[cfg(test)]
     387              :     Test(harness::TestRedoManager),
     388              : }
     389              : 
     390            0 : #[derive(thiserror::Error, Debug)]
     391              : #[error("pageserver is shutting down")]
     392              : pub(crate) struct GlobalShutDown;
     393              : 
     394              : impl WalRedoManager {
     395            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     396            0 :         let id = WalredoManagerId::next();
     397            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     398            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     399            0 :         match &mut *guard {
     400            0 :             Some(map) => {
     401            0 :                 map.insert(id, Arc::downgrade(&arc));
     402            0 :                 Ok(arc)
     403              :             }
     404            0 :             None => Err(GlobalShutDown),
     405              :         }
     406            0 :     }
     407              : }
     408              : 
     409              : impl Drop for WalRedoManager {
     410           10 :     fn drop(&mut self) {
     411           10 :         match self {
     412            0 :             Self::Prod(id, _) => {
     413            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     414            0 :                 if let Some(map) = &mut *guard {
     415            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     416            0 :                 }
     417              :             }
     418              :             #[cfg(test)]
     419           10 :             Self::Test(_) => {
     420           10 :                 // Not applicable to test redo manager
     421           10 :             }
     422              :         }
     423           10 :     }
     424              : }
     425              : 
     426              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     427              : /// the walredo processes outside of the regular order.
     428              : ///
     429              : /// This is necessary to work around a systemd bug where it freezes if there are
     430              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     431              : #[allow(clippy::type_complexity)]
     432              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     433              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     434            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     435              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     436              : pub(crate) struct WalredoManagerId(u64);
     437              : impl WalredoManagerId {
     438            0 :     pub fn next() -> Self {
     439              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     440            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     441            0 :         if id == 0 {
     442            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     443            0 :         }
     444            0 :         Self(id)
     445            0 :     }
     446              : }
     447              : 
     448              : #[cfg(test)]
     449              : impl From<harness::TestRedoManager> for WalRedoManager {
     450          192 :     fn from(mgr: harness::TestRedoManager) -> Self {
     451          192 :         Self::Test(mgr)
     452          192 :     }
     453              : }
     454              : 
     455              : impl WalRedoManager {
     456            6 :     pub(crate) async fn shutdown(&self) -> bool {
     457            6 :         match self {
     458            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     459              :             #[cfg(test)]
     460              :             Self::Test(_) => {
     461              :                 // Not applicable to test redo manager
     462            6 :                 true
     463              :             }
     464              :         }
     465            6 :     }
     466              : 
     467            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     468            0 :         match self {
     469            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     470            0 :             #[cfg(test)]
     471            0 :             Self::Test(_) => {
     472            0 :                 // Not applicable to test redo manager
     473            0 :             }
     474            0 :         }
     475            0 :     }
     476              : 
     477              :     /// # Cancel-Safety
     478              :     ///
     479              :     /// This method is cancellation-safe.
     480          410 :     pub async fn request_redo(
     481          410 :         &self,
     482          410 :         key: pageserver_api::key::Key,
     483          410 :         lsn: Lsn,
     484          410 :         base_img: Option<(Lsn, bytes::Bytes)>,
     485          410 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     486          410 :         pg_version: u32,
     487          410 :     ) -> Result<bytes::Bytes, walredo::Error> {
     488          410 :         match self {
     489            0 :             Self::Prod(_, mgr) => {
     490            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     491            0 :                     .await
     492              :             }
     493              :             #[cfg(test)]
     494          410 :             Self::Test(mgr) => {
     495          410 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     496            0 :                     .await
     497              :             }
     498              :         }
     499          410 :     }
     500              : 
     501            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     502            0 :         match self {
     503            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     504            0 :             #[cfg(test)]
     505            0 :             WalRedoManager::Test(_) => None,
     506            0 :         }
     507            0 :     }
     508              : }
     509              : 
     510              : /// A very lightweight memory representation of an offloaded timeline.
     511              : ///
     512              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     513              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     514              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     515              : /// more offloaded timelines than we can manage ones that aren't.
     516              : pub struct OffloadedTimeline {
     517              :     pub tenant_shard_id: TenantShardId,
     518              :     pub timeline_id: TimelineId,
     519              :     pub ancestor_timeline_id: Option<TimelineId>,
     520              :     /// Whether to retain the branch lsn at the ancestor or not
     521              :     pub ancestor_retain_lsn: Option<Lsn>,
     522              : 
     523              :     /// When the timeline was archived.
     524              :     ///
     525              :     /// Present for future flattening deliberations.
     526              :     pub archived_at: NaiveDateTime,
     527              : 
     528              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     529              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     530              :     pub delete_progress: TimelineDeleteProgress,
     531              : 
     532              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     533              :     pub deleted_from_ancestor: AtomicBool,
     534              : }
     535              : 
     536              : impl OffloadedTimeline {
     537              :     /// Obtains an offloaded timeline from a given timeline object.
     538              :     ///
     539              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     540              :     /// the timeline is not in a stopped state.
     541              :     /// Panics if the timeline is not archived.
     542            2 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     543            2 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     544            2 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     545            2 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     546            2 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     547            2 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     548            2 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     549            2 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     550              :             } else {
     551            0 :                 (None, None)
     552              :             };
     553            2 :         let archived_at = timeline
     554            2 :             .remote_client
     555            2 :             .archived_at_stopped_queue()?
     556            2 :             .expect("must be called on an archived timeline");
     557            2 :         Ok(Self {
     558            2 :             tenant_shard_id: timeline.tenant_shard_id,
     559            2 :             timeline_id: timeline.timeline_id,
     560            2 :             ancestor_timeline_id,
     561            2 :             ancestor_retain_lsn,
     562            2 :             archived_at,
     563            2 : 
     564            2 :             delete_progress: timeline.delete_progress.clone(),
     565            2 :             deleted_from_ancestor: AtomicBool::new(false),
     566            2 :         })
     567            2 :     }
     568            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     569            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     570            0 :         // by the `initialize_gc_info` function.
     571            0 :         let OffloadedTimelineManifest {
     572            0 :             timeline_id,
     573            0 :             ancestor_timeline_id,
     574            0 :             ancestor_retain_lsn,
     575            0 :             archived_at,
     576            0 :         } = *manifest;
     577            0 :         Self {
     578            0 :             tenant_shard_id,
     579            0 :             timeline_id,
     580            0 :             ancestor_timeline_id,
     581            0 :             ancestor_retain_lsn,
     582            0 :             archived_at,
     583            0 :             delete_progress: TimelineDeleteProgress::default(),
     584            0 :             deleted_from_ancestor: AtomicBool::new(false),
     585            0 :         }
     586            0 :     }
     587            2 :     fn manifest(&self) -> OffloadedTimelineManifest {
     588            2 :         let Self {
     589            2 :             timeline_id,
     590            2 :             ancestor_timeline_id,
     591            2 :             ancestor_retain_lsn,
     592            2 :             archived_at,
     593            2 :             ..
     594            2 :         } = self;
     595            2 :         OffloadedTimelineManifest {
     596            2 :             timeline_id: *timeline_id,
     597            2 :             ancestor_timeline_id: *ancestor_timeline_id,
     598            2 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     599            2 :             archived_at: *archived_at,
     600            2 :         }
     601            2 :     }
     602              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     603            0 :     fn delete_from_ancestor_with_timelines(
     604            0 :         &self,
     605            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     606            0 :     ) {
     607            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     608            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     609              :         {
     610            0 :             if let Some((_, ancestor_timeline)) = timelines
     611            0 :                 .iter()
     612            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     613              :             {
     614            0 :                 let removal_happened = ancestor_timeline
     615            0 :                     .gc_info
     616            0 :                     .write()
     617            0 :                     .unwrap()
     618            0 :                     .remove_child_offloaded(self.timeline_id);
     619            0 :                 if !removal_happened {
     620            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     621            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     622            0 :                 }
     623            0 :             }
     624            0 :         }
     625            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     626            0 :     }
     627              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     628              :     ///
     629              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     630            2 :     fn defuse_for_tenant_drop(&self) {
     631            2 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     632            2 :     }
     633              : }
     634              : 
     635              : impl fmt::Debug for OffloadedTimeline {
     636            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     637            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     638            0 :     }
     639              : }
     640              : 
     641              : impl Drop for OffloadedTimeline {
     642            2 :     fn drop(&mut self) {
     643            2 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     644            0 :             tracing::warn!(
     645            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     646              :                 self.timeline_id
     647              :             );
     648            2 :         }
     649            2 :     }
     650              : }
     651              : 
     652              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     653              : pub enum MaybeOffloaded {
     654              :     Yes,
     655              :     No,
     656              : }
     657              : 
     658              : #[derive(Clone, Debug)]
     659              : pub enum TimelineOrOffloaded {
     660              :     Timeline(Arc<Timeline>),
     661              :     Offloaded(Arc<OffloadedTimeline>),
     662              : }
     663              : 
     664              : impl TimelineOrOffloaded {
     665            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     666            0 :         match self {
     667            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     668            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     669              :             }
     670            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     671            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     672              :             }
     673              :         }
     674            0 :     }
     675            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     676            0 :         self.arc_ref().tenant_shard_id()
     677            0 :     }
     678            0 :     pub fn timeline_id(&self) -> TimelineId {
     679            0 :         self.arc_ref().timeline_id()
     680            0 :     }
     681            2 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     682            2 :         match self {
     683            2 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     684            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     685              :         }
     686            2 :     }
     687            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     688            0 :         match self {
     689            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     690            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     691              :         }
     692            0 :     }
     693              : }
     694              : 
     695              : pub enum TimelineOrOffloadedArcRef<'a> {
     696              :     Timeline(&'a Arc<Timeline>),
     697              :     Offloaded(&'a Arc<OffloadedTimeline>),
     698              : }
     699              : 
     700              : impl TimelineOrOffloadedArcRef<'_> {
     701            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     702            0 :         match self {
     703            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     704            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     705              :         }
     706            0 :     }
     707            0 :     pub fn timeline_id(&self) -> TimelineId {
     708            0 :         match self {
     709            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     710            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     711              :         }
     712            0 :     }
     713              : }
     714              : 
     715              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     716            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     717            0 :         Self::Timeline(timeline)
     718            0 :     }
     719              : }
     720              : 
     721              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     722            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     723            0 :         Self::Offloaded(timeline)
     724            0 :     }
     725              : }
     726              : 
     727            0 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     728              : pub enum GetTimelineError {
     729              :     #[error("Timeline is shutting down")]
     730              :     ShuttingDown,
     731              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     732              :     NotActive {
     733              :         tenant_id: TenantShardId,
     734              :         timeline_id: TimelineId,
     735              :         state: TimelineState,
     736              :     },
     737              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     738              :     NotFound {
     739              :         tenant_id: TenantShardId,
     740              :         timeline_id: TimelineId,
     741              :     },
     742              : }
     743              : 
     744            0 : #[derive(Debug, thiserror::Error)]
     745              : pub enum LoadLocalTimelineError {
     746              :     #[error("FailedToLoad")]
     747              :     Load(#[source] anyhow::Error),
     748              :     #[error("FailedToResumeDeletion")]
     749              :     ResumeDeletion(#[source] anyhow::Error),
     750              : }
     751              : 
     752            0 : #[derive(thiserror::Error)]
     753              : pub enum DeleteTimelineError {
     754              :     #[error("NotFound")]
     755              :     NotFound,
     756              : 
     757              :     #[error("HasChildren")]
     758              :     HasChildren(Vec<TimelineId>),
     759              : 
     760              :     #[error("Timeline deletion is already in progress")]
     761              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     762              : 
     763              :     #[error("Cancelled")]
     764              :     Cancelled,
     765              : 
     766              :     #[error(transparent)]
     767              :     Other(#[from] anyhow::Error),
     768              : }
     769              : 
     770              : impl Debug for DeleteTimelineError {
     771            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     772            0 :         match self {
     773            0 :             Self::NotFound => write!(f, "NotFound"),
     774            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     775            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     776            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     777            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     778              :         }
     779            0 :     }
     780              : }
     781              : 
     782            0 : #[derive(thiserror::Error)]
     783              : pub enum TimelineArchivalError {
     784              :     #[error("NotFound")]
     785              :     NotFound,
     786              : 
     787              :     #[error("Timeout")]
     788              :     Timeout,
     789              : 
     790              :     #[error("Cancelled")]
     791              :     Cancelled,
     792              : 
     793              :     #[error("ancestor is archived: {}", .0)]
     794              :     HasArchivedParent(TimelineId),
     795              : 
     796              :     #[error("HasUnarchivedChildren")]
     797              :     HasUnarchivedChildren(Vec<TimelineId>),
     798              : 
     799              :     #[error("Timeline archival is already in progress")]
     800              :     AlreadyInProgress,
     801              : 
     802              :     #[error(transparent)]
     803              :     Other(anyhow::Error),
     804              : }
     805              : 
     806            0 : #[derive(thiserror::Error, Debug)]
     807              : pub(crate) enum TenantManifestError {
     808              :     #[error("Remote storage error: {0}")]
     809              :     RemoteStorage(anyhow::Error),
     810              : 
     811              :     #[error("Cancelled")]
     812              :     Cancelled,
     813              : }
     814              : 
     815              : impl From<TenantManifestError> for TimelineArchivalError {
     816            0 :     fn from(e: TenantManifestError) -> Self {
     817            0 :         match e {
     818            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     819            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     820              :         }
     821            0 :     }
     822              : }
     823              : 
     824              : impl Debug for TimelineArchivalError {
     825            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     826            0 :         match self {
     827            0 :             Self::NotFound => write!(f, "NotFound"),
     828            0 :             Self::Timeout => write!(f, "Timeout"),
     829            0 :             Self::Cancelled => write!(f, "Cancelled"),
     830            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     831            0 :             Self::HasUnarchivedChildren(c) => {
     832            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     833              :             }
     834            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     835            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     836              :         }
     837            0 :     }
     838              : }
     839              : 
     840              : pub enum SetStoppingError {
     841              :     AlreadyStopping(completion::Barrier),
     842              :     Broken,
     843              : }
     844              : 
     845              : impl Debug for SetStoppingError {
     846            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     847            0 :         match self {
     848            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     849            0 :             Self::Broken => write!(f, "Broken"),
     850              :         }
     851            0 :     }
     852              : }
     853              : 
     854              : /// Arguments to [`Tenant::create_timeline`].
     855              : ///
     856              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     857              : /// is `None`, the result of the timeline create call is not deterministic.
     858              : ///
     859              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     860              : #[derive(Debug)]
     861              : pub(crate) enum CreateTimelineParams {
     862              :     Bootstrap(CreateTimelineParamsBootstrap),
     863              :     Branch(CreateTimelineParamsBranch),
     864              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     865              : }
     866              : 
     867              : #[derive(Debug)]
     868              : pub(crate) struct CreateTimelineParamsBootstrap {
     869              :     pub(crate) new_timeline_id: TimelineId,
     870              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     871              :     pub(crate) pg_version: u32,
     872              : }
     873              : 
     874              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     875              : #[derive(Debug)]
     876              : pub(crate) struct CreateTimelineParamsBranch {
     877              :     pub(crate) new_timeline_id: TimelineId,
     878              :     pub(crate) ancestor_timeline_id: TimelineId,
     879              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     880              : }
     881              : 
     882              : #[derive(Debug)]
     883              : pub(crate) struct CreateTimelineParamsImportPgdata {
     884              :     pub(crate) new_timeline_id: TimelineId,
     885              :     pub(crate) location: import_pgdata::index_part_format::Location,
     886              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     887              : }
     888              : 
     889              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     890              : ///
     891              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     892              : ///
     893              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     894              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     895              : ///
     896              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     897              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     898              : ///
     899              : /// Notes:
     900              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     901              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     902              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     903              : ///
     904              : #[derive(Debug, Clone, PartialEq, Eq)]
     905              : pub(crate) enum CreateTimelineIdempotency {
     906              :     /// NB: special treatment, see comment in [`Self`].
     907              :     FailWithConflict,
     908              :     Bootstrap {
     909              :         pg_version: u32,
     910              :     },
     911              :     /// NB: branches always have the same `pg_version` as their ancestor.
     912              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     913              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     914              :     /// determining the child branch pg_version.
     915              :     Branch {
     916              :         ancestor_timeline_id: TimelineId,
     917              :         ancestor_start_lsn: Lsn,
     918              :     },
     919              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     920              : }
     921              : 
     922              : #[derive(Debug, Clone, PartialEq, Eq)]
     923              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     924              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     925              : }
     926              : 
     927              : /// What is returned by [`Tenant::start_creating_timeline`].
     928              : #[must_use]
     929              : enum StartCreatingTimelineResult {
     930              :     CreateGuard(TimelineCreateGuard),
     931              :     Idempotent(Arc<Timeline>),
     932              : }
     933              : 
     934              : enum TimelineInitAndSyncResult {
     935              :     ReadyToActivate(Arc<Timeline>),
     936              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     937              : }
     938              : 
     939              : impl TimelineInitAndSyncResult {
     940            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     941            0 :         match self {
     942            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     943            0 :             _ => None,
     944              :         }
     945            0 :     }
     946              : }
     947              : 
     948              : #[must_use]
     949              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     950              :     timeline: Arc<Timeline>,
     951              :     import_pgdata: import_pgdata::index_part_format::Root,
     952              :     guard: TimelineCreateGuard,
     953              : }
     954              : 
     955              : /// What is returned by [`Tenant::create_timeline`].
     956              : enum CreateTimelineResult {
     957              :     Created(Arc<Timeline>),
     958              :     Idempotent(Arc<Timeline>),
     959              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     960              :     /// we return this result, nor will this concrete object ever be added there.
     961              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     962              :     ImportSpawned(Arc<Timeline>),
     963              : }
     964              : 
     965              : impl CreateTimelineResult {
     966            0 :     fn discriminant(&self) -> &'static str {
     967            0 :         match self {
     968            0 :             Self::Created(_) => "Created",
     969            0 :             Self::Idempotent(_) => "Idempotent",
     970            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     971              :         }
     972            0 :     }
     973            0 :     fn timeline(&self) -> &Arc<Timeline> {
     974            0 :         match self {
     975            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     976            0 :         }
     977            0 :     }
     978              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     979              :     #[cfg(test)]
     980          230 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     981          230 :         match self {
     982          230 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     983          230 :         }
     984          230 :     }
     985              : }
     986              : 
     987            2 : #[derive(thiserror::Error, Debug)]
     988              : pub enum CreateTimelineError {
     989              :     #[error("creation of timeline with the given ID is in progress")]
     990              :     AlreadyCreating,
     991              :     #[error("timeline already exists with different parameters")]
     992              :     Conflict,
     993              :     #[error(transparent)]
     994              :     AncestorLsn(anyhow::Error),
     995              :     #[error("ancestor timeline is not active")]
     996              :     AncestorNotActive,
     997              :     #[error("ancestor timeline is archived")]
     998              :     AncestorArchived,
     999              :     #[error("tenant shutting down")]
    1000              :     ShuttingDown,
    1001              :     #[error(transparent)]
    1002              :     Other(#[from] anyhow::Error),
    1003              : }
    1004              : 
    1005            0 : #[derive(thiserror::Error, Debug)]
    1006              : pub enum InitdbError {
    1007              :     #[error("Operation was cancelled")]
    1008              :     Cancelled,
    1009              :     #[error(transparent)]
    1010              :     Other(anyhow::Error),
    1011              :     #[error(transparent)]
    1012              :     Inner(postgres_initdb::Error),
    1013              : }
    1014              : 
    1015              : enum CreateTimelineCause {
    1016              :     Load,
    1017              :     Delete,
    1018              : }
    1019              : 
    1020              : enum LoadTimelineCause {
    1021              :     Attach,
    1022              :     Unoffload,
    1023              :     ImportPgdata {
    1024              :         create_guard: TimelineCreateGuard,
    1025              :         activate: ActivateTimelineArgs,
    1026              :     },
    1027              : }
    1028              : 
    1029            0 : #[derive(thiserror::Error, Debug)]
    1030              : pub(crate) enum GcError {
    1031              :     // The tenant is shutting down
    1032              :     #[error("tenant shutting down")]
    1033              :     TenantCancelled,
    1034              : 
    1035              :     // The tenant is shutting down
    1036              :     #[error("timeline shutting down")]
    1037              :     TimelineCancelled,
    1038              : 
    1039              :     // The tenant is in a state inelegible to run GC
    1040              :     #[error("not active")]
    1041              :     NotActive,
    1042              : 
    1043              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1044              :     #[error("not active")]
    1045              :     BadLsn { why: String },
    1046              : 
    1047              :     // A remote storage error while scheduling updates after compaction
    1048              :     #[error(transparent)]
    1049              :     Remote(anyhow::Error),
    1050              : 
    1051              :     // An error reading while calculating GC cutoffs
    1052              :     #[error(transparent)]
    1053              :     GcCutoffs(PageReconstructError),
    1054              : 
    1055              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1056              :     #[error("timeline not found")]
    1057              :     TimelineNotFound,
    1058              : }
    1059              : 
    1060              : impl From<PageReconstructError> for GcError {
    1061            0 :     fn from(value: PageReconstructError) -> Self {
    1062            0 :         match value {
    1063            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1064            0 :             other => Self::GcCutoffs(other),
    1065              :         }
    1066            0 :     }
    1067              : }
    1068              : 
    1069              : impl From<NotInitialized> for GcError {
    1070            0 :     fn from(value: NotInitialized) -> Self {
    1071            0 :         match value {
    1072            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1073            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1074              :         }
    1075            0 :     }
    1076              : }
    1077              : 
    1078              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1079            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1080            0 :         GcError::TimelineCancelled
    1081            0 :     }
    1082              : }
    1083              : 
    1084            0 : #[derive(thiserror::Error, Debug)]
    1085              : pub(crate) enum LoadConfigError {
    1086              :     #[error("TOML deserialization error: '{0}'")]
    1087              :     DeserializeToml(#[from] toml_edit::de::Error),
    1088              : 
    1089              :     #[error("Config not found at {0}")]
    1090              :     NotFound(Utf8PathBuf),
    1091              : }
    1092              : 
    1093              : impl Tenant {
    1094              :     /// Yet another helper for timeline initialization.
    1095              :     ///
    1096              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1097              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1098              :     /// - Downloads remote index file and adds remote files to the layer map
    1099              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1100              :     ///
    1101              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1102              :     /// it is marked as Active.
    1103              :     #[allow(clippy::too_many_arguments)]
    1104            6 :     async fn timeline_init_and_sync(
    1105            6 :         self: &Arc<Self>,
    1106            6 :         timeline_id: TimelineId,
    1107            6 :         resources: TimelineResources,
    1108            6 :         mut index_part: IndexPart,
    1109            6 :         metadata: TimelineMetadata,
    1110            6 :         ancestor: Option<Arc<Timeline>>,
    1111            6 :         cause: LoadTimelineCause,
    1112            6 :         ctx: &RequestContext,
    1113            6 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1114            6 :         let tenant_id = self.tenant_shard_id;
    1115            6 : 
    1116            6 :         let import_pgdata = index_part.import_pgdata.take();
    1117            6 :         let idempotency = match &import_pgdata {
    1118            0 :             Some(import_pgdata) => {
    1119            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1120            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1121            0 :                 })
    1122              :             }
    1123              :             None => {
    1124            6 :                 if metadata.ancestor_timeline().is_none() {
    1125            4 :                     CreateTimelineIdempotency::Bootstrap {
    1126            4 :                         pg_version: metadata.pg_version(),
    1127            4 :                     }
    1128              :                 } else {
    1129            2 :                     CreateTimelineIdempotency::Branch {
    1130            2 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1131            2 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1132            2 :                     }
    1133              :                 }
    1134              :             }
    1135              :         };
    1136              : 
    1137            6 :         let timeline = self.create_timeline_struct(
    1138            6 :             timeline_id,
    1139            6 :             &metadata,
    1140            6 :             ancestor.clone(),
    1141            6 :             resources,
    1142            6 :             CreateTimelineCause::Load,
    1143            6 :             idempotency.clone(),
    1144            6 :         )?;
    1145            6 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1146            6 :         anyhow::ensure!(
    1147            6 :             disk_consistent_lsn.is_valid(),
    1148            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1149              :         );
    1150            6 :         assert_eq!(
    1151            6 :             disk_consistent_lsn,
    1152            6 :             metadata.disk_consistent_lsn(),
    1153            0 :             "these are used interchangeably"
    1154              :         );
    1155              : 
    1156            6 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1157              : 
    1158            6 :         timeline
    1159            6 :             .load_layer_map(disk_consistent_lsn, index_part)
    1160            4 :             .await
    1161            6 :             .with_context(|| {
    1162            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1163            6 :             })?;
    1164              : 
    1165            0 :         match import_pgdata {
    1166            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1167            0 :                 match cause {
    1168            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1169              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1170            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1171              :                     }
    1172              :                 }
    1173            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1174            0 :                 if !guard.insert(timeline_id) {
    1175              :                     // We should never try and load the same timeline twice during startup
    1176            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1177            0 :                 }
    1178            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1179            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1180            0 :                     owning_tenant: self.clone(),
    1181            0 :                     timeline_id,
    1182            0 :                     idempotency,
    1183            0 :                     // The users of this specific return value don't need the timline_path in there.
    1184            0 :                     timeline_path: timeline
    1185            0 :                         .conf
    1186            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1187            0 :                 };
    1188            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1189            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1190            0 :                         timeline,
    1191            0 :                         import_pgdata,
    1192            0 :                         guard: timeline_create_guard,
    1193            0 :                     },
    1194            0 :                 ))
    1195              :             }
    1196              :             Some(_) | None => {
    1197              :                 {
    1198            6 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1199            6 :                     match timelines_accessor.entry(timeline_id) {
    1200              :                         // We should never try and load the same timeline twice during startup
    1201              :                         Entry::Occupied(_) => {
    1202            0 :                             unreachable!(
    1203            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1204            0 :                         );
    1205              :                         }
    1206            6 :                         Entry::Vacant(v) => {
    1207            6 :                             v.insert(Arc::clone(&timeline));
    1208            6 :                             timeline.maybe_spawn_flush_loop();
    1209            6 :                         }
    1210            6 :                     }
    1211            6 :                 }
    1212            6 : 
    1213            6 :                 // Sanity check: a timeline should have some content.
    1214            6 :                 anyhow::ensure!(
    1215            6 :                     ancestor.is_some()
    1216            4 :                         || timeline
    1217            4 :                             .layers
    1218            4 :                             .read()
    1219            0 :                             .await
    1220            4 :                             .layer_map()
    1221            4 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1222            4 :                             .iter_historic_layers()
    1223            4 :                             .next()
    1224            4 :                             .is_some(),
    1225            0 :                     "Timeline has no ancestor and no layer files"
    1226              :                 );
    1227              : 
    1228            6 :                 match cause {
    1229            6 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1230              :                     LoadTimelineCause::ImportPgdata {
    1231            0 :                         create_guard,
    1232            0 :                         activate,
    1233            0 :                     } => {
    1234            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1235            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1236            0 :                         match activate {
    1237            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1238            0 :                                 info!("activating timeline after reload from pgdata import task");
    1239            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1240              :                             }
    1241            0 :                             ActivateTimelineArgs::No => (),
    1242              :                         }
    1243            0 :                         drop(create_guard);
    1244              :                     }
    1245              :                 }
    1246              : 
    1247            6 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1248              :             }
    1249              :         }
    1250            6 :     }
    1251              : 
    1252              :     /// Attach a tenant that's available in cloud storage.
    1253              :     ///
    1254              :     /// This returns quickly, after just creating the in-memory object
    1255              :     /// Tenant struct and launching a background task to download
    1256              :     /// the remote index files.  On return, the tenant is most likely still in
    1257              :     /// Attaching state, and it will become Active once the background task
    1258              :     /// finishes. You can use wait_until_active() to wait for the task to
    1259              :     /// complete.
    1260              :     ///
    1261              :     #[allow(clippy::too_many_arguments)]
    1262            0 :     pub(crate) fn spawn(
    1263            0 :         conf: &'static PageServerConf,
    1264            0 :         tenant_shard_id: TenantShardId,
    1265            0 :         resources: TenantSharedResources,
    1266            0 :         attached_conf: AttachedTenantConf,
    1267            0 :         shard_identity: ShardIdentity,
    1268            0 :         init_order: Option<InitializationOrder>,
    1269            0 :         mode: SpawnMode,
    1270            0 :         ctx: &RequestContext,
    1271            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1272            0 :         let wal_redo_manager =
    1273            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1274              : 
    1275              :         let TenantSharedResources {
    1276            0 :             broker_client,
    1277            0 :             remote_storage,
    1278            0 :             deletion_queue_client,
    1279            0 :             l0_flush_global_state,
    1280            0 :         } = resources;
    1281            0 : 
    1282            0 :         let attach_mode = attached_conf.location.attach_mode;
    1283            0 :         let generation = attached_conf.location.generation;
    1284            0 : 
    1285            0 :         let tenant = Arc::new(Tenant::new(
    1286            0 :             TenantState::Attaching,
    1287            0 :             conf,
    1288            0 :             attached_conf,
    1289            0 :             shard_identity,
    1290            0 :             Some(wal_redo_manager),
    1291            0 :             tenant_shard_id,
    1292            0 :             remote_storage.clone(),
    1293            0 :             deletion_queue_client,
    1294            0 :             l0_flush_global_state,
    1295            0 :         ));
    1296            0 : 
    1297            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1298            0 :         // we shut down while attaching.
    1299            0 :         let attach_gate_guard = tenant
    1300            0 :             .gate
    1301            0 :             .enter()
    1302            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1303            0 : 
    1304            0 :         // Do all the hard work in the background
    1305            0 :         let tenant_clone = Arc::clone(&tenant);
    1306            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1307            0 :         task_mgr::spawn(
    1308            0 :             &tokio::runtime::Handle::current(),
    1309            0 :             TaskKind::Attach,
    1310            0 :             tenant_shard_id,
    1311            0 :             None,
    1312            0 :             "attach tenant",
    1313            0 :             async move {
    1314            0 : 
    1315            0 :                 info!(
    1316              :                     ?attach_mode,
    1317            0 :                     "Attaching tenant"
    1318              :                 );
    1319              : 
    1320            0 :                 let _gate_guard = attach_gate_guard;
    1321            0 : 
    1322            0 :                 // Is this tenant being spawned as part of process startup?
    1323            0 :                 let starting_up = init_order.is_some();
    1324            0 :                 scopeguard::defer! {
    1325            0 :                     if starting_up {
    1326            0 :                         TENANT.startup_complete.inc();
    1327            0 :                     }
    1328            0 :                 }
    1329              : 
    1330              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1331              :                 enum BrokenVerbosity {
    1332              :                     Error,
    1333              :                     Info
    1334              :                 }
    1335            0 :                 let make_broken =
    1336            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1337            0 :                         match verbosity {
    1338              :                             BrokenVerbosity::Info => {
    1339            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1340              :                             },
    1341              :                             BrokenVerbosity::Error => {
    1342            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1343              :                             }
    1344              :                         }
    1345            0 :                         t.state.send_modify(|state| {
    1346            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1347            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1348            0 :                             assert!(
    1349            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1350            0 :                                 "the attach task owns the tenant state until activation is complete"
    1351              :                             );
    1352              : 
    1353            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1354            0 :                         });
    1355            0 :                     };
    1356              : 
    1357              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1358            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1359            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1360            0 :                     return Ok(());
    1361            0 :                 }
    1362            0 : 
    1363            0 :                 let mut init_order = init_order;
    1364            0 :                 // take the completion because initial tenant loading will complete when all of
    1365            0 :                 // these tasks complete.
    1366            0 :                 let _completion = init_order
    1367            0 :                     .as_mut()
    1368            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1369            0 :                 let remote_load_completion = init_order
    1370            0 :                     .as_mut()
    1371            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1372              : 
    1373              :                 enum AttachType<'a> {
    1374              :                     /// We are attaching this tenant lazily in the background.
    1375              :                     Warmup {
    1376              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1377              :                         during_startup: bool
    1378              :                     },
    1379              :                     /// We are attaching this tenant as soon as we can, because for example an
    1380              :                     /// endpoint tried to access it.
    1381              :                     OnDemand,
    1382              :                     /// During normal operations after startup, we are attaching a tenant, and
    1383              :                     /// eager attach was requested.
    1384              :                     Normal,
    1385              :                 }
    1386              : 
    1387            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1388              :                     // Before doing any I/O, wait for at least one of:
    1389              :                     // - A client attempting to access to this tenant (on-demand loading)
    1390              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1391              : 
    1392            0 :                     tokio::select!(
    1393            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1394            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1395            0 :                             tracing::info!("Activating tenant (on-demand)");
    1396            0 :                             AttachType::OnDemand
    1397              :                         },
    1398            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1399            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1400            0 :                             tracing::info!("Activating tenant (warmup)");
    1401            0 :                             AttachType::Warmup {
    1402            0 :                                 _permit,
    1403            0 :                                 during_startup: init_order.is_some()
    1404            0 :                             }
    1405              :                         }
    1406            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1407              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1408              :                             // stayed in Activating for such a long time that shutdown found it in
    1409              :                             // that state.
    1410            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1411              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1412              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1413              :                             // just shutting down), but ensures progress.
    1414            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1415            0 :                             return Ok(());
    1416              :                         },
    1417              :                     )
    1418              :                 } else {
    1419              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1420              :                     // concurrent_tenant_warmup queue
    1421            0 :                     AttachType::Normal
    1422              :                 };
    1423              : 
    1424            0 :                 let preload = match &mode {
    1425              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1426            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1427            0 :                         let res = tenant_clone
    1428            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1429            0 :                             .await;
    1430            0 :                         match res {
    1431            0 :                             Ok(p) => Some(p),
    1432            0 :                             Err(e) => {
    1433            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1434            0 :                                 return Ok(());
    1435              :                             }
    1436              :                         }
    1437              :                     }
    1438              : 
    1439              :                 };
    1440              : 
    1441              :                 // Remote preload is complete.
    1442            0 :                 drop(remote_load_completion);
    1443            0 : 
    1444            0 : 
    1445            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1446            0 :                 let attach_start = std::time::Instant::now();
    1447            0 :                 let attached = {
    1448            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1449            0 :                     tenant_clone.attach(preload, &ctx).await
    1450              :                 };
    1451            0 :                 let attach_duration = attach_start.elapsed();
    1452            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1453            0 : 
    1454            0 :                 match attached {
    1455              :                     Ok(()) => {
    1456            0 :                         info!("attach finished, activating");
    1457            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1458              :                     }
    1459            0 :                     Err(e) => {
    1460            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1461            0 :                     }
    1462              :                 }
    1463              : 
    1464              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1465              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1466              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1467              :                 //
    1468              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1469              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1470              :                 // then warmup will wait for that before proceeding to the next tenant.
    1471            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1472            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1473            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1474            0 :                     while futs.next().await.is_some() {}
    1475            0 :                     tracing::info!("Warm-up complete");
    1476            0 :                 }
    1477              : 
    1478            0 :                 Ok(())
    1479            0 :             }
    1480            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1481              :         );
    1482            0 :         Ok(tenant)
    1483            0 :     }
    1484              : 
    1485          192 :     #[instrument(skip_all)]
    1486              :     pub(crate) async fn preload(
    1487              :         self: &Arc<Self>,
    1488              :         remote_storage: &GenericRemoteStorage,
    1489              :         cancel: CancellationToken,
    1490              :     ) -> anyhow::Result<TenantPreload> {
    1491              :         span::debug_assert_current_span_has_tenant_id();
    1492              :         // Get list of remote timelines
    1493              :         // download index files for every tenant timeline
    1494              :         info!("listing remote timelines");
    1495              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1496              :             remote_storage,
    1497              :             self.tenant_shard_id,
    1498              :             cancel.clone(),
    1499              :         )
    1500              :         .await?;
    1501              :         let (offloaded_add, tenant_manifest) =
    1502              :             match remote_timeline_client::download_tenant_manifest(
    1503              :                 remote_storage,
    1504              :                 &self.tenant_shard_id,
    1505              :                 self.generation,
    1506              :                 &cancel,
    1507              :             )
    1508              :             .await
    1509              :             {
    1510              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1511              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1512              :                     tenant_manifest,
    1513              :                 ),
    1514              :                 Err(DownloadError::NotFound) => {
    1515              :                     ("no manifest".to_string(), TenantManifest::empty())
    1516              :                 }
    1517              :                 Err(e) => Err(e)?,
    1518              :             };
    1519              : 
    1520              :         info!(
    1521              :             "found {} timelines, and {offloaded_add}",
    1522              :             remote_timeline_ids.len()
    1523              :         );
    1524              : 
    1525              :         for k in other_keys {
    1526              :             warn!("Unexpected non timeline key {k}");
    1527              :         }
    1528              : 
    1529              :         // Avoid downloading IndexPart of offloaded timelines.
    1530              :         let mut offloaded_with_prefix = HashSet::new();
    1531              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1532              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1533              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1534              :             } else {
    1535              :                 // We'll take care later of timelines in the manifest without a prefix
    1536              :             }
    1537              :         }
    1538              : 
    1539              :         let timelines = self
    1540              :             .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1541              :             .await?;
    1542              : 
    1543              :         Ok(TenantPreload {
    1544              :             tenant_manifest,
    1545              :             timelines: timelines
    1546              :                 .into_iter()
    1547            6 :                 .map(|(id, tl)| (id, Some(tl)))
    1548            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1549              :                 .collect(),
    1550              :         })
    1551              :     }
    1552              : 
    1553              :     ///
    1554              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1555              :     ///
    1556              :     /// No background tasks are started as part of this routine.
    1557              :     ///
    1558          192 :     async fn attach(
    1559          192 :         self: &Arc<Tenant>,
    1560          192 :         preload: Option<TenantPreload>,
    1561          192 :         ctx: &RequestContext,
    1562          192 :     ) -> anyhow::Result<()> {
    1563          192 :         span::debug_assert_current_span_has_tenant_id();
    1564          192 : 
    1565          192 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1566              : 
    1567          192 :         let Some(preload) = preload else {
    1568            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1569              :         };
    1570              : 
    1571          192 :         let mut offloaded_timeline_ids = HashSet::new();
    1572          192 :         let mut offloaded_timelines_list = Vec::new();
    1573          192 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1574            0 :             let timeline_id = timeline_manifest.timeline_id;
    1575            0 :             let offloaded_timeline =
    1576            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1577            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1578            0 :             offloaded_timeline_ids.insert(timeline_id);
    1579            0 :         }
    1580              :         // Complete deletions for offloaded timeline id's from manifest.
    1581              :         // The manifest will be uploaded later in this function.
    1582          192 :         offloaded_timelines_list
    1583          192 :             .retain(|(offloaded_id, offloaded)| {
    1584            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1585            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1586            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1587            0 :                 if delete {
    1588            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1589            0 :                     offloaded.defuse_for_tenant_drop();
    1590            0 :                 }
    1591            0 :                 !delete
    1592          192 :         });
    1593          192 : 
    1594          192 :         let mut timelines_to_resume_deletions = vec![];
    1595          192 : 
    1596          192 :         let mut remote_index_and_client = HashMap::new();
    1597          192 :         let mut timeline_ancestors = HashMap::new();
    1598          192 :         let mut existent_timelines = HashSet::new();
    1599          198 :         for (timeline_id, preload) in preload.timelines {
    1600            6 :             let Some(preload) = preload else { continue };
    1601              :             // This is an invariant of the `preload` function's API
    1602            6 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1603            6 :             let index_part = match preload.index_part {
    1604            6 :                 Ok(i) => {
    1605            6 :                     debug!("remote index part exists for timeline {timeline_id}");
    1606              :                     // We found index_part on the remote, this is the standard case.
    1607            6 :                     existent_timelines.insert(timeline_id);
    1608            6 :                     i
    1609              :                 }
    1610              :                 Err(DownloadError::NotFound) => {
    1611              :                     // There is no index_part on the remote. We only get here
    1612              :                     // if there is some prefix for the timeline in the remote storage.
    1613              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1614              :                     // remnant from a prior incomplete creation or deletion attempt.
    1615              :                     // Delete the local directory as the deciding criterion for a
    1616              :                     // timeline's existence is presence of index_part.
    1617            0 :                     info!(%timeline_id, "index_part not found on remote");
    1618            0 :                     continue;
    1619              :                 }
    1620            0 :                 Err(DownloadError::Fatal(why)) => {
    1621            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1622            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1623            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1624            0 :                     anyhow::bail!(why.to_string());
    1625              :                 }
    1626            0 :                 Err(e) => {
    1627            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1628            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1629            0 :                     // as it might be a temporary issue and we don't want to re-download
    1630            0 :                     // everything after it resolves.
    1631            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1632              : 
    1633            0 :                     existent_timelines.insert(timeline_id);
    1634            0 :                     continue;
    1635              :                 }
    1636              :             };
    1637            6 :             match index_part {
    1638            6 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1639            6 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1640            6 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1641            6 :                 }
    1642            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1643            0 :                     info!(
    1644            0 :                         "timeline {} is deleted, picking to resume deletion",
    1645              :                         timeline_id
    1646              :                     );
    1647            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1648              :                 }
    1649              :             }
    1650              :         }
    1651              : 
    1652          192 :         let mut gc_blocks = HashMap::new();
    1653              : 
    1654              :         // For every timeline, download the metadata file, scan the local directory,
    1655              :         // and build a layer map that contains an entry for each remote and local
    1656              :         // layer file.
    1657          192 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1658          198 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1659            6 :             let (index_part, remote_client) = remote_index_and_client
    1660            6 :                 .remove(&timeline_id)
    1661            6 :                 .expect("just put it in above");
    1662              : 
    1663            6 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1664              :                 // could just filter these away, but it helps while testing
    1665            0 :                 anyhow::ensure!(
    1666            0 :                     !blocking.reasons.is_empty(),
    1667            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1668              :                 );
    1669            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1670            0 :                 assert!(prev.is_none());
    1671            6 :             }
    1672              : 
    1673              :             // TODO again handle early failure
    1674            6 :             let effect = self
    1675            6 :                 .load_remote_timeline(
    1676            6 :                     timeline_id,
    1677            6 :                     index_part,
    1678            6 :                     remote_metadata,
    1679            6 :                     TimelineResources {
    1680            6 :                         remote_client,
    1681            6 :                         timeline_get_throttle: self.timeline_get_throttle.clone(),
    1682            6 :                         l0_flush_global_state: self.l0_flush_global_state.clone(),
    1683            6 :                     },
    1684            6 :                     LoadTimelineCause::Attach,
    1685            6 :                     ctx,
    1686            6 :                 )
    1687            8 :                 .await
    1688            6 :                 .with_context(|| {
    1689            0 :                     format!(
    1690            0 :                         "failed to load remote timeline {} for tenant {}",
    1691            0 :                         timeline_id, self.tenant_shard_id
    1692            0 :                     )
    1693            6 :                 })?;
    1694              : 
    1695            6 :             match effect {
    1696            6 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1697            6 :                     // activation happens later, on Tenant::activate
    1698            6 :                 }
    1699              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1700              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1701            0 :                         timeline,
    1702            0 :                         import_pgdata,
    1703            0 :                         guard,
    1704            0 :                     },
    1705            0 :                 ) => {
    1706            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1707            0 :                         timeline,
    1708            0 :                         import_pgdata,
    1709            0 :                         ActivateTimelineArgs::No,
    1710            0 :                         guard,
    1711            0 :                     ));
    1712            0 :                 }
    1713              :             }
    1714              :         }
    1715              : 
    1716              :         // Walk through deleted timelines, resume deletion
    1717          192 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1718            0 :             remote_timeline_client
    1719            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1720            0 :                 .context("init queue stopped")
    1721            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1722              : 
    1723            0 :             DeleteTimelineFlow::resume_deletion(
    1724            0 :                 Arc::clone(self),
    1725            0 :                 timeline_id,
    1726            0 :                 &index_part.metadata,
    1727            0 :                 remote_timeline_client,
    1728            0 :             )
    1729            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1730            0 :             .await
    1731            0 :             .context("resume_deletion")
    1732            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1733              :         }
    1734          192 :         let needs_manifest_upload =
    1735          192 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1736          192 :         {
    1737          192 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1738          192 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1739          192 :         }
    1740          192 :         if needs_manifest_upload {
    1741            0 :             self.store_tenant_manifest().await?;
    1742          192 :         }
    1743              : 
    1744              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1745              :         // IndexPart is the source of truth.
    1746          192 :         self.clean_up_timelines(&existent_timelines)?;
    1747              : 
    1748          192 :         self.gc_block.set_scanned(gc_blocks);
    1749          192 : 
    1750          192 :         fail::fail_point!("attach-before-activate", |_| {
    1751            0 :             anyhow::bail!("attach-before-activate");
    1752          192 :         });
    1753          192 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1754              : 
    1755          192 :         info!("Done");
    1756              : 
    1757          192 :         Ok(())
    1758          192 :     }
    1759              : 
    1760              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1761              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1762              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1763          192 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1764          192 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1765              : 
    1766          192 :         let entries = match timelines_dir.read_dir_utf8() {
    1767          192 :             Ok(d) => d,
    1768            0 :             Err(e) => {
    1769            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1770            0 :                     return Ok(());
    1771              :                 } else {
    1772            0 :                     return Err(e).context("list timelines directory for tenant");
    1773              :                 }
    1774              :             }
    1775              :         };
    1776              : 
    1777          200 :         for entry in entries {
    1778            8 :             let entry = entry.context("read timeline dir entry")?;
    1779            8 :             let entry_path = entry.path();
    1780              : 
    1781            8 :             let purge = if crate::is_temporary(entry_path)
    1782              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1783            8 :                 || is_uninit_mark(entry_path)
    1784            8 :                 || crate::is_delete_mark(entry_path)
    1785              :             {
    1786            0 :                 true
    1787              :             } else {
    1788            8 :                 match TimelineId::try_from(entry_path.file_name()) {
    1789            8 :                     Ok(i) => {
    1790            8 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1791            8 :                         !existent_timelines.contains(&i)
    1792              :                     }
    1793            0 :                     Err(e) => {
    1794            0 :                         tracing::warn!(
    1795            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1796              :                         );
    1797              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1798            0 :                         false
    1799              :                     }
    1800              :                 }
    1801              :             };
    1802              : 
    1803            8 :             if purge {
    1804            2 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1805            2 :                 if let Err(e) = match entry.file_type() {
    1806            2 :                     Ok(t) => if t.is_dir() {
    1807            2 :                         std::fs::remove_dir_all(entry_path)
    1808              :                     } else {
    1809            0 :                         std::fs::remove_file(entry_path)
    1810              :                     }
    1811            2 :                     .or_else(fs_ext::ignore_not_found),
    1812            0 :                     Err(e) => Err(e),
    1813              :                 } {
    1814            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1815            2 :                 }
    1816            6 :             }
    1817              :         }
    1818              : 
    1819          192 :         Ok(())
    1820          192 :     }
    1821              : 
    1822              :     /// Get sum of all remote timelines sizes
    1823              :     ///
    1824              :     /// This function relies on the index_part instead of listing the remote storage
    1825            0 :     pub fn remote_size(&self) -> u64 {
    1826            0 :         let mut size = 0;
    1827              : 
    1828            0 :         for timeline in self.list_timelines() {
    1829            0 :             size += timeline.remote_client.get_remote_physical_size();
    1830            0 :         }
    1831              : 
    1832            0 :         size
    1833            0 :     }
    1834              : 
    1835            6 :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1836              :     async fn load_remote_timeline(
    1837              :         self: &Arc<Self>,
    1838              :         timeline_id: TimelineId,
    1839              :         index_part: IndexPart,
    1840              :         remote_metadata: TimelineMetadata,
    1841              :         resources: TimelineResources,
    1842              :         cause: LoadTimelineCause,
    1843              :         ctx: &RequestContext,
    1844              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1845              :         span::debug_assert_current_span_has_tenant_id();
    1846              : 
    1847              :         info!("downloading index file for timeline {}", timeline_id);
    1848              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1849              :             .await
    1850              :             .context("Failed to create new timeline directory")?;
    1851              : 
    1852              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1853              :             let timelines = self.timelines.lock().unwrap();
    1854              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1855            0 :                 || {
    1856            0 :                     anyhow::anyhow!(
    1857            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1858            0 :                     )
    1859            0 :                 },
    1860              :             )?))
    1861              :         } else {
    1862              :             None
    1863              :         };
    1864              : 
    1865              :         self.timeline_init_and_sync(
    1866              :             timeline_id,
    1867              :             resources,
    1868              :             index_part,
    1869              :             remote_metadata,
    1870              :             ancestor,
    1871              :             cause,
    1872              :             ctx,
    1873              :         )
    1874              :         .await
    1875              :     }
    1876              : 
    1877          192 :     async fn load_timelines_metadata(
    1878          192 :         self: &Arc<Tenant>,
    1879          192 :         timeline_ids: HashSet<TimelineId>,
    1880          192 :         remote_storage: &GenericRemoteStorage,
    1881          192 :         cancel: CancellationToken,
    1882          192 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1883          192 :         let mut part_downloads = JoinSet::new();
    1884          198 :         for timeline_id in timeline_ids {
    1885            6 :             let cancel_clone = cancel.clone();
    1886            6 :             part_downloads.spawn(
    1887            6 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1888            6 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1889              :             );
    1890              :         }
    1891              : 
    1892          192 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1893              : 
    1894              :         loop {
    1895          198 :             tokio::select!(
    1896          198 :                 next = part_downloads.join_next() => {
    1897          198 :                     match next {
    1898            6 :                         Some(result) => {
    1899            6 :                             let preload = result.context("join preload task")?;
    1900            6 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1901              :                         },
    1902              :                         None => {
    1903          192 :                             break;
    1904              :                         }
    1905              :                     }
    1906              :                 },
    1907          198 :                 _ = cancel.cancelled() => {
    1908            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1909              :                 }
    1910              :             )
    1911              :         }
    1912              : 
    1913          192 :         Ok(timeline_preloads)
    1914          192 :     }
    1915              : 
    1916            6 :     fn build_timeline_client(
    1917            6 :         &self,
    1918            6 :         timeline_id: TimelineId,
    1919            6 :         remote_storage: GenericRemoteStorage,
    1920            6 :     ) -> RemoteTimelineClient {
    1921            6 :         RemoteTimelineClient::new(
    1922            6 :             remote_storage.clone(),
    1923            6 :             self.deletion_queue_client.clone(),
    1924            6 :             self.conf,
    1925            6 :             self.tenant_shard_id,
    1926            6 :             timeline_id,
    1927            6 :             self.generation,
    1928            6 :             &self.tenant_conf.load().location,
    1929            6 :         )
    1930            6 :     }
    1931              : 
    1932            6 :     fn load_timeline_metadata(
    1933            6 :         self: &Arc<Tenant>,
    1934            6 :         timeline_id: TimelineId,
    1935            6 :         remote_storage: GenericRemoteStorage,
    1936            6 :         cancel: CancellationToken,
    1937            6 :     ) -> impl Future<Output = TimelinePreload> {
    1938            6 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1939            6 :         async move {
    1940            6 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1941            6 :             debug!("starting index part download");
    1942              : 
    1943           10 :             let index_part = client.download_index_file(&cancel).await;
    1944              : 
    1945            6 :             debug!("finished index part download");
    1946              : 
    1947            6 :             TimelinePreload {
    1948            6 :                 client,
    1949            6 :                 timeline_id,
    1950            6 :                 index_part,
    1951            6 :             }
    1952            6 :         }
    1953            6 :     }
    1954              : 
    1955            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1956            0 :         timeline_id: TimelineId,
    1957            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1958            0 :     ) -> Result<(), TimelineArchivalError> {
    1959            0 :         let children: Vec<TimelineId> = timelines
    1960            0 :             .iter()
    1961            0 :             .filter_map(|(id, entry)| {
    1962            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1963            0 :                     return None;
    1964            0 :                 }
    1965            0 :                 if entry.is_archived() == Some(true) {
    1966            0 :                     return None;
    1967            0 :                 }
    1968            0 :                 Some(*id)
    1969            0 :             })
    1970            0 :             .collect();
    1971            0 : 
    1972            0 :         if !children.is_empty() {
    1973            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1974            0 :         }
    1975            0 :         Ok(())
    1976            0 :     }
    1977              : 
    1978            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1979            0 :         ancestor_timeline_id: TimelineId,
    1980            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1981            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1982            0 :             '_,
    1983            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1984            0 :         >,
    1985            0 :     ) -> Result<(), TimelineArchivalError> {
    1986            0 :         let has_archived_parent =
    1987            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    1988            0 :                 ancestor_timeline.is_archived() == Some(true)
    1989            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    1990            0 :                 true
    1991              :             } else {
    1992            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    1993            0 :                 if cfg!(debug_assertions) {
    1994            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    1995            0 :                 }
    1996            0 :                 return Err(TimelineArchivalError::NotFound);
    1997              :             };
    1998            0 :         if has_archived_parent {
    1999            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2000            0 :                 ancestor_timeline_id,
    2001            0 :             ));
    2002            0 :         }
    2003            0 :         Ok(())
    2004            0 :     }
    2005              : 
    2006            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2007            0 :         timeline: &Arc<Timeline>,
    2008            0 :     ) -> Result<(), TimelineArchivalError> {
    2009            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2010            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2011            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2012            0 :                     ancestor_timeline.timeline_id,
    2013            0 :                 ));
    2014            0 :             }
    2015            0 :         }
    2016            0 :         Ok(())
    2017            0 :     }
    2018              : 
    2019              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2020              :     ///
    2021              :     /// Counterpart to [`offload_timeline`].
    2022            0 :     async fn unoffload_timeline(
    2023            0 :         self: &Arc<Self>,
    2024            0 :         timeline_id: TimelineId,
    2025            0 :         broker_client: storage_broker::BrokerClientChannel,
    2026            0 :         ctx: RequestContext,
    2027            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2028            0 :         info!("unoffloading timeline");
    2029              : 
    2030              :         // We activate the timeline below manually, so this must be called on an active timeline.
    2031              :         // We expect callers of this function to ensure this.
    2032            0 :         match self.current_state() {
    2033              :             TenantState::Activating { .. }
    2034              :             | TenantState::Attaching
    2035              :             | TenantState::Broken { .. } => {
    2036            0 :                 panic!("Timeline expected to be active")
    2037              :             }
    2038            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2039            0 :             TenantState::Active => {}
    2040            0 :         }
    2041            0 :         let cancel = self.cancel.clone();
    2042            0 : 
    2043            0 :         // Protect against concurrent attempts to use this TimelineId
    2044            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2045            0 :         let allow_offloaded = true;
    2046            0 :         let _create_guard = self
    2047            0 :             .create_timeline_create_guard(
    2048            0 :                 timeline_id,
    2049            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2050            0 :                 allow_offloaded,
    2051            0 :             )
    2052            0 :             .map_err(|err| match err {
    2053            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2054              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2055            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2056              :                 }
    2057            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2058            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2059            0 :             })?;
    2060              : 
    2061            0 :         let timeline_preload = self
    2062            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    2063            0 :             .await;
    2064              : 
    2065            0 :         let index_part = match timeline_preload.index_part {
    2066            0 :             Ok(index_part) => {
    2067            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2068            0 :                 index_part
    2069              :             }
    2070              :             Err(DownloadError::NotFound) => {
    2071            0 :                 error!(%timeline_id, "index_part not found on remote");
    2072            0 :                 return Err(TimelineArchivalError::NotFound);
    2073              :             }
    2074            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2075            0 :             Err(e) => {
    2076            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2077            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2078            0 :                 return Err(TimelineArchivalError::Other(
    2079            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2080            0 :                 ));
    2081              :             }
    2082              :         };
    2083            0 :         let index_part = match index_part {
    2084            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2085            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2086            0 :                 info!("timeline is deleted according to index_part.json");
    2087            0 :                 return Err(TimelineArchivalError::NotFound);
    2088              :             }
    2089              :         };
    2090            0 :         let remote_metadata = index_part.metadata.clone();
    2091            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2092            0 :         self.load_remote_timeline(
    2093            0 :             timeline_id,
    2094            0 :             index_part,
    2095            0 :             remote_metadata,
    2096            0 :             timeline_resources,
    2097            0 :             LoadTimelineCause::Unoffload,
    2098            0 :             &ctx,
    2099            0 :         )
    2100            0 :         .await
    2101            0 :         .with_context(|| {
    2102            0 :             format!(
    2103            0 :                 "failed to load remote timeline {} for tenant {}",
    2104            0 :                 timeline_id, self.tenant_shard_id
    2105            0 :             )
    2106            0 :         })
    2107            0 :         .map_err(TimelineArchivalError::Other)?;
    2108              : 
    2109            0 :         let timeline = {
    2110            0 :             let timelines = self.timelines.lock().unwrap();
    2111            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2112            0 :                 warn!("timeline not available directly after attach");
    2113              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2114              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2115            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2116            0 :                     "timeline not available directly after attach"
    2117            0 :                 )));
    2118              :             };
    2119            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2120            0 :             match offloaded_timelines.remove(&timeline_id) {
    2121            0 :                 Some(offloaded) => {
    2122            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2123            0 :                 }
    2124            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2125              :             }
    2126              : 
    2127            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2128            0 : 
    2129            0 :             Arc::clone(timeline)
    2130            0 :         };
    2131            0 : 
    2132            0 :         // Upload new list of offloaded timelines to S3
    2133            0 :         self.store_tenant_manifest().await?;
    2134              : 
    2135              :         // Activate the timeline (if it makes sense)
    2136            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2137            0 :             let background_jobs_can_start = None;
    2138            0 :             timeline.activate(
    2139            0 :                 self.clone(),
    2140            0 :                 broker_client.clone(),
    2141            0 :                 background_jobs_can_start,
    2142            0 :                 &ctx,
    2143            0 :             );
    2144            0 :         }
    2145              : 
    2146            0 :         info!("timeline unoffloading complete");
    2147            0 :         Ok(timeline)
    2148            0 :     }
    2149              : 
    2150            0 :     pub(crate) async fn apply_timeline_archival_config(
    2151            0 :         self: &Arc<Self>,
    2152            0 :         timeline_id: TimelineId,
    2153            0 :         new_state: TimelineArchivalState,
    2154            0 :         broker_client: storage_broker::BrokerClientChannel,
    2155            0 :         ctx: RequestContext,
    2156            0 :     ) -> Result<(), TimelineArchivalError> {
    2157            0 :         info!("setting timeline archival config");
    2158              :         // First part: figure out what is needed to do, and do validation
    2159            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2160            0 :             let timelines = self.timelines.lock().unwrap();
    2161              : 
    2162            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2163            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2164            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2165            0 :                     return Err(TimelineArchivalError::NotFound);
    2166              :                 };
    2167            0 :                 if new_state == TimelineArchivalState::Archived {
    2168              :                     // It's offloaded already, so nothing to do
    2169            0 :                     return Ok(());
    2170            0 :                 }
    2171            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2172            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2173            0 :                         ancestor_timeline_id,
    2174            0 :                         &timelines,
    2175            0 :                         &offloaded_timelines,
    2176            0 :                     )?;
    2177            0 :                 }
    2178            0 :                 break 'outer None;
    2179              :             };
    2180              : 
    2181              :             // Do some validation. We release the timelines lock below, so there is potential
    2182              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2183              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2184            0 :             match new_state {
    2185              :                 TimelineArchivalState::Unarchived => {
    2186            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2187              :                 }
    2188              :                 TimelineArchivalState::Archived => {
    2189            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2190              :                 }
    2191              :             }
    2192            0 :             Some(Arc::clone(timeline))
    2193              :         };
    2194              : 
    2195              :         // Second part: unoffload timeline (if needed)
    2196            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2197            0 :             timeline
    2198              :         } else {
    2199              :             // Turn offloaded timeline into a non-offloaded one
    2200            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2201            0 :                 .await?
    2202              :         };
    2203              : 
    2204              :         // Third part: upload new timeline archival state and block until it is present in S3
    2205            0 :         let upload_needed = match timeline
    2206            0 :             .remote_client
    2207            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2208              :         {
    2209            0 :             Ok(upload_needed) => upload_needed,
    2210            0 :             Err(e) => {
    2211            0 :                 if timeline.cancel.is_cancelled() {
    2212            0 :                     return Err(TimelineArchivalError::Cancelled);
    2213              :                 } else {
    2214            0 :                     return Err(TimelineArchivalError::Other(e));
    2215              :                 }
    2216              :             }
    2217              :         };
    2218              : 
    2219            0 :         if upload_needed {
    2220            0 :             info!("Uploading new state");
    2221              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2222            0 :             let Ok(v) =
    2223            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2224              :             else {
    2225            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2226            0 :                 return Err(TimelineArchivalError::Timeout);
    2227              :             };
    2228            0 :             v.map_err(|e| match e {
    2229            0 :                 WaitCompletionError::NotInitialized(e) => {
    2230            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2231              :                 }
    2232              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2233            0 :                     TimelineArchivalError::Cancelled
    2234              :                 }
    2235            0 :             })?;
    2236            0 :         }
    2237            0 :         Ok(())
    2238            0 :     }
    2239              : 
    2240            2 :     pub fn get_offloaded_timeline(
    2241            2 :         &self,
    2242            2 :         timeline_id: TimelineId,
    2243            2 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2244            2 :         self.timelines_offloaded
    2245            2 :             .lock()
    2246            2 :             .unwrap()
    2247            2 :             .get(&timeline_id)
    2248            2 :             .map(Arc::clone)
    2249            2 :             .ok_or(GetTimelineError::NotFound {
    2250            2 :                 tenant_id: self.tenant_shard_id,
    2251            2 :                 timeline_id,
    2252            2 :             })
    2253            2 :     }
    2254              : 
    2255            4 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2256            4 :         self.tenant_shard_id
    2257            4 :     }
    2258              : 
    2259              :     /// Get Timeline handle for given Neon timeline ID.
    2260              :     /// This function is idempotent. It doesn't change internal state in any way.
    2261          222 :     pub fn get_timeline(
    2262          222 :         &self,
    2263          222 :         timeline_id: TimelineId,
    2264          222 :         active_only: bool,
    2265          222 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2266          222 :         let timelines_accessor = self.timelines.lock().unwrap();
    2267          222 :         let timeline = timelines_accessor
    2268          222 :             .get(&timeline_id)
    2269          222 :             .ok_or(GetTimelineError::NotFound {
    2270          222 :                 tenant_id: self.tenant_shard_id,
    2271          222 :                 timeline_id,
    2272          222 :             })?;
    2273              : 
    2274          220 :         if active_only && !timeline.is_active() {
    2275            0 :             Err(GetTimelineError::NotActive {
    2276            0 :                 tenant_id: self.tenant_shard_id,
    2277            0 :                 timeline_id,
    2278            0 :                 state: timeline.current_state(),
    2279            0 :             })
    2280              :         } else {
    2281          220 :             Ok(Arc::clone(timeline))
    2282              :         }
    2283          222 :     }
    2284              : 
    2285              :     /// Lists timelines the tenant contains.
    2286              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2287            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2288            0 :         self.timelines
    2289            0 :             .lock()
    2290            0 :             .unwrap()
    2291            0 :             .values()
    2292            0 :             .map(Arc::clone)
    2293            0 :             .collect()
    2294            0 :     }
    2295              : 
    2296              :     /// Lists timelines the tenant manages, including offloaded ones.
    2297              :     ///
    2298              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2299            0 :     pub fn list_timelines_and_offloaded(
    2300            0 :         &self,
    2301            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2302            0 :         let timelines = self
    2303            0 :             .timelines
    2304            0 :             .lock()
    2305            0 :             .unwrap()
    2306            0 :             .values()
    2307            0 :             .map(Arc::clone)
    2308            0 :             .collect();
    2309            0 :         let offloaded = self
    2310            0 :             .timelines_offloaded
    2311            0 :             .lock()
    2312            0 :             .unwrap()
    2313            0 :             .values()
    2314            0 :             .map(Arc::clone)
    2315            0 :             .collect();
    2316            0 :         (timelines, offloaded)
    2317            0 :     }
    2318              : 
    2319            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2320            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2321            0 :     }
    2322              : 
    2323              :     /// This is used by tests & import-from-basebackup.
    2324              :     ///
    2325              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2326              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2327              :     ///
    2328              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2329              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2330              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2331              :     /// to the [`Tenant::timelines`].
    2332              :     ///
    2333              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2334          184 :     pub(crate) async fn create_empty_timeline(
    2335          184 :         self: &Arc<Self>,
    2336          184 :         new_timeline_id: TimelineId,
    2337          184 :         initdb_lsn: Lsn,
    2338          184 :         pg_version: u32,
    2339          184 :         _ctx: &RequestContext,
    2340          184 :     ) -> anyhow::Result<UninitializedTimeline> {
    2341          184 :         anyhow::ensure!(
    2342          184 :             self.is_active(),
    2343            0 :             "Cannot create empty timelines on inactive tenant"
    2344              :         );
    2345              : 
    2346              :         // Protect against concurrent attempts to use this TimelineId
    2347          184 :         let create_guard = match self
    2348          184 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2349          174 :             .await?
    2350              :         {
    2351          182 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2352              :             StartCreatingTimelineResult::Idempotent(_) => {
    2353            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2354              :             }
    2355              :         };
    2356              : 
    2357          182 :         let new_metadata = TimelineMetadata::new(
    2358          182 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2359          182 :             // make it valid, before calling finish_creation()
    2360          182 :             Lsn(0),
    2361          182 :             None,
    2362          182 :             None,
    2363          182 :             Lsn(0),
    2364          182 :             initdb_lsn,
    2365          182 :             initdb_lsn,
    2366          182 :             pg_version,
    2367          182 :         );
    2368          182 :         self.prepare_new_timeline(
    2369          182 :             new_timeline_id,
    2370          182 :             &new_metadata,
    2371          182 :             create_guard,
    2372          182 :             initdb_lsn,
    2373          182 :             None,
    2374          182 :         )
    2375            0 :         .await
    2376          184 :     }
    2377              : 
    2378              :     /// Helper for unit tests to create an empty timeline.
    2379              :     ///
    2380              :     /// The timeline is has state value `Active` but its background loops are not running.
    2381              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2382              :     // Our current tests don't need the background loops.
    2383              :     #[cfg(test)]
    2384          174 :     pub async fn create_test_timeline(
    2385          174 :         self: &Arc<Self>,
    2386          174 :         new_timeline_id: TimelineId,
    2387          174 :         initdb_lsn: Lsn,
    2388          174 :         pg_version: u32,
    2389          174 :         ctx: &RequestContext,
    2390          174 :     ) -> anyhow::Result<Arc<Timeline>> {
    2391          174 :         let uninit_tl = self
    2392          174 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2393          166 :             .await?;
    2394          174 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2395          174 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2396              : 
    2397              :         // Setup minimum keys required for the timeline to be usable.
    2398          174 :         let mut modification = tline.begin_modification(initdb_lsn);
    2399          174 :         modification
    2400          174 :             .init_empty_test_timeline()
    2401          174 :             .context("init_empty_test_timeline")?;
    2402          174 :         modification
    2403          174 :             .commit(ctx)
    2404          168 :             .await
    2405          174 :             .context("commit init_empty_test_timeline modification")?;
    2406              : 
    2407              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2408          174 :         tline.maybe_spawn_flush_loop();
    2409          174 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2410              : 
    2411              :         // Make sure the freeze_and_flush reaches remote storage.
    2412          174 :         tline.remote_client.wait_completion().await.unwrap();
    2413              : 
    2414          174 :         let tl = uninit_tl.finish_creation()?;
    2415              :         // The non-test code would call tl.activate() here.
    2416          174 :         tl.set_state(TimelineState::Active);
    2417          174 :         Ok(tl)
    2418          174 :     }
    2419              : 
    2420              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2421              :     #[cfg(test)]
    2422              :     #[allow(clippy::too_many_arguments)]
    2423           32 :     pub async fn create_test_timeline_with_layers(
    2424           32 :         self: &Arc<Self>,
    2425           32 :         new_timeline_id: TimelineId,
    2426           32 :         initdb_lsn: Lsn,
    2427           32 :         pg_version: u32,
    2428           32 :         ctx: &RequestContext,
    2429           32 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2430           32 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2431           32 :         end_lsn: Lsn,
    2432           32 :     ) -> anyhow::Result<Arc<Timeline>> {
    2433              :         use checks::check_valid_layermap;
    2434              :         use itertools::Itertools;
    2435              : 
    2436           32 :         let tline = self
    2437           32 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2438           94 :             .await?;
    2439           32 :         tline.force_advance_lsn(end_lsn);
    2440          100 :         for deltas in delta_layer_desc {
    2441           68 :             tline
    2442           68 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2443          204 :                 .await?;
    2444              :         }
    2445           80 :         for (lsn, images) in image_layer_desc {
    2446           48 :             tline
    2447           48 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2448          294 :                 .await?;
    2449              :         }
    2450           32 :         let layer_names = tline
    2451           32 :             .layers
    2452           32 :             .read()
    2453            0 :             .await
    2454           32 :             .layer_map()
    2455           32 :             .unwrap()
    2456           32 :             .iter_historic_layers()
    2457          148 :             .map(|layer| layer.layer_name())
    2458           32 :             .collect_vec();
    2459           32 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2460            0 :             bail!("invalid layermap: {err}");
    2461           32 :         }
    2462           32 :         Ok(tline)
    2463           32 :     }
    2464              : 
    2465              :     /// Create a new timeline.
    2466              :     ///
    2467              :     /// Returns the new timeline ID and reference to its Timeline object.
    2468              :     ///
    2469              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2470              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2471              :     #[allow(clippy::too_many_arguments)]
    2472            0 :     pub(crate) async fn create_timeline(
    2473            0 :         self: &Arc<Tenant>,
    2474            0 :         params: CreateTimelineParams,
    2475            0 :         broker_client: storage_broker::BrokerClientChannel,
    2476            0 :         ctx: &RequestContext,
    2477            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2478            0 :         if !self.is_active() {
    2479            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2480            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2481              :             } else {
    2482            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2483            0 :                     "Cannot create timelines on inactive tenant"
    2484            0 :                 )));
    2485              :             }
    2486            0 :         }
    2487              : 
    2488            0 :         let _gate = self
    2489            0 :             .gate
    2490            0 :             .enter()
    2491            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2492              : 
    2493            0 :         let result: CreateTimelineResult = match params {
    2494              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2495            0 :                 new_timeline_id,
    2496            0 :                 existing_initdb_timeline_id,
    2497            0 :                 pg_version,
    2498            0 :             }) => {
    2499            0 :                 self.bootstrap_timeline(
    2500            0 :                     new_timeline_id,
    2501            0 :                     pg_version,
    2502            0 :                     existing_initdb_timeline_id,
    2503            0 :                     ctx,
    2504            0 :                 )
    2505            0 :                 .await?
    2506              :             }
    2507              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2508            0 :                 new_timeline_id,
    2509            0 :                 ancestor_timeline_id,
    2510            0 :                 mut ancestor_start_lsn,
    2511              :             }) => {
    2512            0 :                 let ancestor_timeline = self
    2513            0 :                     .get_timeline(ancestor_timeline_id, false)
    2514            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2515              : 
    2516              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2517              :                 // ready for other purposes either.
    2518            0 :                 if !ancestor_timeline.is_active() {
    2519            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2520            0 :                 }
    2521            0 : 
    2522            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2523            0 :                     info!("tried to branch archived timeline");
    2524            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2525            0 :                 }
    2526              : 
    2527            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2528            0 :                     *lsn = lsn.align();
    2529            0 : 
    2530            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2531            0 :                     if ancestor_ancestor_lsn > *lsn {
    2532              :                         // can we safely just branch from the ancestor instead?
    2533            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2534            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2535            0 :                             lsn,
    2536            0 :                             ancestor_timeline_id,
    2537            0 :                             ancestor_ancestor_lsn,
    2538            0 :                         )));
    2539            0 :                     }
    2540            0 : 
    2541            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2542            0 :                     // to the requested branch point. The repository code itself doesn't
    2543            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2544            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2545            0 :                     // sizes etc. and that would get confused if the previous page versions
    2546            0 :                     // are not in the repository yet.
    2547            0 :                     ancestor_timeline
    2548            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    2549            0 :                         .await
    2550            0 :                         .map_err(|e| match e {
    2551            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2552            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2553              :                             }
    2554            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2555            0 :                         })?;
    2556            0 :                 }
    2557              : 
    2558            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2559            0 :                     .await?
    2560              :             }
    2561            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2562            0 :                 self.create_timeline_import_pgdata(
    2563            0 :                     params,
    2564            0 :                     ActivateTimelineArgs::Yes {
    2565            0 :                         broker_client: broker_client.clone(),
    2566            0 :                     },
    2567            0 :                     ctx,
    2568            0 :                 )
    2569            0 :                 .await?
    2570              :             }
    2571              :         };
    2572              : 
    2573              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2574              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2575              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2576              :         //
    2577              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2578              :         // assume that, because they can see the timeline via API, that the creation is done and
    2579              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2580              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2581              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2582              :         //
    2583              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2584              :         // creation API until it returns success. Only then is durability guaranteed.
    2585            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2586            0 :         result
    2587            0 :             .timeline()
    2588            0 :             .remote_client
    2589            0 :             .wait_completion()
    2590            0 :             .await
    2591            0 :             .map_err(|e| match e {
    2592              :                 WaitCompletionError::NotInitialized(
    2593            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2594            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2595            0 :                 e => CreateTimelineError::Other(e.into()),
    2596            0 :             })
    2597            0 :             .context("wait for timeline initial uploads to complete")?;
    2598              : 
    2599              :         // The creating task is responsible for activating the timeline.
    2600              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2601              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2602            0 :         let activated_timeline = match result {
    2603            0 :             CreateTimelineResult::Created(timeline) => {
    2604            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2605            0 :                 timeline
    2606              :             }
    2607            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2608            0 :                 info!(
    2609            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2610              :                 );
    2611            0 :                 timeline
    2612              :             }
    2613            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2614            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2615            0 :                 timeline
    2616              :             }
    2617              :         };
    2618              : 
    2619            0 :         Ok(activated_timeline)
    2620            0 :     }
    2621              : 
    2622              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2623              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2624              :     /// [`Tenant::timelines`] map when the import completes.
    2625              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2626              :     /// for the response.
    2627            0 :     async fn create_timeline_import_pgdata(
    2628            0 :         self: &Arc<Tenant>,
    2629            0 :         params: CreateTimelineParamsImportPgdata,
    2630            0 :         activate: ActivateTimelineArgs,
    2631            0 :         ctx: &RequestContext,
    2632            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2633            0 :         let CreateTimelineParamsImportPgdata {
    2634            0 :             new_timeline_id,
    2635            0 :             location,
    2636            0 :             idempotency_key,
    2637            0 :         } = params;
    2638            0 : 
    2639            0 :         let started_at = chrono::Utc::now().naive_utc();
    2640              : 
    2641              :         //
    2642              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2643              :         // is the canonical way we do it.
    2644              :         // - create an empty timeline in-memory
    2645              :         // - use its remote_timeline_client to do the upload
    2646              :         // - dispose of the uninit timeline
    2647              :         // - keep the creation guard alive
    2648              : 
    2649            0 :         let timeline_create_guard = match self
    2650            0 :             .start_creating_timeline(
    2651            0 :                 new_timeline_id,
    2652            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2653            0 :                     idempotency_key: idempotency_key.clone(),
    2654            0 :                 }),
    2655            0 :             )
    2656            0 :             .await?
    2657              :         {
    2658            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2659            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2660            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2661              :             }
    2662              :         };
    2663              : 
    2664            0 :         let mut uninit_timeline = {
    2665            0 :             let this = &self;
    2666            0 :             let initdb_lsn = Lsn(0);
    2667            0 :             let _ctx = ctx;
    2668            0 :             async move {
    2669            0 :                 let new_metadata = TimelineMetadata::new(
    2670            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2671            0 :                     // make it valid, before calling finish_creation()
    2672            0 :                     Lsn(0),
    2673            0 :                     None,
    2674            0 :                     None,
    2675            0 :                     Lsn(0),
    2676            0 :                     initdb_lsn,
    2677            0 :                     initdb_lsn,
    2678            0 :                     15,
    2679            0 :                 );
    2680            0 :                 this.prepare_new_timeline(
    2681            0 :                     new_timeline_id,
    2682            0 :                     &new_metadata,
    2683            0 :                     timeline_create_guard,
    2684            0 :                     initdb_lsn,
    2685            0 :                     None,
    2686            0 :                 )
    2687            0 :                 .await
    2688            0 :             }
    2689              :         }
    2690            0 :         .await?;
    2691              : 
    2692            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2693            0 :             idempotency_key,
    2694            0 :             location,
    2695            0 :             started_at,
    2696            0 :         };
    2697            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2698            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2699            0 :         );
    2700            0 :         uninit_timeline
    2701            0 :             .raw_timeline()
    2702            0 :             .unwrap()
    2703            0 :             .remote_client
    2704            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2705              : 
    2706              :         // wait_completion happens in caller
    2707              : 
    2708            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2709            0 : 
    2710            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2711            0 :             timeline.clone(),
    2712            0 :             index_part,
    2713            0 :             activate,
    2714            0 :             timeline_create_guard,
    2715            0 :         ));
    2716            0 : 
    2717            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2718            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2719            0 :     }
    2720              : 
    2721            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))]
    2722              :     async fn create_timeline_import_pgdata_task(
    2723              :         self: Arc<Tenant>,
    2724              :         timeline: Arc<Timeline>,
    2725              :         index_part: import_pgdata::index_part_format::Root,
    2726              :         activate: ActivateTimelineArgs,
    2727              :         timeline_create_guard: TimelineCreateGuard,
    2728              :     ) {
    2729              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2730              :         info!("starting");
    2731              :         scopeguard::defer! {info!("exiting")};
    2732              : 
    2733              :         let res = self
    2734              :             .create_timeline_import_pgdata_task_impl(
    2735              :                 timeline,
    2736              :                 index_part,
    2737              :                 activate,
    2738              :                 timeline_create_guard,
    2739              :             )
    2740              :             .await;
    2741              :         if let Err(err) = &res {
    2742              :             error!(?err, "task failed");
    2743              :             // TODO sleep & retry, sensitive to tenant shutdown
    2744              :             // TODO: allow timeline deletion requests => should cancel the task
    2745              :         }
    2746              :     }
    2747              : 
    2748            0 :     async fn create_timeline_import_pgdata_task_impl(
    2749            0 :         self: Arc<Tenant>,
    2750            0 :         timeline: Arc<Timeline>,
    2751            0 :         index_part: import_pgdata::index_part_format::Root,
    2752            0 :         activate: ActivateTimelineArgs,
    2753            0 :         timeline_create_guard: TimelineCreateGuard,
    2754            0 :     ) -> Result<(), anyhow::Error> {
    2755            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2756            0 : 
    2757            0 :         info!("importing pgdata");
    2758            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2759            0 :             .await
    2760            0 :             .context("import")?;
    2761            0 :         info!("import done");
    2762              : 
    2763              :         //
    2764              :         // Reload timeline from remote.
    2765              :         // This proves that the remote state is attachable, and it reuses the code.
    2766              :         //
    2767              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2768              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2769              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2770              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2771              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2772              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2773              :         // to manifest because of the long runtime of this import task.
    2774              : 
    2775              :         //        in theory this shouldn't even .await anything except for coop yield
    2776            0 :         info!("shutting down timeline");
    2777            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2778            0 :         info!("timeline shut down, reloading from remote");
    2779              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2780              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2781              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2782              :         // };
    2783            0 :         let timeline_id = timeline.timeline_id;
    2784            0 : 
    2785            0 :         // load from object storage like Tenant::attach does
    2786            0 :         let resources = self.build_timeline_resources(timeline_id);
    2787            0 :         let index_part = resources
    2788            0 :             .remote_client
    2789            0 :             .download_index_file(&self.cancel)
    2790            0 :             .await?;
    2791            0 :         let index_part = match index_part {
    2792              :             MaybeDeletedIndexPart::Deleted(_) => {
    2793              :                 // likely concurrent delete call, cplane should prevent this
    2794            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2795              :             }
    2796            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2797            0 :         };
    2798            0 :         let metadata = index_part.metadata.clone();
    2799            0 :         self
    2800            0 :             .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
    2801            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2802            0 :             .await?
    2803            0 :             .ready_to_activate()
    2804            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2805              : 
    2806            0 :         anyhow::Ok(())
    2807            0 :     }
    2808              : 
    2809            0 :     pub(crate) async fn delete_timeline(
    2810            0 :         self: Arc<Self>,
    2811            0 :         timeline_id: TimelineId,
    2812            0 :     ) -> Result<(), DeleteTimelineError> {
    2813            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2814              : 
    2815            0 :         Ok(())
    2816            0 :     }
    2817              : 
    2818              :     /// perform one garbage collection iteration, removing old data files from disk.
    2819              :     /// this function is periodically called by gc task.
    2820              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2821              :     ///
    2822              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2823              :     ///
    2824              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2825              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2826              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2827              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2828              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2829              :     /// requires more history to be retained.
    2830              :     //
    2831          754 :     pub(crate) async fn gc_iteration(
    2832          754 :         &self,
    2833          754 :         target_timeline_id: Option<TimelineId>,
    2834          754 :         horizon: u64,
    2835          754 :         pitr: Duration,
    2836          754 :         cancel: &CancellationToken,
    2837          754 :         ctx: &RequestContext,
    2838          754 :     ) -> Result<GcResult, GcError> {
    2839          754 :         // Don't start doing work during shutdown
    2840          754 :         if let TenantState::Stopping { .. } = self.current_state() {
    2841            0 :             return Ok(GcResult::default());
    2842          754 :         }
    2843          754 : 
    2844          754 :         // there is a global allowed_error for this
    2845          754 :         if !self.is_active() {
    2846            0 :             return Err(GcError::NotActive);
    2847          754 :         }
    2848          754 : 
    2849          754 :         {
    2850          754 :             let conf = self.tenant_conf.load();
    2851          754 : 
    2852          754 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2853          754 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2854          754 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2855          754 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2856          754 :             if !conf.location.may_delete_layers_hint() {
    2857            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2858            0 :                 return Ok(GcResult::default());
    2859          754 :             }
    2860          754 : 
    2861          754 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2862          750 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2863          750 :                 return Ok(GcResult::default());
    2864            4 :             }
    2865              :         }
    2866              : 
    2867            4 :         let _guard = match self.gc_block.start().await {
    2868            4 :             Ok(guard) => guard,
    2869            0 :             Err(reasons) => {
    2870            0 :                 info!("Skipping GC: {reasons}");
    2871            0 :                 return Ok(GcResult::default());
    2872              :             }
    2873              :         };
    2874              : 
    2875            4 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2876            3 :             .await
    2877          754 :     }
    2878              : 
    2879              :     /// Perform one compaction iteration.
    2880              :     /// This function is periodically called by compactor task.
    2881              :     /// Also it can be explicitly requested per timeline through page server
    2882              :     /// api's 'compact' command.
    2883              :     ///
    2884              :     /// Returns whether we have pending compaction task.
    2885            0 :     async fn compaction_iteration(
    2886            0 :         self: &Arc<Self>,
    2887            0 :         cancel: &CancellationToken,
    2888            0 :         ctx: &RequestContext,
    2889            0 :     ) -> Result<bool, timeline::CompactionError> {
    2890            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2891            0 :         if !self.is_active() {
    2892            0 :             return Ok(false);
    2893            0 :         }
    2894            0 : 
    2895            0 :         {
    2896            0 :             let conf = self.tenant_conf.load();
    2897            0 : 
    2898            0 :             // Note that compaction usually requires deletions, but we don't respect
    2899            0 :             // may_delete_layers_hint here: that is because tenants in AttachedMulti
    2900            0 :             // should proceed with compaction even if they can't do deletion, to avoid
    2901            0 :             // accumulating dangerously deep stacks of L0 layers.  Deletions will be
    2902            0 :             // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
    2903            0 :             // to AttachedSingle state.
    2904            0 :             if !conf.location.may_upload_layers_hint() {
    2905            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2906            0 :                 return Ok(false);
    2907            0 :             }
    2908            0 :         }
    2909            0 : 
    2910            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2911            0 :         // while holding the lock. Then drop the lock and actually perform the
    2912            0 :         // compactions.  We don't want to block everything else while the
    2913            0 :         // compaction runs.
    2914            0 :         let timelines_to_compact_or_offload;
    2915            0 :         {
    2916            0 :             let timelines = self.timelines.lock().unwrap();
    2917            0 :             timelines_to_compact_or_offload = timelines
    2918            0 :                 .iter()
    2919            0 :                 .filter_map(|(timeline_id, timeline)| {
    2920            0 :                     let (is_active, (can_offload, _)) =
    2921            0 :                         (timeline.is_active(), timeline.can_offload());
    2922            0 :                     let has_no_unoffloaded_children = {
    2923            0 :                         !timelines
    2924            0 :                             .iter()
    2925            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2926              :                     };
    2927            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2928            0 :                         || self
    2929            0 :                             .tenant_conf
    2930            0 :                             .load()
    2931            0 :                             .tenant_conf
    2932            0 :                             .timeline_offloading
    2933            0 :                             .unwrap_or_default();
    2934            0 :                     let can_offload =
    2935            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2936            0 :                     if (is_active, can_offload) == (false, false) {
    2937            0 :                         None
    2938              :                     } else {
    2939            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2940              :                     }
    2941            0 :                 })
    2942            0 :                 .collect::<Vec<_>>();
    2943            0 :             drop(timelines);
    2944            0 :         }
    2945            0 : 
    2946            0 :         // Before doing any I/O work, check our circuit breaker
    2947            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2948            0 :             info!("Skipping compaction due to previous failures");
    2949            0 :             return Ok(false);
    2950            0 :         }
    2951            0 : 
    2952            0 :         let mut has_pending_task = false;
    2953              : 
    2954            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2955              :         {
    2956            0 :             let pending_task_left = if *can_compact {
    2957              :                 Some(
    2958            0 :                     timeline
    2959            0 :                         .compact(cancel, EnumSet::empty(), ctx)
    2960            0 :                         .instrument(info_span!("compact_timeline", %timeline_id))
    2961            0 :                         .await
    2962            0 :                         .inspect_err(|e| match e {
    2963            0 :                             timeline::CompactionError::ShuttingDown => (),
    2964            0 :                             timeline::CompactionError::Offload(_) => {
    2965            0 :                                 // Failures to offload timelines do not trip the circuit breaker, because
    2966            0 :                                 // they do not do lots of writes the way compaction itself does: it is cheap
    2967            0 :                                 // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2968            0 :                             }
    2969            0 :                             timeline::CompactionError::Other(e) => {
    2970            0 :                                 self.compaction_circuit_breaker
    2971            0 :                                     .lock()
    2972            0 :                                     .unwrap()
    2973            0 :                                     .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2974            0 :                             }
    2975            0 :                         })?,
    2976              :                 )
    2977              :             } else {
    2978            0 :                 None
    2979              :             };
    2980            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    2981            0 :             if pending_task_left == Some(false) && *can_offload {
    2982            0 :                 offload_timeline(self, timeline)
    2983            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    2984            0 :                     .await?;
    2985            0 :             }
    2986              :         }
    2987              : 
    2988            0 :         self.compaction_circuit_breaker
    2989            0 :             .lock()
    2990            0 :             .unwrap()
    2991            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    2992            0 : 
    2993            0 :         Ok(has_pending_task)
    2994            0 :     }
    2995              : 
    2996              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    2997              :     // this happens during ingest: this background housekeeping is for freezing layers
    2998              :     // that are open but haven't been written to for some time.
    2999            0 :     async fn ingest_housekeeping(&self) {
    3000            0 :         // Scan through the hashmap and collect a list of all the timelines,
    3001            0 :         // while holding the lock. Then drop the lock and actually perform the
    3002            0 :         // compactions.  We don't want to block everything else while the
    3003            0 :         // compaction runs.
    3004            0 :         let timelines = {
    3005            0 :             self.timelines
    3006            0 :                 .lock()
    3007            0 :                 .unwrap()
    3008            0 :                 .values()
    3009            0 :                 .filter_map(|timeline| {
    3010            0 :                     if timeline.is_active() {
    3011            0 :                         Some(timeline.clone())
    3012              :                     } else {
    3013            0 :                         None
    3014              :                     }
    3015            0 :                 })
    3016            0 :                 .collect::<Vec<_>>()
    3017              :         };
    3018              : 
    3019            0 :         for timeline in &timelines {
    3020            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3021              :         }
    3022            0 :     }
    3023              : 
    3024            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3025            0 :         let timelines = self.timelines.lock().unwrap();
    3026            0 :         !timelines
    3027            0 :             .iter()
    3028            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3029            0 :     }
    3030              : 
    3031         1702 :     pub fn current_state(&self) -> TenantState {
    3032         1702 :         self.state.borrow().clone()
    3033         1702 :     }
    3034              : 
    3035          942 :     pub fn is_active(&self) -> bool {
    3036          942 :         self.current_state() == TenantState::Active
    3037          942 :     }
    3038              : 
    3039            0 :     pub fn generation(&self) -> Generation {
    3040            0 :         self.generation
    3041            0 :     }
    3042              : 
    3043            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3044            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3045            0 :     }
    3046              : 
    3047              :     /// Changes tenant status to active, unless shutdown was already requested.
    3048              :     ///
    3049              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3050              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3051            0 :     fn activate(
    3052            0 :         self: &Arc<Self>,
    3053            0 :         broker_client: BrokerClientChannel,
    3054            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3055            0 :         ctx: &RequestContext,
    3056            0 :     ) {
    3057            0 :         span::debug_assert_current_span_has_tenant_id();
    3058            0 : 
    3059            0 :         let mut activating = false;
    3060            0 :         self.state.send_modify(|current_state| {
    3061              :             use pageserver_api::models::ActivatingFrom;
    3062            0 :             match &*current_state {
    3063              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3064            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3065              :                 }
    3066            0 :                 TenantState::Attaching => {
    3067            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3068            0 :                 }
    3069            0 :             }
    3070            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3071            0 :             activating = true;
    3072            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3073            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3074            0 :         });
    3075            0 : 
    3076            0 :         if activating {
    3077            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3078            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3079            0 :             let timelines_to_activate = timelines_accessor
    3080            0 :                 .values()
    3081            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3082            0 : 
    3083            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3084            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3085            0 : 
    3086            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3087            0 :             // down when they notice that the tenant is inactive.
    3088            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3089            0 : 
    3090            0 :             let mut activated_timelines = 0;
    3091              : 
    3092            0 :             for timeline in timelines_to_activate {
    3093            0 :                 timeline.activate(
    3094            0 :                     self.clone(),
    3095            0 :                     broker_client.clone(),
    3096            0 :                     background_jobs_can_start,
    3097            0 :                     ctx,
    3098            0 :                 );
    3099            0 :                 activated_timelines += 1;
    3100            0 :             }
    3101              : 
    3102            0 :             self.state.send_modify(move |current_state| {
    3103            0 :                 assert!(
    3104            0 :                     matches!(current_state, TenantState::Activating(_)),
    3105            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3106              :                 );
    3107            0 :                 *current_state = TenantState::Active;
    3108            0 : 
    3109            0 :                 let elapsed = self.constructed_at.elapsed();
    3110            0 :                 let total_timelines = timelines_accessor.len();
    3111            0 : 
    3112            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3113            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3114            0 :                 info!(
    3115            0 :                     since_creation_millis = elapsed.as_millis(),
    3116            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3117            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3118            0 :                     activated_timelines,
    3119            0 :                     total_timelines,
    3120            0 :                     post_state = <&'static str>::from(&*current_state),
    3121            0 :                     "activation attempt finished"
    3122              :                 );
    3123              : 
    3124            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3125            0 :             });
    3126            0 :         }
    3127            0 :     }
    3128              : 
    3129              :     /// Shutdown the tenant and join all of the spawned tasks.
    3130              :     ///
    3131              :     /// The method caters for all use-cases:
    3132              :     /// - pageserver shutdown (freeze_and_flush == true)
    3133              :     /// - detach + ignore (freeze_and_flush == false)
    3134              :     ///
    3135              :     /// This will attempt to shutdown even if tenant is broken.
    3136              :     ///
    3137              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3138              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3139              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3140              :     /// the ongoing shutdown.
    3141            6 :     async fn shutdown(
    3142            6 :         &self,
    3143            6 :         shutdown_progress: completion::Barrier,
    3144            6 :         shutdown_mode: timeline::ShutdownMode,
    3145            6 :     ) -> Result<(), completion::Barrier> {
    3146            6 :         span::debug_assert_current_span_has_tenant_id();
    3147              : 
    3148              :         // Set tenant (and its timlines) to Stoppping state.
    3149              :         //
    3150              :         // Since we can only transition into Stopping state after activation is complete,
    3151              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3152              :         //
    3153              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3154              :         // 1. Lock out any new requests to the tenants.
    3155              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3156              :         // 3. Signal cancellation for other tenant background loops.
    3157              :         // 4. ???
    3158              :         //
    3159              :         // The waiting for the cancellation is not done uniformly.
    3160              :         // We certainly wait for WAL receivers to shut down.
    3161              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3162              :         // But the tenant background loops are joined-on in our caller.
    3163              :         // It's mesed up.
    3164              :         // we just ignore the failure to stop
    3165              : 
    3166              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3167              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3168              :         // is very slow.
    3169            6 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3170            0 :             self.cancel.cancel();
    3171            0 : 
    3172            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3173            0 :             // are children of ours, so their flush loops will have shut down already
    3174            0 :             timeline::ShutdownMode::Hard
    3175              :         } else {
    3176            6 :             shutdown_mode
    3177              :         };
    3178              : 
    3179            6 :         match self.set_stopping(shutdown_progress, false, false).await {
    3180            6 :             Ok(()) => {}
    3181            0 :             Err(SetStoppingError::Broken) => {
    3182            0 :                 // assume that this is acceptable
    3183            0 :             }
    3184            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3185            0 :                 // give caller the option to wait for this this shutdown
    3186            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3187            0 :                 return Err(other);
    3188              :             }
    3189              :         };
    3190              : 
    3191            6 :         let mut js = tokio::task::JoinSet::new();
    3192            6 :         {
    3193            6 :             let timelines = self.timelines.lock().unwrap();
    3194            6 :             timelines.values().for_each(|timeline| {
    3195            6 :                 let timeline = Arc::clone(timeline);
    3196            6 :                 let timeline_id = timeline.timeline_id;
    3197            6 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3198           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3199            6 :             });
    3200            6 :         }
    3201            6 :         {
    3202            6 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3203            6 :             timelines_offloaded.values().for_each(|timeline| {
    3204            0 :                 timeline.defuse_for_tenant_drop();
    3205            6 :             });
    3206            6 :         }
    3207            6 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3208            6 :         tracing::info!("Waiting for timelines...");
    3209           12 :         while let Some(res) = js.join_next().await {
    3210            0 :             match res {
    3211            6 :                 Ok(()) => {}
    3212            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3213            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3214            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3215              :             }
    3216              :         }
    3217              : 
    3218              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3219              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3220            6 :         tracing::debug!("Cancelling CancellationToken");
    3221            6 :         self.cancel.cancel();
    3222            6 : 
    3223            6 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3224            6 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3225            6 :         //
    3226            6 :         // this will additionally shutdown and await all timeline tasks.
    3227            6 :         tracing::debug!("Waiting for tasks...");
    3228            6 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3229              : 
    3230            6 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3231            6 :             walredo_mgr.shutdown().await;
    3232            0 :         }
    3233              : 
    3234              :         // Wait for any in-flight operations to complete
    3235            6 :         self.gate.close().await;
    3236              : 
    3237            6 :         remove_tenant_metrics(&self.tenant_shard_id);
    3238            6 : 
    3239            6 :         Ok(())
    3240            6 :     }
    3241              : 
    3242              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3243              :     ///
    3244              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3245              :     ///
    3246              :     /// This function is not cancel-safe!
    3247              :     ///
    3248              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3249              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3250            6 :     async fn set_stopping(
    3251            6 :         &self,
    3252            6 :         progress: completion::Barrier,
    3253            6 :         _allow_transition_from_loading: bool,
    3254            6 :         allow_transition_from_attaching: bool,
    3255            6 :     ) -> Result<(), SetStoppingError> {
    3256            6 :         let mut rx = self.state.subscribe();
    3257            6 : 
    3258            6 :         // cannot stop before we're done activating, so wait out until we're done activating
    3259            6 :         rx.wait_for(|state| match state {
    3260            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3261              :             TenantState::Activating(_) | TenantState::Attaching => {
    3262            0 :                 info!(
    3263            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3264            0 :                     <&'static str>::from(state)
    3265              :                 );
    3266            0 :                 false
    3267              :             }
    3268            6 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3269            6 :         })
    3270            0 :         .await
    3271            6 :         .expect("cannot drop self.state while on a &self method");
    3272            6 : 
    3273            6 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3274            6 :         let mut err = None;
    3275            6 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3276              :             TenantState::Activating(_) => {
    3277            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3278              :             }
    3279              :             TenantState::Attaching => {
    3280            0 :                 if !allow_transition_from_attaching {
    3281            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3282            0 :                 };
    3283            0 :                 *current_state = TenantState::Stopping { progress };
    3284            0 :                 true
    3285              :             }
    3286              :             TenantState::Active => {
    3287              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3288              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3289              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3290            6 :                 *current_state = TenantState::Stopping { progress };
    3291            6 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3292            6 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3293            6 :                 true
    3294              :             }
    3295            0 :             TenantState::Broken { reason, .. } => {
    3296            0 :                 info!(
    3297            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3298              :                 );
    3299            0 :                 err = Some(SetStoppingError::Broken);
    3300            0 :                 false
    3301              :             }
    3302            0 :             TenantState::Stopping { progress } => {
    3303            0 :                 info!("Tenant is already in Stopping state");
    3304            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3305            0 :                 false
    3306              :             }
    3307            6 :         });
    3308            6 :         match (stopping, err) {
    3309            6 :             (true, None) => {} // continue
    3310            0 :             (false, Some(err)) => return Err(err),
    3311            0 :             (true, Some(_)) => unreachable!(
    3312            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3313            0 :             ),
    3314            0 :             (false, None) => unreachable!(
    3315            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3316            0 :             ),
    3317              :         }
    3318              : 
    3319            6 :         let timelines_accessor = self.timelines.lock().unwrap();
    3320            6 :         let not_broken_timelines = timelines_accessor
    3321            6 :             .values()
    3322            6 :             .filter(|timeline| !timeline.is_broken());
    3323           12 :         for timeline in not_broken_timelines {
    3324            6 :             timeline.set_state(TimelineState::Stopping);
    3325            6 :         }
    3326            6 :         Ok(())
    3327            6 :     }
    3328              : 
    3329              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3330              :     /// `remove_tenant_from_memory`
    3331              :     ///
    3332              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3333              :     ///
    3334              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3335            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3336            0 :         let mut rx = self.state.subscribe();
    3337            0 : 
    3338            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3339            0 :         // So, wait until it's done.
    3340            0 :         rx.wait_for(|state| match state {
    3341              :             TenantState::Activating(_) | TenantState::Attaching => {
    3342            0 :                 info!(
    3343            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3344            0 :                     <&'static str>::from(state)
    3345              :                 );
    3346            0 :                 false
    3347              :             }
    3348            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3349            0 :         })
    3350            0 :         .await
    3351            0 :         .expect("cannot drop self.state while on a &self method");
    3352            0 : 
    3353            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3354            0 :         self.set_broken_no_wait(reason)
    3355            0 :     }
    3356              : 
    3357            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3358            0 :         let reason = reason.to_string();
    3359            0 :         self.state.send_modify(|current_state| {
    3360            0 :             match *current_state {
    3361              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3362            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3363              :                 }
    3364              :                 TenantState::Active => {
    3365            0 :                     if cfg!(feature = "testing") {
    3366            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3367            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3368              :                     } else {
    3369            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3370              :                     }
    3371              :                 }
    3372              :                 TenantState::Broken { .. } => {
    3373            0 :                     warn!("Tenant is already in Broken state");
    3374              :                 }
    3375              :                 // This is the only "expected" path, any other path is a bug.
    3376              :                 TenantState::Stopping { .. } => {
    3377            0 :                     warn!(
    3378            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3379              :                         reason
    3380              :                     );
    3381            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3382              :                 }
    3383              :            }
    3384            0 :         });
    3385            0 :     }
    3386              : 
    3387            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3388            0 :         self.state.subscribe()
    3389            0 :     }
    3390              : 
    3391              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3392              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3393            0 :     pub(crate) fn activate_now(&self) {
    3394            0 :         self.activate_now_sem.add_permits(1);
    3395            0 :     }
    3396              : 
    3397            0 :     pub(crate) async fn wait_to_become_active(
    3398            0 :         &self,
    3399            0 :         timeout: Duration,
    3400            0 :     ) -> Result<(), GetActiveTenantError> {
    3401            0 :         let mut receiver = self.state.subscribe();
    3402              :         loop {
    3403            0 :             let current_state = receiver.borrow_and_update().clone();
    3404            0 :             match current_state {
    3405              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3406              :                     // in these states, there's a chance that we can reach ::Active
    3407            0 :                     self.activate_now();
    3408            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3409            0 :                         Ok(r) => {
    3410            0 :                             r.map_err(
    3411            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3412              :                                 // Tenant existed but was dropped: report it as non-existent
    3413            0 :                                 GetActiveTenantError::NotFound(GetTenantError::NotFound(self.tenant_shard_id.tenant_id))
    3414            0 :                         )?
    3415              :                         }
    3416              :                         Err(TimeoutCancellableError::Cancelled) => {
    3417            0 :                             return Err(GetActiveTenantError::Cancelled);
    3418              :                         }
    3419              :                         Err(TimeoutCancellableError::Timeout) => {
    3420            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3421            0 :                                 latest_state: Some(self.current_state()),
    3422            0 :                                 wait_time: timeout,
    3423            0 :                             });
    3424              :                         }
    3425              :                     }
    3426              :                 }
    3427              :                 TenantState::Active { .. } => {
    3428            0 :                     return Ok(());
    3429              :                 }
    3430            0 :                 TenantState::Broken { reason, .. } => {
    3431            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3432            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3433            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3434              :                 }
    3435              :                 TenantState::Stopping { .. } => {
    3436              :                     // There's no chance the tenant can transition back into ::Active
    3437            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3438              :                 }
    3439              :             }
    3440              :         }
    3441            0 :     }
    3442              : 
    3443            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3444            0 :         self.tenant_conf.load().location.attach_mode
    3445            0 :     }
    3446              : 
    3447              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3448              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3449              :     /// rare external API calls, like a reconciliation at startup.
    3450            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3451            0 :         let conf = self.tenant_conf.load();
    3452              : 
    3453            0 :         let location_config_mode = match conf.location.attach_mode {
    3454            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3455            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3456            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3457              :         };
    3458              : 
    3459              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3460            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3461            0 : 
    3462            0 :         models::LocationConfig {
    3463            0 :             mode: location_config_mode,
    3464            0 :             generation: self.generation.into(),
    3465            0 :             secondary_conf: None,
    3466            0 :             shard_number: self.shard_identity.number.0,
    3467            0 :             shard_count: self.shard_identity.count.literal(),
    3468            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3469            0 :             tenant_conf: tenant_config,
    3470            0 :         }
    3471            0 :     }
    3472              : 
    3473            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3474            0 :         &self.tenant_shard_id
    3475            0 :     }
    3476              : 
    3477            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3478            0 :         self.shard_identity.stripe_size
    3479            0 :     }
    3480              : 
    3481            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3482            0 :         self.generation
    3483            0 :     }
    3484              : 
    3485              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3486              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3487              :     /// resetting this tenant to a valid state if we fail.
    3488            0 :     pub(crate) async fn split_prepare(
    3489            0 :         &self,
    3490            0 :         child_shards: &Vec<TenantShardId>,
    3491            0 :     ) -> anyhow::Result<()> {
    3492            0 :         let (timelines, offloaded) = {
    3493            0 :             let timelines = self.timelines.lock().unwrap();
    3494            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3495            0 :             (timelines.clone(), offloaded.clone())
    3496            0 :         };
    3497            0 :         let timelines_iter = timelines
    3498            0 :             .values()
    3499            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3500            0 :             .chain(
    3501            0 :                 offloaded
    3502            0 :                     .values()
    3503            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3504            0 :             );
    3505            0 :         for timeline in timelines_iter {
    3506              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3507              :             // to ensure that they do not start a split if currently in the process of doing these.
    3508              : 
    3509            0 :             let timeline_id = timeline.timeline_id();
    3510              : 
    3511            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3512              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3513              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3514              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3515            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3516            0 :                 timeline
    3517            0 :                     .remote_client
    3518            0 :                     .schedule_index_upload_for_file_changes()?;
    3519            0 :                 timeline.remote_client.wait_completion().await?;
    3520            0 :             }
    3521              : 
    3522            0 :             let remote_client = match timeline {
    3523            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3524            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3525            0 :                     let remote_client = self
    3526            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3527            0 :                     Arc::new(remote_client)
    3528              :                 }
    3529              :             };
    3530              : 
    3531              :             // Shut down the timeline's remote client: this means that the indices we write
    3532              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3533            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3534            0 :             remote_client.shutdown().await;
    3535              : 
    3536              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3537              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3538              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3539              :             // we use here really is the remotely persistent one).
    3540            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3541            0 :             let result = remote_client
    3542            0 :                 .download_index_file(&self.cancel)
    3543            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))
    3544            0 :                 .await?;
    3545            0 :             let index_part = match result {
    3546              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3547            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3548              :                 }
    3549            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3550              :             };
    3551              : 
    3552            0 :             for child_shard in child_shards {
    3553            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3554            0 :                 upload_index_part(
    3555            0 :                     &self.remote_storage,
    3556            0 :                     child_shard,
    3557            0 :                     &timeline_id,
    3558            0 :                     self.generation,
    3559            0 :                     &index_part,
    3560            0 :                     &self.cancel,
    3561            0 :                 )
    3562            0 :                 .await?;
    3563              :             }
    3564              :         }
    3565              : 
    3566            0 :         let tenant_manifest = self.build_tenant_manifest();
    3567            0 :         for child_shard in child_shards {
    3568            0 :             tracing::info!(
    3569            0 :                 "Uploading tenant manifest for child {}",
    3570            0 :                 child_shard.to_index()
    3571              :             );
    3572            0 :             upload_tenant_manifest(
    3573            0 :                 &self.remote_storage,
    3574            0 :                 child_shard,
    3575            0 :                 self.generation,
    3576            0 :                 &tenant_manifest,
    3577            0 :                 &self.cancel,
    3578            0 :             )
    3579            0 :             .await?;
    3580              :         }
    3581              : 
    3582            0 :         Ok(())
    3583            0 :     }
    3584              : 
    3585            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3586            0 :         let mut result = TopTenantShardItem {
    3587            0 :             id: self.tenant_shard_id,
    3588            0 :             resident_size: 0,
    3589            0 :             physical_size: 0,
    3590            0 :             max_logical_size: 0,
    3591            0 :         };
    3592              : 
    3593            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3594            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3595            0 : 
    3596            0 :             result.physical_size += timeline
    3597            0 :                 .remote_client
    3598            0 :                 .metrics
    3599            0 :                 .remote_physical_size_gauge
    3600            0 :                 .get();
    3601            0 :             result.max_logical_size = std::cmp::max(
    3602            0 :                 result.max_logical_size,
    3603            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3604            0 :             );
    3605            0 :         }
    3606              : 
    3607            0 :         result
    3608            0 :     }
    3609              : }
    3610              : 
    3611              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3612              : /// perform a topological sort, so that the parent of each timeline comes
    3613              : /// before the children.
    3614              : /// E extracts the ancestor from T
    3615              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3616          192 : fn tree_sort_timelines<T, E>(
    3617          192 :     timelines: HashMap<TimelineId, T>,
    3618          192 :     extractor: E,
    3619          192 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3620          192 : where
    3621          192 :     E: Fn(&T) -> Option<TimelineId>,
    3622          192 : {
    3623          192 :     let mut result = Vec::with_capacity(timelines.len());
    3624          192 : 
    3625          192 :     let mut now = Vec::with_capacity(timelines.len());
    3626          192 :     // (ancestor, children)
    3627          192 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3628          192 :         HashMap::with_capacity(timelines.len());
    3629              : 
    3630          198 :     for (timeline_id, value) in timelines {
    3631            6 :         if let Some(ancestor_id) = extractor(&value) {
    3632            2 :             let children = later.entry(ancestor_id).or_default();
    3633            2 :             children.push((timeline_id, value));
    3634            4 :         } else {
    3635            4 :             now.push((timeline_id, value));
    3636            4 :         }
    3637              :     }
    3638              : 
    3639          198 :     while let Some((timeline_id, metadata)) = now.pop() {
    3640            6 :         result.push((timeline_id, metadata));
    3641              :         // All children of this can be loaded now
    3642            6 :         if let Some(mut children) = later.remove(&timeline_id) {
    3643            2 :             now.append(&mut children);
    3644            4 :         }
    3645              :     }
    3646              : 
    3647              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3648          192 :     if !later.is_empty() {
    3649            0 :         for (missing_id, orphan_ids) in later {
    3650            0 :             for (orphan_id, _) in orphan_ids {
    3651            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3652              :             }
    3653              :         }
    3654            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3655          192 :     }
    3656          192 : 
    3657          192 :     Ok(result)
    3658          192 : }
    3659              : 
    3660              : enum ActivateTimelineArgs {
    3661              :     Yes {
    3662              :         broker_client: storage_broker::BrokerClientChannel,
    3663              :     },
    3664              :     No,
    3665              : }
    3666              : 
    3667              : impl Tenant {
    3668            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3669            0 :         self.tenant_conf.load().tenant_conf.clone()
    3670            0 :     }
    3671              : 
    3672            0 :     pub fn effective_config(&self) -> TenantConf {
    3673            0 :         self.tenant_specific_overrides()
    3674            0 :             .merge(self.conf.default_tenant_conf.clone())
    3675            0 :     }
    3676              : 
    3677            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3678            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3679            0 :         tenant_conf
    3680            0 :             .checkpoint_distance
    3681            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3682            0 :     }
    3683              : 
    3684            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3685            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3686            0 :         tenant_conf
    3687            0 :             .checkpoint_timeout
    3688            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3689            0 :     }
    3690              : 
    3691            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3692            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3693            0 :         tenant_conf
    3694            0 :             .compaction_target_size
    3695            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3696            0 :     }
    3697              : 
    3698            0 :     pub fn get_compaction_period(&self) -> Duration {
    3699            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3700            0 :         tenant_conf
    3701            0 :             .compaction_period
    3702            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3703            0 :     }
    3704              : 
    3705            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3706            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3707            0 :         tenant_conf
    3708            0 :             .compaction_threshold
    3709            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3710            0 :     }
    3711              : 
    3712            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3713            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3714            0 :         tenant_conf
    3715            0 :             .gc_horizon
    3716            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3717            0 :     }
    3718              : 
    3719            0 :     pub fn get_gc_period(&self) -> Duration {
    3720            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3721            0 :         tenant_conf
    3722            0 :             .gc_period
    3723            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3724            0 :     }
    3725              : 
    3726            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3727            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3728            0 :         tenant_conf
    3729            0 :             .image_creation_threshold
    3730            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3731            0 :     }
    3732              : 
    3733            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3734            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3735            0 :         tenant_conf
    3736            0 :             .pitr_interval
    3737            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3738            0 :     }
    3739              : 
    3740            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3741            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3742            0 :         tenant_conf
    3743            0 :             .min_resident_size_override
    3744            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3745            0 :     }
    3746              : 
    3747            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3748            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3749            0 :         let heatmap_period = tenant_conf
    3750            0 :             .heatmap_period
    3751            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3752            0 :         if heatmap_period.is_zero() {
    3753            0 :             None
    3754              :         } else {
    3755            0 :             Some(heatmap_period)
    3756              :         }
    3757            0 :     }
    3758              : 
    3759            4 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3760            4 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3761            4 :         tenant_conf
    3762            4 :             .lsn_lease_length
    3763            4 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3764            4 :     }
    3765              : 
    3766              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3767            2 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3768            2 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3769            2 : 
    3770            2 :         let mut timeline_manifests = timelines_offloaded
    3771            2 :             .iter()
    3772            2 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3773            2 :             .collect::<Vec<_>>();
    3774            2 :         // Sort the manifests so that our output is deterministic
    3775            2 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3776            2 : 
    3777            2 :         TenantManifest {
    3778            2 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3779            2 :             offloaded_timelines: timeline_manifests,
    3780            2 :         }
    3781            2 :     }
    3782              : 
    3783            0 :     pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
    3784            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3785            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3786            0 :         // this race is not possible if both request types come from the storage
    3787            0 :         // controller (as they should!) because an exclusive op lock is required
    3788            0 :         // on the storage controller side.
    3789            0 : 
    3790            0 :         self.tenant_conf.rcu(|inner| {
    3791            0 :             Arc::new(AttachedTenantConf {
    3792            0 :                 tenant_conf: new_tenant_conf.clone(),
    3793            0 :                 location: inner.location,
    3794            0 :                 // Attached location is not changed, no need to update lsn lease deadline.
    3795            0 :                 lsn_lease_deadline: inner.lsn_lease_deadline,
    3796            0 :             })
    3797            0 :         });
    3798            0 : 
    3799            0 :         let updated = self.tenant_conf.load().clone();
    3800            0 : 
    3801            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3802            0 :         // Don't hold self.timelines.lock() during the notifies.
    3803            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3804            0 :         // mutexes in struct Timeline in the future.
    3805            0 :         let timelines = self.list_timelines();
    3806            0 :         for timeline in timelines {
    3807            0 :             timeline.tenant_conf_updated(&updated);
    3808            0 :         }
    3809            0 :     }
    3810              : 
    3811            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3812            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3813            0 : 
    3814            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    3815            0 : 
    3816            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3817            0 :         // Don't hold self.timelines.lock() during the notifies.
    3818            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3819            0 :         // mutexes in struct Timeline in the future.
    3820            0 :         let timelines = self.list_timelines();
    3821            0 :         for timeline in timelines {
    3822            0 :             timeline.tenant_conf_updated(&new_conf);
    3823            0 :         }
    3824            0 :     }
    3825              : 
    3826          192 :     fn get_timeline_get_throttle_config(
    3827          192 :         psconf: &'static PageServerConf,
    3828          192 :         overrides: &TenantConfOpt,
    3829          192 :     ) -> throttle::Config {
    3830          192 :         overrides
    3831          192 :             .timeline_get_throttle
    3832          192 :             .clone()
    3833          192 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3834          192 :     }
    3835              : 
    3836            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3837            0 :         let conf = Self::get_timeline_get_throttle_config(self.conf, new_conf);
    3838            0 :         self.timeline_get_throttle.reconfigure(conf)
    3839            0 :     }
    3840              : 
    3841              :     /// Helper function to create a new Timeline struct.
    3842              :     ///
    3843              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3844              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3845              :     /// map.
    3846              :     ///
    3847              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3848              :     /// and we might not have the ancestor present anymore which is fine for to be
    3849              :     /// deleted timelines.
    3850              :     #[allow(clippy::too_many_arguments)]
    3851          418 :     fn create_timeline_struct(
    3852          418 :         &self,
    3853          418 :         new_timeline_id: TimelineId,
    3854          418 :         new_metadata: &TimelineMetadata,
    3855          418 :         ancestor: Option<Arc<Timeline>>,
    3856          418 :         resources: TimelineResources,
    3857          418 :         cause: CreateTimelineCause,
    3858          418 :         create_idempotency: CreateTimelineIdempotency,
    3859          418 :     ) -> anyhow::Result<Arc<Timeline>> {
    3860          418 :         let state = match cause {
    3861              :             CreateTimelineCause::Load => {
    3862          418 :                 let ancestor_id = new_metadata.ancestor_timeline();
    3863          418 :                 anyhow::ensure!(
    3864          418 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    3865            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    3866              :                 );
    3867          418 :                 TimelineState::Loading
    3868              :             }
    3869            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    3870              :         };
    3871              : 
    3872          418 :         let pg_version = new_metadata.pg_version();
    3873          418 : 
    3874          418 :         let timeline = Timeline::new(
    3875          418 :             self.conf,
    3876          418 :             Arc::clone(&self.tenant_conf),
    3877          418 :             new_metadata,
    3878          418 :             ancestor,
    3879          418 :             new_timeline_id,
    3880          418 :             self.tenant_shard_id,
    3881          418 :             self.generation,
    3882          418 :             self.shard_identity,
    3883          418 :             self.walredo_mgr.clone(),
    3884          418 :             resources,
    3885          418 :             pg_version,
    3886          418 :             state,
    3887          418 :             self.attach_wal_lag_cooldown.clone(),
    3888          418 :             create_idempotency,
    3889          418 :             self.cancel.child_token(),
    3890          418 :         );
    3891          418 : 
    3892          418 :         Ok(timeline)
    3893          418 :     }
    3894              : 
    3895              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    3896              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    3897              :     #[allow(clippy::too_many_arguments)]
    3898          192 :     fn new(
    3899          192 :         state: TenantState,
    3900          192 :         conf: &'static PageServerConf,
    3901          192 :         attached_conf: AttachedTenantConf,
    3902          192 :         shard_identity: ShardIdentity,
    3903          192 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    3904          192 :         tenant_shard_id: TenantShardId,
    3905          192 :         remote_storage: GenericRemoteStorage,
    3906          192 :         deletion_queue_client: DeletionQueueClient,
    3907          192 :         l0_flush_global_state: L0FlushGlobalState,
    3908          192 :     ) -> Tenant {
    3909          192 :         debug_assert!(
    3910          192 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    3911              :         );
    3912              : 
    3913          192 :         let (state, mut rx) = watch::channel(state);
    3914          192 : 
    3915          192 :         tokio::spawn(async move {
    3916          192 :             // reflect tenant state in metrics:
    3917          192 :             // - global per tenant state: TENANT_STATE_METRIC
    3918          192 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    3919          192 :             //
    3920          192 :             // set of broken tenants should not have zero counts so that it remains accessible for
    3921          192 :             // alerting.
    3922          192 : 
    3923          192 :             let tid = tenant_shard_id.to_string();
    3924          192 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    3925          192 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    3926              : 
    3927          382 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    3928          382 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    3929          382 :             }
    3930              : 
    3931          192 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    3932          192 : 
    3933          192 :             let is_broken = tuple.1;
    3934          192 :             let mut counted_broken = if is_broken {
    3935              :                 // add the id to the set right away, there should not be any updates on the channel
    3936              :                 // after before tenant is removed, if ever
    3937            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    3938            0 :                 true
    3939              :             } else {
    3940          192 :                 false
    3941              :             };
    3942              : 
    3943              :             loop {
    3944          382 :                 let labels = &tuple.0;
    3945          382 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    3946          382 :                 current.inc();
    3947          382 : 
    3948          382 :                 if rx.changed().await.is_err() {
    3949              :                     // tenant has been dropped
    3950           14 :                     current.dec();
    3951           14 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    3952           14 :                     break;
    3953          190 :                 }
    3954          190 : 
    3955          190 :                 current.dec();
    3956          190 :                 tuple = inspect_state(&rx.borrow_and_update());
    3957          190 : 
    3958          190 :                 let is_broken = tuple.1;
    3959          190 :                 if is_broken && !counted_broken {
    3960            0 :                     counted_broken = true;
    3961            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    3962            0 :                     // access
    3963            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    3964          190 :                 }
    3965              :             }
    3966          192 :         });
    3967          192 : 
    3968          192 :         Tenant {
    3969          192 :             tenant_shard_id,
    3970          192 :             shard_identity,
    3971          192 :             generation: attached_conf.location.generation,
    3972          192 :             conf,
    3973          192 :             // using now here is good enough approximation to catch tenants with really long
    3974          192 :             // activation times.
    3975          192 :             constructed_at: Instant::now(),
    3976          192 :             timelines: Mutex::new(HashMap::new()),
    3977          192 :             timelines_creating: Mutex::new(HashSet::new()),
    3978          192 :             timelines_offloaded: Mutex::new(HashMap::new()),
    3979          192 :             tenant_manifest_upload: Default::default(),
    3980          192 :             gc_cs: tokio::sync::Mutex::new(()),
    3981          192 :             walredo_mgr,
    3982          192 :             remote_storage,
    3983          192 :             deletion_queue_client,
    3984          192 :             state,
    3985          192 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    3986          192 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    3987          192 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    3988          192 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    3989          192 :                 format!("compaction-{tenant_shard_id}"),
    3990          192 :                 5,
    3991          192 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    3992          192 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    3993          192 :                 // use an extremely long backoff.
    3994          192 :                 Some(Duration::from_secs(3600 * 24)),
    3995          192 :             )),
    3996          192 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    3997          192 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    3998          192 :             cancel: CancellationToken::default(),
    3999          192 :             gate: Gate::default(),
    4000          192 :             timeline_get_throttle: Arc::new(throttle::Throttle::new(
    4001          192 :                 Tenant::get_timeline_get_throttle_config(conf, &attached_conf.tenant_conf),
    4002          192 :                 crate::metrics::tenant_throttling::TimelineGet::new(&tenant_shard_id),
    4003          192 :             )),
    4004          192 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4005          192 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4006          192 :             gc_block: Default::default(),
    4007          192 :             l0_flush_global_state,
    4008          192 :         }
    4009          192 :     }
    4010              : 
    4011              :     /// Locate and load config
    4012            0 :     pub(super) fn load_tenant_config(
    4013            0 :         conf: &'static PageServerConf,
    4014            0 :         tenant_shard_id: &TenantShardId,
    4015            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4016            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4017            0 : 
    4018            0 :         info!("loading tenant configuration from {config_path}");
    4019              : 
    4020              :         // load and parse file
    4021            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4022            0 :             match e.kind() {
    4023              :                 std::io::ErrorKind::NotFound => {
    4024              :                     // The config should almost always exist for a tenant directory:
    4025              :                     //  - When attaching a tenant, the config is the first thing we write
    4026              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4027              :                     //    before deleting contents.
    4028              :                     //
    4029              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4030              :                     // between creating directory and writing config.  Callers should handle that as if the
    4031              :                     // directory didn't exist.
    4032              : 
    4033            0 :                     LoadConfigError::NotFound(config_path)
    4034              :                 }
    4035              :                 _ => {
    4036              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4037              :                     // that we cannot cleanly recover
    4038            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4039              :                 }
    4040              :             }
    4041            0 :         })?;
    4042              : 
    4043            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4044            0 :     }
    4045              : 
    4046            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4047              :     pub(super) async fn persist_tenant_config(
    4048              :         conf: &'static PageServerConf,
    4049              :         tenant_shard_id: &TenantShardId,
    4050              :         location_conf: &LocationConf,
    4051              :     ) -> std::io::Result<()> {
    4052              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4053              : 
    4054              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4055              :     }
    4056              : 
    4057            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4058              :     pub(super) async fn persist_tenant_config_at(
    4059              :         tenant_shard_id: &TenantShardId,
    4060              :         config_path: &Utf8Path,
    4061              :         location_conf: &LocationConf,
    4062              :     ) -> std::io::Result<()> {
    4063              :         debug!("persisting tenantconf to {config_path}");
    4064              : 
    4065              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4066              : #  It is read in case of pageserver restart.
    4067              : "#
    4068              :         .to_string();
    4069              : 
    4070            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4071            0 :             Err(std::io::Error::new(
    4072            0 :                 std::io::ErrorKind::Other,
    4073            0 :                 "tenant-config-before-write",
    4074            0 :             ))
    4075            0 :         });
    4076              : 
    4077              :         // Convert the config to a toml file.
    4078              :         conf_content +=
    4079              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4080              : 
    4081              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4082              : 
    4083              :         let conf_content = conf_content.into_bytes();
    4084              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4085              :     }
    4086              : 
    4087              :     //
    4088              :     // How garbage collection works:
    4089              :     //
    4090              :     //                    +--bar------------->
    4091              :     //                   /
    4092              :     //             +----+-----foo---------------->
    4093              :     //            /
    4094              :     // ----main--+-------------------------->
    4095              :     //                \
    4096              :     //                 +-----baz-------->
    4097              :     //
    4098              :     //
    4099              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4100              :     //    `gc_infos` are being refreshed
    4101              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4102              :     //    all the points where other timelines have been branched off.
    4103              :     //    We will refrain from removing page versions at those LSNs.
    4104              :     // 3. For each timeline, scan all layer files on the timeline.
    4105              :     //    Remove all files for which a newer file exists and which
    4106              :     //    don't cover any branch point LSNs.
    4107              :     //
    4108              :     // TODO:
    4109              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4110              :     //   don't need to keep that in the parent anymore. But currently
    4111              :     //   we do.
    4112            4 :     async fn gc_iteration_internal(
    4113            4 :         &self,
    4114            4 :         target_timeline_id: Option<TimelineId>,
    4115            4 :         horizon: u64,
    4116            4 :         pitr: Duration,
    4117            4 :         cancel: &CancellationToken,
    4118            4 :         ctx: &RequestContext,
    4119            4 :     ) -> Result<GcResult, GcError> {
    4120            4 :         let mut totals: GcResult = Default::default();
    4121            4 :         let now = Instant::now();
    4122              : 
    4123            4 :         let gc_timelines = self
    4124            4 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4125            3 :             .await?;
    4126              : 
    4127            4 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4128              : 
    4129              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4130            4 :         if !gc_timelines.is_empty() {
    4131            4 :             info!("{} timelines need GC", gc_timelines.len());
    4132              :         } else {
    4133            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4134              :         }
    4135              : 
    4136              :         // Perform GC for each timeline.
    4137              :         //
    4138              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4139              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4140              :         // with branch creation.
    4141              :         //
    4142              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4143              :         // creation task can run concurrently with timeline's GC iteration.
    4144            8 :         for timeline in gc_timelines {
    4145            4 :             if cancel.is_cancelled() {
    4146              :                 // We were requested to shut down. Stop and return with the progress we
    4147              :                 // made.
    4148            0 :                 break;
    4149            4 :             }
    4150            4 :             let result = match timeline.gc().await {
    4151              :                 Err(GcError::TimelineCancelled) => {
    4152            0 :                     if target_timeline_id.is_some() {
    4153              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4154            0 :                         return Err(GcError::TimelineCancelled);
    4155              :                     } else {
    4156              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4157              :                         // skip past this and proceed to try GC on other timelines.
    4158            0 :                         continue;
    4159              :                     }
    4160              :                 }
    4161            4 :                 r => r?,
    4162              :             };
    4163            4 :             totals += result;
    4164              :         }
    4165              : 
    4166            4 :         totals.elapsed = now.elapsed();
    4167            4 :         Ok(totals)
    4168            4 :     }
    4169              : 
    4170              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4171              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4172              :     /// [`Tenant::get_gc_horizon`].
    4173              :     ///
    4174              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4175            0 :     pub(crate) async fn refresh_gc_info(
    4176            0 :         &self,
    4177            0 :         cancel: &CancellationToken,
    4178            0 :         ctx: &RequestContext,
    4179            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4180            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4181            0 :         // might be that these configuration values get applied faster than what it was previously,
    4182            0 :         // since these were only read from the gc task.
    4183            0 :         let horizon = self.get_gc_horizon();
    4184            0 :         let pitr = self.get_pitr_interval();
    4185            0 : 
    4186            0 :         // refresh all timelines
    4187            0 :         let target_timeline_id = None;
    4188            0 : 
    4189            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4190            0 :             .await
    4191            0 :     }
    4192              : 
    4193              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4194              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4195              :     ///
    4196              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4197            0 :     fn initialize_gc_info(
    4198            0 :         &self,
    4199            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4200            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4201            0 :         restrict_to_timeline: Option<TimelineId>,
    4202            0 :     ) {
    4203            0 :         if restrict_to_timeline.is_none() {
    4204              :             // This function must be called before activation: after activation timeline create/delete operations
    4205              :             // might happen, and this function is not safe to run concurrently with those.
    4206            0 :             assert!(!self.is_active());
    4207            0 :         }
    4208              : 
    4209              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4210              :         // the branch point where it was created.
    4211            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4212            0 :             BTreeMap::new();
    4213            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4214            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4215            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4216            0 :                 ancestor_children.push((
    4217            0 :                     timeline_entry.get_ancestor_lsn(),
    4218            0 :                     *timeline_id,
    4219            0 :                     MaybeOffloaded::No,
    4220            0 :                 ));
    4221            0 :             }
    4222            0 :         });
    4223            0 :         timelines_offloaded
    4224            0 :             .iter()
    4225            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4226            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4227            0 :                     return;
    4228              :                 };
    4229            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4230            0 :                     return;
    4231              :                 };
    4232            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4233            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4234            0 :             });
    4235            0 : 
    4236            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4237            0 :         let horizon = self.get_gc_horizon();
    4238              : 
    4239              :         // Populate each timeline's GcInfo with information about its child branches
    4240            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4241            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4242              :         } else {
    4243            0 :             itertools::Either::Right(timelines.values())
    4244              :         };
    4245            0 :         for timeline in timelines_to_write {
    4246            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4247            0 :                 .remove(&timeline.timeline_id)
    4248            0 :                 .unwrap_or_default();
    4249            0 : 
    4250            0 :             branchpoints.sort_by_key(|b| b.0);
    4251            0 : 
    4252            0 :             let mut target = timeline.gc_info.write().unwrap();
    4253            0 : 
    4254            0 :             target.retain_lsns = branchpoints;
    4255            0 : 
    4256            0 :             let space_cutoff = timeline
    4257            0 :                 .get_last_record_lsn()
    4258            0 :                 .checked_sub(horizon)
    4259            0 :                 .unwrap_or(Lsn(0));
    4260            0 : 
    4261            0 :             target.cutoffs = GcCutoffs {
    4262            0 :                 space: space_cutoff,
    4263            0 :                 time: Lsn::INVALID,
    4264            0 :             };
    4265            0 :         }
    4266            0 :     }
    4267              : 
    4268            4 :     async fn refresh_gc_info_internal(
    4269            4 :         &self,
    4270            4 :         target_timeline_id: Option<TimelineId>,
    4271            4 :         horizon: u64,
    4272            4 :         pitr: Duration,
    4273            4 :         cancel: &CancellationToken,
    4274            4 :         ctx: &RequestContext,
    4275            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4276            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4277            4 :         // currently visible timelines.
    4278            4 :         let timelines = self
    4279            4 :             .timelines
    4280            4 :             .lock()
    4281            4 :             .unwrap()
    4282            4 :             .values()
    4283            4 :             .filter(|tl| match target_timeline_id.as_ref() {
    4284            4 :                 Some(target) => &tl.timeline_id == target,
    4285            0 :                 None => true,
    4286            4 :             })
    4287            4 :             .cloned()
    4288            4 :             .collect::<Vec<_>>();
    4289            4 : 
    4290            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4291              :             // We were to act on a particular timeline and it wasn't found
    4292            0 :             return Err(GcError::TimelineNotFound);
    4293            4 :         }
    4294            4 : 
    4295            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4296            4 :             HashMap::with_capacity(timelines.len());
    4297              : 
    4298            4 :         for timeline in timelines.iter() {
    4299            4 :             let cutoff = timeline
    4300            4 :                 .get_last_record_lsn()
    4301            4 :                 .checked_sub(horizon)
    4302            4 :                 .unwrap_or(Lsn(0));
    4303              : 
    4304            4 :             let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
    4305            4 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4306            4 :             assert!(old.is_none());
    4307              :         }
    4308              : 
    4309            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    4310            0 :             return Err(GcError::TenantCancelled);
    4311            4 :         }
    4312              : 
    4313              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4314              :         // because that will stall branch creation.
    4315            4 :         let gc_cs = self.gc_cs.lock().await;
    4316              : 
    4317              :         // Ok, we now know all the branch points.
    4318              :         // Update the GC information for each timeline.
    4319            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4320            8 :         for timeline in timelines {
    4321              :             // We filtered the timeline list above
    4322            4 :             if let Some(target_timeline_id) = target_timeline_id {
    4323            4 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4324            0 :             }
    4325              : 
    4326              :             {
    4327            4 :                 let mut target = timeline.gc_info.write().unwrap();
    4328            4 : 
    4329            4 :                 // Cull any expired leases
    4330            4 :                 let now = SystemTime::now();
    4331            6 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4332            4 : 
    4333            4 :                 timeline
    4334            4 :                     .metrics
    4335            4 :                     .valid_lsn_lease_count_gauge
    4336            4 :                     .set(target.leases.len() as u64);
    4337              : 
    4338              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4339            4 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4340            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4341            0 :                         target.within_ancestor_pitr =
    4342            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4343            0 :                     }
    4344            4 :                 }
    4345              : 
    4346              :                 // Update metrics that depend on GC state
    4347            4 :                 timeline
    4348            4 :                     .metrics
    4349            4 :                     .archival_size
    4350            4 :                     .set(if target.within_ancestor_pitr {
    4351            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4352              :                     } else {
    4353            4 :                         0
    4354              :                     });
    4355            4 :                 timeline.metrics.pitr_history_size.set(
    4356            4 :                     timeline
    4357            4 :                         .get_last_record_lsn()
    4358            4 :                         .checked_sub(target.cutoffs.time)
    4359            4 :                         .unwrap_or(Lsn(0))
    4360            4 :                         .0,
    4361            4 :                 );
    4362              : 
    4363              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4364              :                 // - this timeline was created while we were finding cutoffs
    4365              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4366            4 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4367            4 :                     target.cutoffs = cutoffs.clone();
    4368            4 :                 }
    4369              :             }
    4370              : 
    4371            4 :             gc_timelines.push(timeline);
    4372              :         }
    4373            4 :         drop(gc_cs);
    4374            4 :         Ok(gc_timelines)
    4375            4 :     }
    4376              : 
    4377              :     /// A substitute for `branch_timeline` for use in unit tests.
    4378              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4379              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4380              :     /// timeline background tasks are launched, except the flush loop.
    4381              :     #[cfg(test)]
    4382          232 :     async fn branch_timeline_test(
    4383          232 :         self: &Arc<Self>,
    4384          232 :         src_timeline: &Arc<Timeline>,
    4385          232 :         dst_id: TimelineId,
    4386          232 :         ancestor_lsn: Option<Lsn>,
    4387          232 :         ctx: &RequestContext,
    4388          232 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4389          232 :         let tl = self
    4390          232 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4391          190 :             .await?
    4392          228 :             .into_timeline_for_test();
    4393          228 :         tl.set_state(TimelineState::Active);
    4394          228 :         Ok(tl)
    4395          232 :     }
    4396              : 
    4397              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4398              :     #[cfg(test)]
    4399              :     #[allow(clippy::too_many_arguments)]
    4400            6 :     pub async fn branch_timeline_test_with_layers(
    4401            6 :         self: &Arc<Self>,
    4402            6 :         src_timeline: &Arc<Timeline>,
    4403            6 :         dst_id: TimelineId,
    4404            6 :         ancestor_lsn: Option<Lsn>,
    4405            6 :         ctx: &RequestContext,
    4406            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4407            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4408            6 :         end_lsn: Lsn,
    4409            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4410              :         use checks::check_valid_layermap;
    4411              :         use itertools::Itertools;
    4412              : 
    4413            6 :         let tline = self
    4414            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4415            4 :             .await?;
    4416            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4417            6 :             ancestor_lsn
    4418              :         } else {
    4419            0 :             tline.get_last_record_lsn()
    4420              :         };
    4421            6 :         assert!(end_lsn >= ancestor_lsn);
    4422            6 :         tline.force_advance_lsn(end_lsn);
    4423           12 :         for deltas in delta_layer_desc {
    4424            6 :             tline
    4425            6 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4426           18 :                 .await?;
    4427              :         }
    4428           10 :         for (lsn, images) in image_layer_desc {
    4429            4 :             tline
    4430            4 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4431           14 :                 .await?;
    4432              :         }
    4433            6 :         let layer_names = tline
    4434            6 :             .layers
    4435            6 :             .read()
    4436            0 :             .await
    4437            6 :             .layer_map()
    4438            6 :             .unwrap()
    4439            6 :             .iter_historic_layers()
    4440           10 :             .map(|layer| layer.layer_name())
    4441            6 :             .collect_vec();
    4442            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4443            0 :             bail!("invalid layermap: {err}");
    4444            6 :         }
    4445            6 :         Ok(tline)
    4446            6 :     }
    4447              : 
    4448              :     /// Branch an existing timeline.
    4449            0 :     async fn branch_timeline(
    4450            0 :         self: &Arc<Self>,
    4451            0 :         src_timeline: &Arc<Timeline>,
    4452            0 :         dst_id: TimelineId,
    4453            0 :         start_lsn: Option<Lsn>,
    4454            0 :         ctx: &RequestContext,
    4455            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4456            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4457            0 :             .await
    4458            0 :     }
    4459              : 
    4460          232 :     async fn branch_timeline_impl(
    4461          232 :         self: &Arc<Self>,
    4462          232 :         src_timeline: &Arc<Timeline>,
    4463          232 :         dst_id: TimelineId,
    4464          232 :         start_lsn: Option<Lsn>,
    4465          232 :         _ctx: &RequestContext,
    4466          232 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4467          232 :         let src_id = src_timeline.timeline_id;
    4468              : 
    4469              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4470              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4471              :         // valid while we are creating the branch.
    4472          232 :         let _gc_cs = self.gc_cs.lock().await;
    4473              : 
    4474              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4475          232 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4476            2 :             let lsn = src_timeline.get_last_record_lsn();
    4477            2 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4478            2 :             lsn
    4479          232 :         });
    4480              : 
    4481              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4482          232 :         let timeline_create_guard = match self
    4483          232 :             .start_creating_timeline(
    4484          232 :                 dst_id,
    4485          232 :                 CreateTimelineIdempotency::Branch {
    4486          232 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4487          232 :                     ancestor_start_lsn: start_lsn,
    4488          232 :                 },
    4489          232 :             )
    4490          190 :             .await?
    4491              :         {
    4492          232 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4493            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4494            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4495              :             }
    4496              :         };
    4497              : 
    4498              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4499              :         // horizon on the source timeline
    4500              :         //
    4501              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4502              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4503              :         // planned GC cutoff in 'gc_info' is normally larger than
    4504              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4505              :         // changed the GC settings for the tenant to make the PITR window
    4506              :         // larger, but some of the data was already removed by an earlier GC
    4507              :         // iteration.
    4508              : 
    4509              :         // check against last actual 'latest_gc_cutoff' first
    4510          232 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4511          232 :         src_timeline
    4512          232 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4513          232 :             .context(format!(
    4514          232 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4515          232 :                 *latest_gc_cutoff_lsn,
    4516          232 :             ))
    4517          232 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4518              : 
    4519              :         // and then the planned GC cutoff
    4520              :         {
    4521          228 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4522          228 :             let cutoff = gc_info.min_cutoff();
    4523          228 :             if start_lsn < cutoff {
    4524            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4525            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4526            0 :                 )));
    4527          228 :             }
    4528          228 :         }
    4529          228 : 
    4530          228 :         //
    4531          228 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4532          228 :         // so that GC cannot advance the GC cutoff until we are finished.
    4533          228 :         // Proceed with the branch creation.
    4534          228 :         //
    4535          228 : 
    4536          228 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4537          228 :         // the timeline was branched at the current end of the source timeline.
    4538          228 :         let RecordLsn {
    4539          228 :             last: src_last,
    4540          228 :             prev: src_prev,
    4541          228 :         } = src_timeline.get_last_record_rlsn();
    4542          228 :         let dst_prev = if src_last == start_lsn {
    4543          216 :             Some(src_prev)
    4544              :         } else {
    4545           12 :             None
    4546              :         };
    4547              : 
    4548              :         // Create the metadata file, noting the ancestor of the new timeline.
    4549              :         // There is initially no data in it, but all the read-calls know to look
    4550              :         // into the ancestor.
    4551          228 :         let metadata = TimelineMetadata::new(
    4552          228 :             start_lsn,
    4553          228 :             dst_prev,
    4554          228 :             Some(src_id),
    4555          228 :             start_lsn,
    4556          228 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4557          228 :             src_timeline.initdb_lsn,
    4558          228 :             src_timeline.pg_version,
    4559          228 :         );
    4560              : 
    4561          228 :         let uninitialized_timeline = self
    4562          228 :             .prepare_new_timeline(
    4563          228 :                 dst_id,
    4564          228 :                 &metadata,
    4565          228 :                 timeline_create_guard,
    4566          228 :                 start_lsn + 1,
    4567          228 :                 Some(Arc::clone(src_timeline)),
    4568          228 :             )
    4569            0 :             .await?;
    4570              : 
    4571          228 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4572              : 
    4573              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4574              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4575              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4576              :         // could get incorrect information and remove more layers, than needed.
    4577              :         // See also https://github.com/neondatabase/neon/issues/3865
    4578          228 :         new_timeline
    4579          228 :             .remote_client
    4580          228 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4581          228 :             .context("branch initial metadata upload")?;
    4582              : 
    4583              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4584              : 
    4585          228 :         Ok(CreateTimelineResult::Created(new_timeline))
    4586          232 :     }
    4587              : 
    4588              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4589              :     #[cfg(test)]
    4590            2 :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4591              :     pub(crate) async fn bootstrap_timeline_test(
    4592              :         self: &Arc<Self>,
    4593              :         timeline_id: TimelineId,
    4594              :         pg_version: u32,
    4595              :         load_existing_initdb: Option<TimelineId>,
    4596              :         ctx: &RequestContext,
    4597              :     ) -> anyhow::Result<Arc<Timeline>> {
    4598              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4599              :             .await
    4600              :             .map_err(anyhow::Error::new)
    4601            2 :             .map(|r| r.into_timeline_for_test())
    4602              :     }
    4603              : 
    4604              :     /// Get exclusive access to the timeline ID for creation.
    4605              :     ///
    4606              :     /// Timeline-creating code paths must use this function before making changes
    4607              :     /// to in-memory or persistent state.
    4608              :     ///
    4609              :     /// The `state` parameter is a description of the timeline creation operation
    4610              :     /// we intend to perform.
    4611              :     /// If the timeline was already created in the meantime, we check whether this
    4612              :     /// request conflicts or is idempotent , based on `state`.
    4613          418 :     async fn start_creating_timeline(
    4614          418 :         self: &Arc<Self>,
    4615          418 :         new_timeline_id: TimelineId,
    4616          418 :         idempotency: CreateTimelineIdempotency,
    4617          418 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4618          418 :         let allow_offloaded = false;
    4619          418 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4620          416 :             Ok(create_guard) => {
    4621          416 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4622          416 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4623              :             }
    4624            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4625              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4626              :                 // Creation is in progress, we cannot create it again, and we cannot
    4627              :                 // check if this request matches the existing one, so caller must try
    4628              :                 // again later.
    4629            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4630              :             }
    4631            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4632              :             Err(TimelineExclusionError::AlreadyExists {
    4633            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4634            0 :                 ..
    4635            0 :             }) => {
    4636            0 :                 info!("timeline already exists but is offloaded");
    4637            0 :                 Err(CreateTimelineError::Conflict)
    4638              :             }
    4639              :             Err(TimelineExclusionError::AlreadyExists {
    4640            2 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4641            2 :                 arg,
    4642            2 :             }) => {
    4643            2 :                 {
    4644            2 :                     let existing = &existing.create_idempotency;
    4645            2 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4646            2 :                     debug!("timeline already exists");
    4647              : 
    4648            2 :                     match (existing, &arg) {
    4649              :                         // FailWithConflict => no idempotency check
    4650              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4651              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4652            2 :                             warn!("timeline already exists, failing request");
    4653            2 :                             return Err(CreateTimelineError::Conflict);
    4654              :                         }
    4655              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4656            0 :                         (x, y) if x == y => {
    4657            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4658              :                             // fallthrough
    4659              :                         }
    4660              :                         (_, _) => {
    4661            0 :                             warn!("idempotency conflict, failing request");
    4662            0 :                             return Err(CreateTimelineError::Conflict);
    4663              :                         }
    4664              :                     }
    4665              :                 }
    4666              : 
    4667            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4668              :             }
    4669              :         }
    4670          418 :     }
    4671              : 
    4672            0 :     async fn upload_initdb(
    4673            0 :         &self,
    4674            0 :         timelines_path: &Utf8PathBuf,
    4675            0 :         pgdata_path: &Utf8PathBuf,
    4676            0 :         timeline_id: &TimelineId,
    4677            0 :     ) -> anyhow::Result<()> {
    4678            0 :         let temp_path = timelines_path.join(format!(
    4679            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4680            0 :         ));
    4681            0 : 
    4682            0 :         scopeguard::defer! {
    4683            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4684            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4685            0 :             }
    4686            0 :         }
    4687              : 
    4688            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4689              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4690            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4691            0 :             warn!(
    4692            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4693              :             );
    4694            0 :         }
    4695              : 
    4696            0 :         pausable_failpoint!("before-initdb-upload");
    4697              : 
    4698            0 :         backoff::retry(
    4699            0 :             || async {
    4700            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4701            0 :                     &self.remote_storage,
    4702            0 :                     &self.tenant_shard_id.tenant_id,
    4703            0 :                     timeline_id,
    4704            0 :                     pgdata_zstd.try_clone().await?,
    4705            0 :                     tar_zst_size,
    4706            0 :                     &self.cancel,
    4707              :                 )
    4708            0 :                 .await
    4709            0 :             },
    4710            0 :             |_| false,
    4711            0 :             3,
    4712            0 :             u32::MAX,
    4713            0 :             "persist_initdb_tar_zst",
    4714            0 :             &self.cancel,
    4715            0 :         )
    4716            0 :         .await
    4717            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4718            0 :         .and_then(|x| x)
    4719            0 :     }
    4720              : 
    4721              :     /// - run initdb to init temporary instance and get bootstrap data
    4722              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4723            2 :     async fn bootstrap_timeline(
    4724            2 :         self: &Arc<Self>,
    4725            2 :         timeline_id: TimelineId,
    4726            2 :         pg_version: u32,
    4727            2 :         load_existing_initdb: Option<TimelineId>,
    4728            2 :         ctx: &RequestContext,
    4729            2 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4730            2 :         let timeline_create_guard = match self
    4731            2 :             .start_creating_timeline(
    4732            2 :                 timeline_id,
    4733            2 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4734            2 :             )
    4735            2 :             .await?
    4736              :         {
    4737            2 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4738            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4739            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4740              :             }
    4741              :         };
    4742              : 
    4743              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4744              :         // temporary directory for basebackup files for the given timeline.
    4745              : 
    4746            2 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4747            2 :         let pgdata_path = path_with_suffix_extension(
    4748            2 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4749            2 :             TEMP_FILE_SUFFIX,
    4750            2 :         );
    4751            2 : 
    4752            2 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4753            2 :         // we won't race with other creations or existent timelines with the same path.
    4754            2 :         if pgdata_path.exists() {
    4755            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4756            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4757            0 :             })?;
    4758            2 :         }
    4759              : 
    4760              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4761            2 :         scopeguard::defer! {
    4762            2 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4763            2 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4764            2 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4765            2 :             }
    4766            2 :         }
    4767            2 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4768            2 :             if existing_initdb_timeline_id != timeline_id {
    4769            0 :                 let source_path = &remote_initdb_archive_path(
    4770            0 :                     &self.tenant_shard_id.tenant_id,
    4771            0 :                     &existing_initdb_timeline_id,
    4772            0 :                 );
    4773            0 :                 let dest_path =
    4774            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4775            0 : 
    4776            0 :                 // if this fails, it will get retried by retried control plane requests
    4777            0 :                 self.remote_storage
    4778            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4779            0 :                     .await
    4780            0 :                     .context("copy initdb tar")?;
    4781            2 :             }
    4782            2 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4783            2 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4784            2 :                     self.conf,
    4785            2 :                     &self.remote_storage,
    4786            2 :                     &self.tenant_shard_id,
    4787            2 :                     &existing_initdb_timeline_id,
    4788            2 :                     &self.cancel,
    4789            2 :                 )
    4790          675 :                 .await
    4791            2 :                 .context("download initdb tar")?;
    4792              : 
    4793            2 :             scopeguard::defer! {
    4794            2 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4795            2 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4796            2 :                 }
    4797            2 :             }
    4798            2 : 
    4799            2 :             let buf_read =
    4800            2 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4801            2 :             extract_zst_tarball(&pgdata_path, buf_read)
    4802        11081 :                 .await
    4803            2 :                 .context("extract initdb tar")?;
    4804              :         } else {
    4805              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4806            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4807            0 :                 .await
    4808            0 :                 .context("run initdb")?;
    4809              : 
    4810              :             // Upload the created data dir to S3
    4811            0 :             if self.tenant_shard_id().is_shard_zero() {
    4812            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4813            0 :                     .await?;
    4814            0 :             }
    4815              :         }
    4816            2 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4817            2 : 
    4818            2 :         // Import the contents of the data directory at the initial checkpoint
    4819            2 :         // LSN, and any WAL after that.
    4820            2 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4821            2 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4822            2 :         let new_metadata = TimelineMetadata::new(
    4823            2 :             Lsn(0),
    4824            2 :             None,
    4825            2 :             None,
    4826            2 :             Lsn(0),
    4827            2 :             pgdata_lsn,
    4828            2 :             pgdata_lsn,
    4829            2 :             pg_version,
    4830            2 :         );
    4831            2 :         let raw_timeline = self
    4832            2 :             .prepare_new_timeline(
    4833            2 :                 timeline_id,
    4834            2 :                 &new_metadata,
    4835            2 :                 timeline_create_guard,
    4836            2 :                 pgdata_lsn,
    4837            2 :                 None,
    4838            2 :             )
    4839            0 :             .await?;
    4840              : 
    4841            2 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4842            2 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4843              : 
    4844              :         // Flush the new layer files to disk, before we make the timeline as available to
    4845              :         // the outside world.
    4846              :         //
    4847              :         // Flush loop needs to be spawned in order to be able to flush.
    4848            2 :         unfinished_timeline.maybe_spawn_flush_loop();
    4849            2 : 
    4850            2 :         import_datadir::import_timeline_from_postgres_datadir(
    4851            2 :             unfinished_timeline,
    4852            2 :             &pgdata_path,
    4853            2 :             pgdata_lsn,
    4854            2 :             ctx,
    4855            2 :         )
    4856         9381 :         .await
    4857            2 :         .with_context(|| {
    4858            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    4859            2 :         })?;
    4860              : 
    4861            2 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    4862            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    4863            0 :                 "failpoint before-checkpoint-new-timeline"
    4864            0 :             )))
    4865            2 :         });
    4866              : 
    4867            2 :         unfinished_timeline
    4868            2 :             .freeze_and_flush()
    4869            2 :             .await
    4870            2 :             .with_context(|| {
    4871            0 :                 format!(
    4872            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    4873            0 :                 )
    4874            2 :             })?;
    4875              : 
    4876              :         // All done!
    4877            2 :         let timeline = raw_timeline.finish_creation()?;
    4878              : 
    4879              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4880              : 
    4881            2 :         Ok(CreateTimelineResult::Created(timeline))
    4882            2 :     }
    4883              : 
    4884          412 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    4885          412 :         RemoteTimelineClient::new(
    4886          412 :             self.remote_storage.clone(),
    4887          412 :             self.deletion_queue_client.clone(),
    4888          412 :             self.conf,
    4889          412 :             self.tenant_shard_id,
    4890          412 :             timeline_id,
    4891          412 :             self.generation,
    4892          412 :             &self.tenant_conf.load().location,
    4893          412 :         )
    4894          412 :     }
    4895              : 
    4896              :     /// Call this before constructing a timeline, to build its required structures
    4897          412 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    4898          412 :         TimelineResources {
    4899          412 :             remote_client: self.build_timeline_remote_client(timeline_id),
    4900          412 :             timeline_get_throttle: self.timeline_get_throttle.clone(),
    4901          412 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    4902          412 :         }
    4903          412 :     }
    4904              : 
    4905              :     /// Creates intermediate timeline structure and its files.
    4906              :     ///
    4907              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    4908              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    4909              :     /// `finish_creation` to insert the Timeline into the timelines map.
    4910          412 :     async fn prepare_new_timeline<'a>(
    4911          412 :         &'a self,
    4912          412 :         new_timeline_id: TimelineId,
    4913          412 :         new_metadata: &TimelineMetadata,
    4914          412 :         create_guard: TimelineCreateGuard,
    4915          412 :         start_lsn: Lsn,
    4916          412 :         ancestor: Option<Arc<Timeline>>,
    4917          412 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    4918          412 :         let tenant_shard_id = self.tenant_shard_id;
    4919          412 : 
    4920          412 :         let resources = self.build_timeline_resources(new_timeline_id);
    4921          412 :         resources
    4922          412 :             .remote_client
    4923          412 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    4924              : 
    4925          412 :         let timeline_struct = self
    4926          412 :             .create_timeline_struct(
    4927          412 :                 new_timeline_id,
    4928          412 :                 new_metadata,
    4929          412 :                 ancestor,
    4930          412 :                 resources,
    4931          412 :                 CreateTimelineCause::Load,
    4932          412 :                 create_guard.idempotency.clone(),
    4933          412 :             )
    4934          412 :             .context("Failed to create timeline data structure")?;
    4935              : 
    4936          412 :         timeline_struct.init_empty_layer_map(start_lsn);
    4937              : 
    4938          412 :         if let Err(e) = self
    4939          412 :             .create_timeline_files(&create_guard.timeline_path)
    4940            0 :             .await
    4941              :         {
    4942            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    4943            0 :             cleanup_timeline_directory(create_guard);
    4944            0 :             return Err(e);
    4945          412 :         }
    4946          412 : 
    4947          412 :         debug!(
    4948            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    4949              :         );
    4950              : 
    4951          412 :         Ok(UninitializedTimeline::new(
    4952          412 :             self,
    4953          412 :             new_timeline_id,
    4954          412 :             Some((timeline_struct, create_guard)),
    4955          412 :         ))
    4956          412 :     }
    4957              : 
    4958          412 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    4959          412 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    4960              : 
    4961          412 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    4962            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    4963          412 :         });
    4964              : 
    4965          412 :         Ok(())
    4966          412 :     }
    4967              : 
    4968              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    4969              :     /// concurrent attempts to create the same timeline.
    4970              :     ///
    4971              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    4972              :     /// offloaded timelines or not.
    4973          418 :     fn create_timeline_create_guard(
    4974          418 :         self: &Arc<Self>,
    4975          418 :         timeline_id: TimelineId,
    4976          418 :         idempotency: CreateTimelineIdempotency,
    4977          418 :         allow_offloaded: bool,
    4978          418 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    4979          418 :         let tenant_shard_id = self.tenant_shard_id;
    4980          418 : 
    4981          418 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    4982              : 
    4983          418 :         let create_guard = TimelineCreateGuard::new(
    4984          418 :             self,
    4985          418 :             timeline_id,
    4986          418 :             timeline_path.clone(),
    4987          418 :             idempotency,
    4988          418 :             allow_offloaded,
    4989          418 :         )?;
    4990              : 
    4991              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    4992              :         // for creation.
    4993              :         // A timeline directory should never exist on disk already:
    4994              :         // - a previous failed creation would have cleaned up after itself
    4995              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    4996              :         //
    4997              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    4998              :         // this error may indicate a bug in cleanup on failed creations.
    4999          416 :         if timeline_path.exists() {
    5000            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5001            0 :                 "Timeline directory already exists! This is a bug."
    5002            0 :             )));
    5003          416 :         }
    5004          416 : 
    5005          416 :         Ok(create_guard)
    5006          418 :     }
    5007              : 
    5008              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5009              :     ///
    5010              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5011            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5012              :     pub async fn gather_size_inputs(
    5013              :         &self,
    5014              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5015              :         // (only if it is shorter than the real cutoff).
    5016              :         max_retention_period: Option<u64>,
    5017              :         cause: LogicalSizeCalculationCause,
    5018              :         cancel: &CancellationToken,
    5019              :         ctx: &RequestContext,
    5020              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5021              :         let logical_sizes_at_once = self
    5022              :             .conf
    5023              :             .concurrent_tenant_size_logical_size_queries
    5024              :             .inner();
    5025              : 
    5026              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5027              :         //
    5028              :         // But the only case where we need to run multiple of these at once is when we
    5029              :         // request a size for a tenant manually via API, while another background calculation
    5030              :         // is in progress (which is not a common case).
    5031              :         //
    5032              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5033              :         let mut shared_cache = tokio::select! {
    5034              :             locked = self.cached_logical_sizes.lock() => locked,
    5035              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5036              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5037              :         };
    5038              : 
    5039              :         size::gather_inputs(
    5040              :             self,
    5041              :             logical_sizes_at_once,
    5042              :             max_retention_period,
    5043              :             &mut shared_cache,
    5044              :             cause,
    5045              :             cancel,
    5046              :             ctx,
    5047              :         )
    5048              :         .await
    5049              :     }
    5050              : 
    5051              :     /// Calculate synthetic tenant size and cache the result.
    5052              :     /// This is periodically called by background worker.
    5053              :     /// result is cached in tenant struct
    5054            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5055              :     pub async fn calculate_synthetic_size(
    5056              :         &self,
    5057              :         cause: LogicalSizeCalculationCause,
    5058              :         cancel: &CancellationToken,
    5059              :         ctx: &RequestContext,
    5060              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5061              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5062              : 
    5063              :         let size = inputs.calculate();
    5064              : 
    5065              :         self.set_cached_synthetic_size(size);
    5066              : 
    5067              :         Ok(size)
    5068              :     }
    5069              : 
    5070              :     /// Cache given synthetic size and update the metric value
    5071            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5072            0 :         self.cached_synthetic_tenant_size
    5073            0 :             .store(size, Ordering::Relaxed);
    5074            0 : 
    5075            0 :         // Only shard zero should be calculating synthetic sizes
    5076            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5077              : 
    5078            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5079            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5080            0 :             .unwrap()
    5081            0 :             .set(size);
    5082            0 :     }
    5083              : 
    5084            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5085            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5086            0 :     }
    5087              : 
    5088              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5089              :     ///
    5090              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5091              :     /// from an external API handler.
    5092              :     ///
    5093              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5094              :     /// still bounded by tenant/timeline shutdown.
    5095            0 :     #[tracing::instrument(skip_all)]
    5096              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5097              :         let timelines = self.timelines.lock().unwrap().clone();
    5098              : 
    5099            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5100            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5101            0 :             timeline.freeze_and_flush().await?;
    5102            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5103            0 :             timeline.remote_client.wait_completion().await?;
    5104              : 
    5105            0 :             Ok(())
    5106            0 :         }
    5107              : 
    5108              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5109              :         // aborted when this function's future is cancelled: they should stay alive
    5110              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5111              :         // before Timeline shutdown completes.
    5112              :         let mut results = FuturesUnordered::new();
    5113              : 
    5114              :         for (_timeline_id, timeline) in timelines {
    5115              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5116              :             // means that if this function's future is cancelled, the Timeline shutdown
    5117              :             // will still wait for any I/O in here to complete.
    5118              :             let Ok(gate) = timeline.gate.enter() else {
    5119              :                 continue;
    5120              :             };
    5121            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5122              :             results.push(jh);
    5123              :         }
    5124              : 
    5125              :         while let Some(r) = results.next().await {
    5126              :             if let Err(e) = r {
    5127              :                 if !e.is_cancelled() && !e.is_panic() {
    5128              :                     tracing::error!("unexpected join error: {e:?}");
    5129              :                 }
    5130              :             }
    5131              :         }
    5132              : 
    5133              :         // The flushes we did above were just writes, but the Tenant might have had
    5134              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5135              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5136              :         // because it's typically a no-op.
    5137              :         match self.deletion_queue_client.flush_execute().await {
    5138              :             Ok(_) => {}
    5139              :             Err(DeletionQueueError::ShuttingDown) => {}
    5140              :         }
    5141              : 
    5142              :         Ok(())
    5143              :     }
    5144              : 
    5145            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5146            0 :         self.tenant_conf.load().tenant_conf.clone()
    5147            0 :     }
    5148              : 
    5149              :     /// How much local storage would this tenant like to have?  It can cope with
    5150              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5151              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5152              :     /// by keeping important things on local disk.
    5153              :     ///
    5154              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5155              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5156              :     /// actually use more than they report here.
    5157            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5158            0 :         let timelines = self.timelines.lock().unwrap();
    5159            0 : 
    5160            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5161            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5162            0 :         // of them is used actively enough to occupy space on disk.
    5163            0 :         timelines
    5164            0 :             .values()
    5165            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5166            0 :             .max()
    5167            0 :             .unwrap_or(0)
    5168            0 :     }
    5169              : 
    5170              :     /// Serialize and write the latest TenantManifest to remote storage.
    5171            2 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5172              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5173              :         // must be loaded while holding this lock. This makes it safe to call this function
    5174              :         // from anywhere without worrying about colliding updates.
    5175            2 :         let mut guard = tokio::select! {
    5176            2 :             g = self.tenant_manifest_upload.lock() => {
    5177            2 :                 g
    5178              :             },
    5179            2 :             _ = self.cancel.cancelled() => {
    5180            0 :                 return Err(TenantManifestError::Cancelled);
    5181              :             }
    5182              :         };
    5183              : 
    5184            2 :         let manifest = self.build_tenant_manifest();
    5185            2 :         if Some(&manifest) == (*guard).as_ref() {
    5186              :             // Optimisation: skip uploads that don't change anything.
    5187            0 :             return Ok(());
    5188            2 :         }
    5189            2 : 
    5190            2 :         upload_tenant_manifest(
    5191            2 :             &self.remote_storage,
    5192            2 :             &self.tenant_shard_id,
    5193            2 :             self.generation,
    5194            2 :             &manifest,
    5195            2 :             &self.cancel,
    5196            2 :         )
    5197            4 :         .await
    5198            2 :         .map_err(|e| {
    5199            0 :             if self.cancel.is_cancelled() {
    5200            0 :                 TenantManifestError::Cancelled
    5201              :             } else {
    5202            0 :                 TenantManifestError::RemoteStorage(e)
    5203              :             }
    5204            2 :         })?;
    5205              : 
    5206              :         // Store the successfully uploaded manifest, so that future callers can avoid
    5207              :         // re-uploading the same thing.
    5208            2 :         *guard = Some(manifest);
    5209            2 : 
    5210            2 :         Ok(())
    5211            2 :     }
    5212              : }
    5213              : 
    5214              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5215              : /// to get bootstrap data for timeline initialization.
    5216            0 : async fn run_initdb(
    5217            0 :     conf: &'static PageServerConf,
    5218            0 :     initdb_target_dir: &Utf8Path,
    5219            0 :     pg_version: u32,
    5220            0 :     cancel: &CancellationToken,
    5221            0 : ) -> Result<(), InitdbError> {
    5222            0 :     let initdb_bin_path = conf
    5223            0 :         .pg_bin_dir(pg_version)
    5224            0 :         .map_err(InitdbError::Other)?
    5225            0 :         .join("initdb");
    5226            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5227            0 :     info!(
    5228            0 :         "running {} in {}, libdir: {}",
    5229              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5230              :     );
    5231              : 
    5232            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    5233              : 
    5234            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5235            0 :         superuser: &conf.superuser,
    5236            0 :         locale: &conf.locale,
    5237            0 :         initdb_bin: &initdb_bin_path,
    5238            0 :         pg_version,
    5239            0 :         library_search_path: &initdb_lib_dir,
    5240            0 :         pgdata: initdb_target_dir,
    5241            0 :     })
    5242            0 :     .await
    5243            0 :     .map_err(InitdbError::Inner);
    5244            0 : 
    5245            0 :     // This isn't true cancellation support, see above. Still return an error to
    5246            0 :     // excercise the cancellation code path.
    5247            0 :     if cancel.is_cancelled() {
    5248            0 :         return Err(InitdbError::Cancelled);
    5249            0 :     }
    5250            0 : 
    5251            0 :     res
    5252            0 : }
    5253              : 
    5254              : /// Dump contents of a layer file to stdout.
    5255            0 : pub async fn dump_layerfile_from_path(
    5256            0 :     path: &Utf8Path,
    5257            0 :     verbose: bool,
    5258            0 :     ctx: &RequestContext,
    5259            0 : ) -> anyhow::Result<()> {
    5260              :     use std::os::unix::fs::FileExt;
    5261              : 
    5262              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5263              :     // file.
    5264            0 :     let file = File::open(path)?;
    5265            0 :     let mut header_buf = [0u8; 2];
    5266            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5267              : 
    5268            0 :     match u16::from_be_bytes(header_buf) {
    5269              :         crate::IMAGE_FILE_MAGIC => {
    5270            0 :             ImageLayer::new_for_path(path, file)?
    5271            0 :                 .dump(verbose, ctx)
    5272            0 :                 .await?
    5273              :         }
    5274              :         crate::DELTA_FILE_MAGIC => {
    5275            0 :             DeltaLayer::new_for_path(path, file)?
    5276            0 :                 .dump(verbose, ctx)
    5277            0 :                 .await?
    5278              :         }
    5279            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5280              :     }
    5281              : 
    5282            0 :     Ok(())
    5283            0 : }
    5284              : 
    5285              : #[cfg(test)]
    5286              : pub(crate) mod harness {
    5287              :     use bytes::{Bytes, BytesMut};
    5288              :     use once_cell::sync::OnceCell;
    5289              :     use pageserver_api::models::ShardParameters;
    5290              :     use pageserver_api::shard::ShardIndex;
    5291              :     use utils::logging;
    5292              : 
    5293              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5294              :     use crate::l0_flush::L0FlushConfig;
    5295              :     use crate::walredo::apply_neon;
    5296              :     use pageserver_api::key::Key;
    5297              :     use pageserver_api::record::NeonWalRecord;
    5298              : 
    5299              :     use super::*;
    5300              :     use hex_literal::hex;
    5301              :     use utils::id::TenantId;
    5302              : 
    5303              :     pub const TIMELINE_ID: TimelineId =
    5304              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5305              :     pub const NEW_TIMELINE_ID: TimelineId =
    5306              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5307              : 
    5308              :     /// Convenience function to create a page image with given string as the only content
    5309      5028721 :     pub fn test_img(s: &str) -> Bytes {
    5310      5028721 :         let mut buf = BytesMut::new();
    5311      5028721 :         buf.extend_from_slice(s.as_bytes());
    5312      5028721 :         buf.resize(64, 0);
    5313      5028721 : 
    5314      5028721 :         buf.freeze()
    5315      5028721 :     }
    5316              : 
    5317              :     impl From<TenantConf> for TenantConfOpt {
    5318          192 :         fn from(tenant_conf: TenantConf) -> Self {
    5319          192 :             Self {
    5320          192 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5321          192 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5322          192 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5323          192 :                 compaction_period: Some(tenant_conf.compaction_period),
    5324          192 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5325          192 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5326          192 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5327          192 :                 gc_period: Some(tenant_conf.gc_period),
    5328          192 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5329          192 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5330          192 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5331          192 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5332          192 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5333          192 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5334          192 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5335          192 :                 evictions_low_residence_duration_metric_threshold: Some(
    5336          192 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5337          192 :                 ),
    5338          192 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5339          192 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5340          192 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5341          192 :                 image_layer_creation_check_threshold: Some(
    5342          192 :                     tenant_conf.image_layer_creation_check_threshold,
    5343          192 :                 ),
    5344          192 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5345          192 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5346          192 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5347          192 :             }
    5348          192 :         }
    5349              :     }
    5350              : 
    5351              :     pub struct TenantHarness {
    5352              :         pub conf: &'static PageServerConf,
    5353              :         pub tenant_conf: TenantConf,
    5354              :         pub tenant_shard_id: TenantShardId,
    5355              :         pub generation: Generation,
    5356              :         pub shard: ShardIndex,
    5357              :         pub remote_storage: GenericRemoteStorage,
    5358              :         pub remote_fs_dir: Utf8PathBuf,
    5359              :         pub deletion_queue: MockDeletionQueue,
    5360              :     }
    5361              : 
    5362              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5363              : 
    5364          208 :     pub(crate) fn setup_logging() {
    5365          208 :         LOG_HANDLE.get_or_init(|| {
    5366          196 :             logging::init(
    5367          196 :                 logging::LogFormat::Test,
    5368          196 :                 // enable it in case the tests exercise code paths that use
    5369          196 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5370          196 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5371          196 :                 logging::Output::Stdout,
    5372          196 :             )
    5373          196 :             .expect("Failed to init test logging")
    5374          208 :         });
    5375          208 :     }
    5376              : 
    5377              :     impl TenantHarness {
    5378          192 :         pub async fn create_custom(
    5379          192 :             test_name: &'static str,
    5380          192 :             tenant_conf: TenantConf,
    5381          192 :             tenant_id: TenantId,
    5382          192 :             shard_identity: ShardIdentity,
    5383          192 :             generation: Generation,
    5384          192 :         ) -> anyhow::Result<Self> {
    5385          192 :             setup_logging();
    5386          192 : 
    5387          192 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5388          192 :             let _ = fs::remove_dir_all(&repo_dir);
    5389          192 :             fs::create_dir_all(&repo_dir)?;
    5390              : 
    5391          192 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5392          192 :             // Make a static copy of the config. This can never be free'd, but that's
    5393          192 :             // OK in a test.
    5394          192 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5395          192 : 
    5396          192 :             let shard = shard_identity.shard_index();
    5397          192 :             let tenant_shard_id = TenantShardId {
    5398          192 :                 tenant_id,
    5399          192 :                 shard_number: shard.shard_number,
    5400          192 :                 shard_count: shard.shard_count,
    5401          192 :             };
    5402          192 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5403          192 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5404              : 
    5405              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5406          192 :             let remote_fs_dir = conf.workdir.join("localfs");
    5407          192 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5408          192 :             let config = RemoteStorageConfig {
    5409          192 :                 storage: RemoteStorageKind::LocalFs {
    5410          192 :                     local_path: remote_fs_dir.clone(),
    5411          192 :                 },
    5412          192 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5413          192 :             };
    5414          192 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5415          192 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5416          192 : 
    5417          192 :             Ok(Self {
    5418          192 :                 conf,
    5419          192 :                 tenant_conf,
    5420          192 :                 tenant_shard_id,
    5421          192 :                 generation,
    5422          192 :                 shard,
    5423          192 :                 remote_storage,
    5424          192 :                 remote_fs_dir,
    5425          192 :                 deletion_queue,
    5426          192 :             })
    5427          192 :         }
    5428              : 
    5429          180 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5430          180 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5431          180 :             // The tests perform them manually if needed.
    5432          180 :             let tenant_conf = TenantConf {
    5433          180 :                 gc_period: Duration::ZERO,
    5434          180 :                 compaction_period: Duration::ZERO,
    5435          180 :                 ..TenantConf::default()
    5436          180 :             };
    5437          180 :             let tenant_id = TenantId::generate();
    5438          180 :             let shard = ShardIdentity::unsharded();
    5439          180 :             Self::create_custom(
    5440          180 :                 test_name,
    5441          180 :                 tenant_conf,
    5442          180 :                 tenant_id,
    5443          180 :                 shard,
    5444          180 :                 Generation::new(0xdeadbeef),
    5445          180 :             )
    5446            0 :             .await
    5447          180 :         }
    5448              : 
    5449           20 :         pub fn span(&self) -> tracing::Span {
    5450           20 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5451           20 :         }
    5452              : 
    5453          192 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5454          192 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5455          192 :             (
    5456          192 :                 self.do_try_load(&ctx)
    5457         1865 :                     .await
    5458          192 :                     .expect("failed to load test tenant"),
    5459          192 :                 ctx,
    5460          192 :             )
    5461          192 :         }
    5462              : 
    5463          192 :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5464              :         pub(crate) async fn do_try_load(
    5465              :             &self,
    5466              :             ctx: &RequestContext,
    5467              :         ) -> anyhow::Result<Arc<Tenant>> {
    5468              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5469              : 
    5470              :             let tenant = Arc::new(Tenant::new(
    5471              :                 TenantState::Attaching,
    5472              :                 self.conf,
    5473              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5474              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5475              :                     self.generation,
    5476              :                     &ShardParameters::default(),
    5477              :                 ))
    5478              :                 .unwrap(),
    5479              :                 // This is a legacy/test code path: sharding isn't supported here.
    5480              :                 ShardIdentity::unsharded(),
    5481              :                 Some(walredo_mgr),
    5482              :                 self.tenant_shard_id,
    5483              :                 self.remote_storage.clone(),
    5484              :                 self.deletion_queue.new_client(),
    5485              :                 // TODO: ideally we should run all unit tests with both configs
    5486              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5487              :             ));
    5488              : 
    5489              :             let preload = tenant
    5490              :                 .preload(&self.remote_storage, CancellationToken::new())
    5491              :                 .await?;
    5492              :             tenant.attach(Some(preload), ctx).await?;
    5493              : 
    5494              :             tenant.state.send_replace(TenantState::Active);
    5495              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5496              :                 timeline.set_state(TimelineState::Active);
    5497              :             }
    5498              :             Ok(tenant)
    5499              :         }
    5500              : 
    5501            2 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5502            2 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5503            2 :         }
    5504              :     }
    5505              : 
    5506              :     // Mock WAL redo manager that doesn't do much
    5507              :     pub(crate) struct TestRedoManager;
    5508              : 
    5509              :     impl TestRedoManager {
    5510              :         /// # Cancel-Safety
    5511              :         ///
    5512              :         /// This method is cancellation-safe.
    5513          410 :         pub async fn request_redo(
    5514          410 :             &self,
    5515          410 :             key: Key,
    5516          410 :             lsn: Lsn,
    5517          410 :             base_img: Option<(Lsn, Bytes)>,
    5518          410 :             records: Vec<(Lsn, NeonWalRecord)>,
    5519          410 :             _pg_version: u32,
    5520          410 :         ) -> Result<Bytes, walredo::Error> {
    5521          570 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5522          410 :             if records_neon {
    5523              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5524          410 :                 let mut page = match (base_img, records.first()) {
    5525          344 :                     (Some((_lsn, img)), _) => {
    5526          344 :                         let mut page = BytesMut::new();
    5527          344 :                         page.extend_from_slice(&img);
    5528          344 :                         page
    5529              :                     }
    5530           66 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5531              :                     _ => {
    5532            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5533              :                     }
    5534              :                 };
    5535              : 
    5536          980 :                 for (record_lsn, record) in records {
    5537          570 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5538              :                 }
    5539          410 :                 Ok(page.freeze())
    5540              :             } else {
    5541              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5542            0 :                 let s = format!(
    5543            0 :                     "redo for {} to get to {}, with {} and {} records",
    5544            0 :                     key,
    5545            0 :                     lsn,
    5546            0 :                     if base_img.is_some() {
    5547            0 :                         "base image"
    5548              :                     } else {
    5549            0 :                         "no base image"
    5550              :                     },
    5551            0 :                     records.len()
    5552            0 :                 );
    5553            0 :                 println!("{s}");
    5554            0 : 
    5555            0 :                 Ok(test_img(&s))
    5556              :             }
    5557          410 :         }
    5558              :     }
    5559              : }
    5560              : 
    5561              : #[cfg(test)]
    5562              : mod tests {
    5563              :     use std::collections::{BTreeMap, BTreeSet};
    5564              : 
    5565              :     use super::*;
    5566              :     use crate::keyspace::KeySpaceAccum;
    5567              :     use crate::tenant::harness::*;
    5568              :     use crate::tenant::timeline::CompactFlags;
    5569              :     use crate::DEFAULT_PG_VERSION;
    5570              :     use bytes::{Bytes, BytesMut};
    5571              :     use hex_literal::hex;
    5572              :     use itertools::Itertools;
    5573              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
    5574              :     use pageserver_api::keyspace::KeySpace;
    5575              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5576              :     use pageserver_api::value::Value;
    5577              :     use pageserver_compaction::helpers::overlaps_with;
    5578              :     use rand::{thread_rng, Rng};
    5579              :     use storage_layer::PersistentLayerKey;
    5580              :     use tests::storage_layer::ValuesReconstructState;
    5581              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5582              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5583              :     use utils::id::TenantId;
    5584              : 
    5585              :     #[cfg(feature = "testing")]
    5586              :     use pageserver_api::record::NeonWalRecord;
    5587              :     #[cfg(feature = "testing")]
    5588              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5589              :     #[cfg(feature = "testing")]
    5590              :     use timeline::GcInfo;
    5591              : 
    5592              :     static TEST_KEY: Lazy<Key> =
    5593           18 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5594              : 
    5595              :     #[tokio::test]
    5596            2 :     async fn test_basic() -> anyhow::Result<()> {
    5597           20 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5598            2 :         let tline = tenant
    5599            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5600            6 :             .await?;
    5601            2 : 
    5602            2 :         let mut writer = tline.writer().await;
    5603            2 :         writer
    5604            2 :             .put(
    5605            2 :                 *TEST_KEY,
    5606            2 :                 Lsn(0x10),
    5607            2 :                 &Value::Image(test_img("foo at 0x10")),
    5608            2 :                 &ctx,
    5609            2 :             )
    5610            2 :             .await?;
    5611            2 :         writer.finish_write(Lsn(0x10));
    5612            2 :         drop(writer);
    5613            2 : 
    5614            2 :         let mut writer = tline.writer().await;
    5615            2 :         writer
    5616            2 :             .put(
    5617            2 :                 *TEST_KEY,
    5618            2 :                 Lsn(0x20),
    5619            2 :                 &Value::Image(test_img("foo at 0x20")),
    5620            2 :                 &ctx,
    5621            2 :             )
    5622            2 :             .await?;
    5623            2 :         writer.finish_write(Lsn(0x20));
    5624            2 :         drop(writer);
    5625            2 : 
    5626            2 :         assert_eq!(
    5627            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5628            2 :             test_img("foo at 0x10")
    5629            2 :         );
    5630            2 :         assert_eq!(
    5631            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5632            2 :             test_img("foo at 0x10")
    5633            2 :         );
    5634            2 :         assert_eq!(
    5635            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5636            2 :             test_img("foo at 0x20")
    5637            2 :         );
    5638            2 : 
    5639            2 :         Ok(())
    5640            2 :     }
    5641              : 
    5642              :     #[tokio::test]
    5643            2 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5644            2 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5645            2 :             .await?
    5646            2 :             .load()
    5647           20 :             .await;
    5648            2 :         let _ = tenant
    5649            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5650            6 :             .await?;
    5651            2 : 
    5652            2 :         match tenant
    5653            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5654            2 :             .await
    5655            2 :         {
    5656            2 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5657            2 :             Err(e) => assert_eq!(
    5658            2 :                 e.to_string(),
    5659            2 :                 "timeline already exists with different parameters".to_string()
    5660            2 :             ),
    5661            2 :         }
    5662            2 : 
    5663            2 :         Ok(())
    5664            2 :     }
    5665              : 
    5666              :     /// Convenience function to create a page image with given string as the only content
    5667           10 :     pub fn test_value(s: &str) -> Value {
    5668           10 :         let mut buf = BytesMut::new();
    5669           10 :         buf.extend_from_slice(s.as_bytes());
    5670           10 :         Value::Image(buf.freeze())
    5671           10 :     }
    5672              : 
    5673              :     ///
    5674              :     /// Test branch creation
    5675              :     ///
    5676              :     #[tokio::test]
    5677            2 :     async fn test_branch() -> anyhow::Result<()> {
    5678            2 :         use std::str::from_utf8;
    5679            2 : 
    5680           20 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5681            2 :         let tline = tenant
    5682            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5683            6 :             .await?;
    5684            2 :         let mut writer = tline.writer().await;
    5685            2 : 
    5686            2 :         #[allow(non_snake_case)]
    5687            2 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5688            2 :         #[allow(non_snake_case)]
    5689            2 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5690            2 : 
    5691            2 :         // Insert a value on the timeline
    5692            2 :         writer
    5693            2 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5694            2 :             .await?;
    5695            2 :         writer
    5696            2 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5697            2 :             .await?;
    5698            2 :         writer.finish_write(Lsn(0x20));
    5699            2 : 
    5700            2 :         writer
    5701            2 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5702            2 :             .await?;
    5703            2 :         writer.finish_write(Lsn(0x30));
    5704            2 :         writer
    5705            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5706            2 :             .await?;
    5707            2 :         writer.finish_write(Lsn(0x40));
    5708            2 : 
    5709            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5710            2 : 
    5711            2 :         // Branch the history, modify relation differently on the new timeline
    5712            2 :         tenant
    5713            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5714            2 :             .await?;
    5715            2 :         let newtline = tenant
    5716            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5717            2 :             .expect("Should have a local timeline");
    5718            2 :         let mut new_writer = newtline.writer().await;
    5719            2 :         new_writer
    5720            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5721            2 :             .await?;
    5722            2 :         new_writer.finish_write(Lsn(0x40));
    5723            2 : 
    5724            2 :         // Check page contents on both branches
    5725            2 :         assert_eq!(
    5726            2 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5727            2 :             "foo at 0x40"
    5728            2 :         );
    5729            2 :         assert_eq!(
    5730            2 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5731            2 :             "bar at 0x40"
    5732            2 :         );
    5733            2 :         assert_eq!(
    5734            2 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5735            2 :             "foobar at 0x20"
    5736            2 :         );
    5737            2 : 
    5738            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5739            2 : 
    5740            2 :         Ok(())
    5741            2 :     }
    5742              : 
    5743           20 :     async fn make_some_layers(
    5744           20 :         tline: &Timeline,
    5745           20 :         start_lsn: Lsn,
    5746           20 :         ctx: &RequestContext,
    5747           20 :     ) -> anyhow::Result<()> {
    5748           20 :         let mut lsn = start_lsn;
    5749              :         {
    5750           20 :             let mut writer = tline.writer().await;
    5751              :             // Create a relation on the timeline
    5752           20 :             writer
    5753           20 :                 .put(
    5754           20 :                     *TEST_KEY,
    5755           20 :                     lsn,
    5756           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5757           20 :                     ctx,
    5758           20 :                 )
    5759           10 :                 .await?;
    5760           20 :             writer.finish_write(lsn);
    5761           20 :             lsn += 0x10;
    5762           20 :             writer
    5763           20 :                 .put(
    5764           20 :                     *TEST_KEY,
    5765           20 :                     lsn,
    5766           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5767           20 :                     ctx,
    5768           20 :                 )
    5769            0 :                 .await?;
    5770           20 :             writer.finish_write(lsn);
    5771           20 :             lsn += 0x10;
    5772           20 :         }
    5773           20 :         tline.freeze_and_flush().await?;
    5774              :         {
    5775           20 :             let mut writer = tline.writer().await;
    5776           20 :             writer
    5777           20 :                 .put(
    5778           20 :                     *TEST_KEY,
    5779           20 :                     lsn,
    5780           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5781           20 :                     ctx,
    5782           20 :                 )
    5783           10 :                 .await?;
    5784           20 :             writer.finish_write(lsn);
    5785           20 :             lsn += 0x10;
    5786           20 :             writer
    5787           20 :                 .put(
    5788           20 :                     *TEST_KEY,
    5789           20 :                     lsn,
    5790           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5791           20 :                     ctx,
    5792           20 :                 )
    5793            0 :                 .await?;
    5794           20 :             writer.finish_write(lsn);
    5795           20 :         }
    5796           21 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5797           20 :     }
    5798              : 
    5799              :     #[tokio::test(start_paused = true)]
    5800            2 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5801            2 :         let (tenant, ctx) =
    5802            2 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5803            2 :                 .await?
    5804            2 :                 .load()
    5805           12 :                 .await;
    5806            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5807            2 :         // initial transition into AttachedSingle.
    5808            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5809            2 :         tokio::time::resume();
    5810            2 :         let tline = tenant
    5811            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5812            4 :             .await?;
    5813            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5814            2 : 
    5815            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5816            2 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5817            2 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5818            2 :         // below should fail.
    5819            2 :         tenant
    5820            2 :             .gc_iteration(
    5821            2 :                 Some(TIMELINE_ID),
    5822            2 :                 0x10,
    5823            2 :                 Duration::ZERO,
    5824            2 :                 &CancellationToken::new(),
    5825            2 :                 &ctx,
    5826            2 :             )
    5827            2 :             .await?;
    5828            2 : 
    5829            2 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5830            2 :         match tenant
    5831            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5832            2 :             .await
    5833            2 :         {
    5834            2 :             Ok(_) => panic!("branching should have failed"),
    5835            2 :             Err(err) => {
    5836            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5837            2 :                     panic!("wrong error type")
    5838            2 :                 };
    5839            2 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    5840            2 :                 assert!(err
    5841            2 :                     .source()
    5842            2 :                     .unwrap()
    5843            2 :                     .to_string()
    5844            2 :                     .contains("we might've already garbage collected needed data"))
    5845            2 :             }
    5846            2 :         }
    5847            2 : 
    5848            2 :         Ok(())
    5849            2 :     }
    5850              : 
    5851              :     #[tokio::test]
    5852            2 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    5853            2 :         let (tenant, ctx) =
    5854            2 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    5855            2 :                 .await?
    5856            2 :                 .load()
    5857           20 :                 .await;
    5858            2 : 
    5859            2 :         let tline = tenant
    5860            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    5861            6 :             .await?;
    5862            2 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    5863            2 :         match tenant
    5864            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5865            2 :             .await
    5866            2 :         {
    5867            2 :             Ok(_) => panic!("branching should have failed"),
    5868            2 :             Err(err) => {
    5869            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5870            2 :                     panic!("wrong error type");
    5871            2 :                 };
    5872            2 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    5873            2 :                 assert!(&err
    5874            2 :                     .source()
    5875            2 :                     .unwrap()
    5876            2 :                     .to_string()
    5877            2 :                     .contains("is earlier than latest GC cutoff"));
    5878            2 :             }
    5879            2 :         }
    5880            2 : 
    5881            2 :         Ok(())
    5882            2 :     }
    5883              : 
    5884              :     /*
    5885              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    5886              :     // remove the old value, we'd need to work a little harder
    5887              :     #[tokio::test]
    5888              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    5889              :         let repo =
    5890              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    5891              :             .load();
    5892              : 
    5893              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    5894              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5895              : 
    5896              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    5897              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    5898              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    5899              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    5900              :             Ok(_) => panic!("request for page should have failed"),
    5901              :             Err(err) => assert!(err.to_string().contains("not found at")),
    5902              :         }
    5903              :         Ok(())
    5904              :     }
    5905              :      */
    5906              : 
    5907              :     #[tokio::test]
    5908            2 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    5909            2 :         let (tenant, ctx) =
    5910            2 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    5911            2 :                 .await?
    5912            2 :                 .load()
    5913           20 :                 .await;
    5914            2 :         let tline = tenant
    5915            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5916            6 :             .await?;
    5917            7 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5918            2 : 
    5919            2 :         tenant
    5920            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5921            2 :             .await?;
    5922            2 :         let newtline = tenant
    5923            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5924            2 :             .expect("Should have a local timeline");
    5925            2 : 
    5926            6 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5927            2 : 
    5928            2 :         tline.set_broken("test".to_owned());
    5929            2 : 
    5930            2 :         tenant
    5931            2 :             .gc_iteration(
    5932            2 :                 Some(TIMELINE_ID),
    5933            2 :                 0x10,
    5934            2 :                 Duration::ZERO,
    5935            2 :                 &CancellationToken::new(),
    5936            2 :                 &ctx,
    5937            2 :             )
    5938            2 :             .await?;
    5939            2 : 
    5940            2 :         // The branchpoints should contain all timelines, even ones marked
    5941            2 :         // as Broken.
    5942            2 :         {
    5943            2 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    5944            2 :             assert_eq!(branchpoints.len(), 1);
    5945            2 :             assert_eq!(
    5946            2 :                 branchpoints[0],
    5947            2 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    5948            2 :             );
    5949            2 :         }
    5950            2 : 
    5951            2 :         // You can read the key from the child branch even though the parent is
    5952            2 :         // Broken, as long as you don't need to access data from the parent.
    5953            2 :         assert_eq!(
    5954            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    5955            2 :             test_img(&format!("foo at {}", Lsn(0x70)))
    5956            2 :         );
    5957            2 : 
    5958            2 :         // This needs to traverse to the parent, and fails.
    5959            2 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    5960            2 :         assert!(
    5961            2 :             err.to_string().starts_with(&format!(
    5962            2 :                 "bad state on timeline {}: Broken",
    5963            2 :                 tline.timeline_id
    5964            2 :             )),
    5965            2 :             "{err}"
    5966            2 :         );
    5967            2 : 
    5968            2 :         Ok(())
    5969            2 :     }
    5970              : 
    5971              :     #[tokio::test]
    5972            2 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    5973            2 :         let (tenant, ctx) =
    5974            2 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    5975            2 :                 .await?
    5976            2 :                 .load()
    5977           20 :                 .await;
    5978            2 :         let tline = tenant
    5979            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5980            6 :             .await?;
    5981            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5982            2 : 
    5983            2 :         tenant
    5984            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5985            2 :             .await?;
    5986            2 :         let newtline = tenant
    5987            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5988            2 :             .expect("Should have a local timeline");
    5989            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5990            2 :         tenant
    5991            2 :             .gc_iteration(
    5992            2 :                 Some(TIMELINE_ID),
    5993            2 :                 0x10,
    5994            2 :                 Duration::ZERO,
    5995            2 :                 &CancellationToken::new(),
    5996            2 :                 &ctx,
    5997            2 :             )
    5998            2 :             .await?;
    5999            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6000            2 : 
    6001            2 :         Ok(())
    6002            2 :     }
    6003              :     #[tokio::test]
    6004            2 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6005            2 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6006            2 :             .await?
    6007            2 :             .load()
    6008           20 :             .await;
    6009            2 :         let tline = tenant
    6010            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6011            6 :             .await?;
    6012            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6013            2 : 
    6014            2 :         tenant
    6015            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6016            2 :             .await?;
    6017            2 :         let newtline = tenant
    6018            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6019            2 :             .expect("Should have a local timeline");
    6020            2 : 
    6021            6 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6022            2 : 
    6023            2 :         // run gc on parent
    6024            2 :         tenant
    6025            2 :             .gc_iteration(
    6026            2 :                 Some(TIMELINE_ID),
    6027            2 :                 0x10,
    6028            2 :                 Duration::ZERO,
    6029            2 :                 &CancellationToken::new(),
    6030            2 :                 &ctx,
    6031            2 :             )
    6032            2 :             .await?;
    6033            2 : 
    6034            2 :         // Check that the data is still accessible on the branch.
    6035            2 :         assert_eq!(
    6036            7 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6037            2 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6038            2 :         );
    6039            2 : 
    6040            2 :         Ok(())
    6041            2 :     }
    6042              : 
    6043              :     #[tokio::test]
    6044            2 :     async fn timeline_load() -> anyhow::Result<()> {
    6045            2 :         const TEST_NAME: &str = "timeline_load";
    6046            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6047            2 :         {
    6048           20 :             let (tenant, ctx) = harness.load().await;
    6049            2 :             let tline = tenant
    6050            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6051            6 :                 .await?;
    6052            6 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6053            2 :             // so that all uploads finish & we can call harness.load() below again
    6054            2 :             tenant
    6055            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6056            2 :                 .instrument(harness.span())
    6057            2 :                 .await
    6058            2 :                 .ok()
    6059            2 :                 .unwrap();
    6060            2 :         }
    6061            2 : 
    6062           15 :         let (tenant, _ctx) = harness.load().await;
    6063            2 :         tenant
    6064            2 :             .get_timeline(TIMELINE_ID, true)
    6065            2 :             .expect("cannot load timeline");
    6066            2 : 
    6067            2 :         Ok(())
    6068            2 :     }
    6069              : 
    6070              :     #[tokio::test]
    6071            2 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6072            2 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6073            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6074            2 :         // create two timelines
    6075            2 :         {
    6076           20 :             let (tenant, ctx) = harness.load().await;
    6077            2 :             let tline = tenant
    6078            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6079            6 :                 .await?;
    6080            2 : 
    6081            6 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6082            2 : 
    6083            2 :             let child_tline = tenant
    6084            2 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6085            2 :                 .await?;
    6086            2 :             child_tline.set_state(TimelineState::Active);
    6087            2 : 
    6088            2 :             let newtline = tenant
    6089            2 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6090            2 :                 .expect("Should have a local timeline");
    6091            2 : 
    6092            6 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6093            2 : 
    6094            2 :             // so that all uploads finish & we can call harness.load() below again
    6095            2 :             tenant
    6096            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6097            2 :                 .instrument(harness.span())
    6098            2 :                 .await
    6099            2 :                 .ok()
    6100            2 :                 .unwrap();
    6101            2 :         }
    6102            2 : 
    6103            2 :         // check that both of them are initially unloaded
    6104           24 :         let (tenant, _ctx) = harness.load().await;
    6105            2 : 
    6106            2 :         // check that both, child and ancestor are loaded
    6107            2 :         let _child_tline = tenant
    6108            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6109            2 :             .expect("cannot get child timeline loaded");
    6110            2 : 
    6111            2 :         let _ancestor_tline = tenant
    6112            2 :             .get_timeline(TIMELINE_ID, true)
    6113            2 :             .expect("cannot get ancestor timeline loaded");
    6114            2 : 
    6115            2 :         Ok(())
    6116            2 :     }
    6117              : 
    6118              :     #[tokio::test]
    6119            2 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6120            2 :         use storage_layer::AsLayerDesc;
    6121            2 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6122            2 :             .await?
    6123            2 :             .load()
    6124           10 :             .await;
    6125            2 :         let tline = tenant
    6126            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6127            5 :             .await?;
    6128            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6129            2 : 
    6130            2 :         let layer_map = tline.layers.read().await;
    6131            2 :         let level0_deltas = layer_map
    6132            2 :             .layer_map()?
    6133            2 :             .level0_deltas()
    6134            2 :             .iter()
    6135            4 :             .map(|desc| layer_map.get_from_desc(desc))
    6136            2 :             .collect::<Vec<_>>();
    6137            2 : 
    6138            2 :         assert!(!level0_deltas.is_empty());
    6139            2 : 
    6140            6 :         for delta in level0_deltas {
    6141            2 :             // Ensure we are dumping a delta layer here
    6142            4 :             assert!(delta.layer_desc().is_delta);
    6143            8 :             delta.dump(true, &ctx).await.unwrap();
    6144            2 :         }
    6145            2 : 
    6146            2 :         Ok(())
    6147            2 :     }
    6148              : 
    6149              :     #[tokio::test]
    6150            2 :     async fn test_images() -> anyhow::Result<()> {
    6151            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6152            2 :         let tline = tenant
    6153            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6154            5 :             .await?;
    6155            2 : 
    6156            2 :         let mut writer = tline.writer().await;
    6157            2 :         writer
    6158            2 :             .put(
    6159            2 :                 *TEST_KEY,
    6160            2 :                 Lsn(0x10),
    6161            2 :                 &Value::Image(test_img("foo at 0x10")),
    6162            2 :                 &ctx,
    6163            2 :             )
    6164            2 :             .await?;
    6165            2 :         writer.finish_write(Lsn(0x10));
    6166            2 :         drop(writer);
    6167            2 : 
    6168            2 :         tline.freeze_and_flush().await?;
    6169            2 :         tline
    6170            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6171            2 :             .await?;
    6172            2 : 
    6173            2 :         let mut writer = tline.writer().await;
    6174            2 :         writer
    6175            2 :             .put(
    6176            2 :                 *TEST_KEY,
    6177            2 :                 Lsn(0x20),
    6178            2 :                 &Value::Image(test_img("foo at 0x20")),
    6179            2 :                 &ctx,
    6180            2 :             )
    6181            2 :             .await?;
    6182            2 :         writer.finish_write(Lsn(0x20));
    6183            2 :         drop(writer);
    6184            2 : 
    6185            2 :         tline.freeze_and_flush().await?;
    6186            2 :         tline
    6187            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6188            2 :             .await?;
    6189            2 : 
    6190            2 :         let mut writer = tline.writer().await;
    6191            2 :         writer
    6192            2 :             .put(
    6193            2 :                 *TEST_KEY,
    6194            2 :                 Lsn(0x30),
    6195            2 :                 &Value::Image(test_img("foo at 0x30")),
    6196            2 :                 &ctx,
    6197            2 :             )
    6198            2 :             .await?;
    6199            2 :         writer.finish_write(Lsn(0x30));
    6200            2 :         drop(writer);
    6201            2 : 
    6202            2 :         tline.freeze_and_flush().await?;
    6203            2 :         tline
    6204            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6205            2 :             .await?;
    6206            2 : 
    6207            2 :         let mut writer = tline.writer().await;
    6208            2 :         writer
    6209            2 :             .put(
    6210            2 :                 *TEST_KEY,
    6211            2 :                 Lsn(0x40),
    6212            2 :                 &Value::Image(test_img("foo at 0x40")),
    6213            2 :                 &ctx,
    6214            2 :             )
    6215            2 :             .await?;
    6216            2 :         writer.finish_write(Lsn(0x40));
    6217            2 :         drop(writer);
    6218            2 : 
    6219            2 :         tline.freeze_and_flush().await?;
    6220            2 :         tline
    6221            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6222            2 :             .await?;
    6223            2 : 
    6224            2 :         assert_eq!(
    6225            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6226            2 :             test_img("foo at 0x10")
    6227            2 :         );
    6228            2 :         assert_eq!(
    6229            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6230            2 :             test_img("foo at 0x10")
    6231            2 :         );
    6232            2 :         assert_eq!(
    6233            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6234            2 :             test_img("foo at 0x20")
    6235            2 :         );
    6236            2 :         assert_eq!(
    6237            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6238            2 :             test_img("foo at 0x30")
    6239            2 :         );
    6240            2 :         assert_eq!(
    6241            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6242            2 :             test_img("foo at 0x40")
    6243            2 :         );
    6244            2 : 
    6245            2 :         Ok(())
    6246            2 :     }
    6247              : 
    6248            4 :     async fn bulk_insert_compact_gc(
    6249            4 :         tenant: &Tenant,
    6250            4 :         timeline: &Arc<Timeline>,
    6251            4 :         ctx: &RequestContext,
    6252            4 :         lsn: Lsn,
    6253            4 :         repeat: usize,
    6254            4 :         key_count: usize,
    6255            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6256            4 :         let compact = true;
    6257        40718 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6258            4 :     }
    6259              : 
    6260            8 :     async fn bulk_insert_maybe_compact_gc(
    6261            8 :         tenant: &Tenant,
    6262            8 :         timeline: &Arc<Timeline>,
    6263            8 :         ctx: &RequestContext,
    6264            8 :         mut lsn: Lsn,
    6265            8 :         repeat: usize,
    6266            8 :         key_count: usize,
    6267            8 :         compact: bool,
    6268            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6269            8 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6270            8 : 
    6271            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6272            8 :         let mut blknum = 0;
    6273            8 : 
    6274            8 :         // Enforce that key range is monotonously increasing
    6275            8 :         let mut keyspace = KeySpaceAccum::new();
    6276            8 : 
    6277            8 :         let cancel = CancellationToken::new();
    6278            8 : 
    6279            8 :         for _ in 0..repeat {
    6280          400 :             for _ in 0..key_count {
    6281      4000000 :                 test_key.field6 = blknum;
    6282      4000000 :                 let mut writer = timeline.writer().await;
    6283      4000000 :                 writer
    6284      4000000 :                     .put(
    6285      4000000 :                         test_key,
    6286      4000000 :                         lsn,
    6287      4000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6288      4000000 :                         ctx,
    6289      4000000 :                     )
    6290         3426 :                     .await?;
    6291      4000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6292      4000000 :                 writer.finish_write(lsn);
    6293      4000000 :                 drop(writer);
    6294      4000000 : 
    6295      4000000 :                 keyspace.add_key(test_key);
    6296      4000000 : 
    6297      4000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6298      4000000 :                 blknum += 1;
    6299              :             }
    6300              : 
    6301          400 :             timeline.freeze_and_flush().await?;
    6302          400 :             if compact {
    6303              :                 // this requires timeline to be &Arc<Timeline>
    6304         8618 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6305          200 :             }
    6306              : 
    6307              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6308              :             // originally was.
    6309          400 :             let res = tenant
    6310          400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6311            0 :                 .await?;
    6312              : 
    6313          400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6314              :         }
    6315              : 
    6316            8 :         Ok(inserted)
    6317            8 :     }
    6318              : 
    6319              :     //
    6320              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6321              :     // Repeat 50 times.
    6322              :     //
    6323              :     #[tokio::test]
    6324            2 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6325            2 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6326           20 :         let (tenant, ctx) = harness.load().await;
    6327            2 :         let tline = tenant
    6328            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6329            6 :             .await?;
    6330            2 : 
    6331            2 :         let lsn = Lsn(0x10);
    6332        20359 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6333            2 : 
    6334            2 :         Ok(())
    6335            2 :     }
    6336              : 
    6337              :     // Test the vectored get real implementation against a simple sequential implementation.
    6338              :     //
    6339              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6340              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6341              :     // grow to the right on the X axis.
    6342              :     //                       [Delta]
    6343              :     //                 [Delta]
    6344              :     //           [Delta]
    6345              :     //    [Delta]
    6346              :     // ------------ Image ---------------
    6347              :     //
    6348              :     // After layer generation we pick the ranges to query as follows:
    6349              :     // 1. The beginning of each delta layer
    6350              :     // 2. At the seam between two adjacent delta layers
    6351              :     //
    6352              :     // There's one major downside to this test: delta layers only contains images,
    6353              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6354              :     #[tokio::test]
    6355            2 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6356            2 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6357           20 :         let (tenant, ctx) = harness.load().await;
    6358            2 :         let tline = tenant
    6359            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6360            6 :             .await?;
    6361            2 : 
    6362            2 :         let lsn = Lsn(0x10);
    6363        20359 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6364            2 : 
    6365            2 :         let guard = tline.layers.read().await;
    6366            2 :         let lm = guard.layer_map()?;
    6367            2 : 
    6368            2 :         lm.dump(true, &ctx).await?;
    6369            2 : 
    6370            2 :         let mut reads = Vec::new();
    6371            2 :         let mut prev = None;
    6372           12 :         lm.iter_historic_layers().for_each(|desc| {
    6373           12 :             if !desc.is_delta() {
    6374            2 :                 prev = Some(desc.clone());
    6375            2 :                 return;
    6376           10 :             }
    6377           10 : 
    6378           10 :             let start = desc.key_range.start;
    6379           10 :             let end = desc
    6380           10 :                 .key_range
    6381           10 :                 .start
    6382           10 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6383           10 :             reads.push(KeySpace {
    6384           10 :                 ranges: vec![start..end],
    6385           10 :             });
    6386            2 : 
    6387           10 :             if let Some(prev) = &prev {
    6388           10 :                 if !prev.is_delta() {
    6389           10 :                     return;
    6390            2 :                 }
    6391            0 : 
    6392            0 :                 let first_range = Key {
    6393            0 :                     field6: prev.key_range.end.field6 - 4,
    6394            0 :                     ..prev.key_range.end
    6395            0 :                 }..prev.key_range.end;
    6396            0 : 
    6397            0 :                 let second_range = desc.key_range.start..Key {
    6398            0 :                     field6: desc.key_range.start.field6 + 4,
    6399            0 :                     ..desc.key_range.start
    6400            0 :                 };
    6401            0 : 
    6402            0 :                 reads.push(KeySpace {
    6403            0 :                     ranges: vec![first_range, second_range],
    6404            0 :                 });
    6405            2 :             };
    6406            2 : 
    6407            2 :             prev = Some(desc.clone());
    6408           12 :         });
    6409            2 : 
    6410            2 :         drop(guard);
    6411            2 : 
    6412            2 :         // Pick a big LSN such that we query over all the changes.
    6413            2 :         let reads_lsn = Lsn(u64::MAX - 1);
    6414            2 : 
    6415           12 :         for read in reads {
    6416           10 :             info!("Doing vectored read on {:?}", read);
    6417            2 : 
    6418           10 :             let vectored_res = tline
    6419           10 :                 .get_vectored_impl(
    6420           10 :                     read.clone(),
    6421           10 :                     reads_lsn,
    6422           10 :                     &mut ValuesReconstructState::new(),
    6423           10 :                     &ctx,
    6424           10 :                 )
    6425           25 :                 .await;
    6426            2 : 
    6427           10 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6428           10 :             let mut expect_missing = false;
    6429           10 :             let mut key = read.start().unwrap();
    6430          330 :             while key != read.end().unwrap() {
    6431          320 :                 if let Some(lsns) = inserted.get(&key) {
    6432          320 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6433          320 :                     match expected_lsn {
    6434          320 :                         Some(lsn) => {
    6435          320 :                             expected_lsns.insert(key, *lsn);
    6436          320 :                         }
    6437            2 :                         None => {
    6438            2 :                             expect_missing = true;
    6439            0 :                             break;
    6440            2 :                         }
    6441            2 :                     }
    6442            2 :                 } else {
    6443            2 :                     expect_missing = true;
    6444            0 :                     break;
    6445            2 :                 }
    6446            2 : 
    6447          320 :                 key = key.next();
    6448            2 :             }
    6449            2 : 
    6450           10 :             if expect_missing {
    6451            2 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6452            2 :             } else {
    6453          320 :                 for (key, image) in vectored_res? {
    6454          320 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6455          320 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6456          320 :                     assert_eq!(image?, expected_image);
    6457            2 :                 }
    6458            2 :             }
    6459            2 :         }
    6460            2 : 
    6461            2 :         Ok(())
    6462            2 :     }
    6463              : 
    6464              :     #[tokio::test]
    6465            2 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6466            2 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6467            2 : 
    6468           20 :         let (tenant, ctx) = harness.load().await;
    6469            2 :         let tline = tenant
    6470            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6471            2 :             .await?;
    6472            2 :         let tline = tline.raw_timeline().unwrap();
    6473            2 : 
    6474            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6475            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6476            2 :         modification.set_lsn(Lsn(0x1008))?;
    6477            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6478            2 :         modification.commit(&ctx).await?;
    6479            2 : 
    6480            2 :         let child_timeline_id = TimelineId::generate();
    6481            2 :         tenant
    6482            2 :             .branch_timeline_test(
    6483            2 :                 tline,
    6484            2 :                 child_timeline_id,
    6485            2 :                 Some(tline.get_last_record_lsn()),
    6486            2 :                 &ctx,
    6487            2 :             )
    6488            2 :             .await?;
    6489            2 : 
    6490            2 :         let child_timeline = tenant
    6491            2 :             .get_timeline(child_timeline_id, true)
    6492            2 :             .expect("Should have the branched timeline");
    6493            2 : 
    6494            2 :         let aux_keyspace = KeySpace {
    6495            2 :             ranges: vec![NON_INHERITED_RANGE],
    6496            2 :         };
    6497            2 :         let read_lsn = child_timeline.get_last_record_lsn();
    6498            2 : 
    6499            2 :         let vectored_res = child_timeline
    6500            2 :             .get_vectored_impl(
    6501            2 :                 aux_keyspace.clone(),
    6502            2 :                 read_lsn,
    6503            2 :                 &mut ValuesReconstructState::new(),
    6504            2 :                 &ctx,
    6505            2 :             )
    6506            2 :             .await;
    6507            2 : 
    6508            2 :         let images = vectored_res?;
    6509            2 :         assert!(images.is_empty());
    6510            2 :         Ok(())
    6511            2 :     }
    6512              : 
    6513              :     // Test that vectored get handles layer gaps correctly
    6514              :     // by advancing into the next ancestor timeline if required.
    6515              :     //
    6516              :     // The test generates timelines that look like the diagram below.
    6517              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6518              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6519              :     //
    6520              :     // ```
    6521              :     //-------------------------------+
    6522              :     //                          ...  |
    6523              :     //               [   L1   ]      |
    6524              :     //     [ / L1   ]                | Child Timeline
    6525              :     // ...                           |
    6526              :     // ------------------------------+
    6527              :     //     [ X L1   ]                | Parent Timeline
    6528              :     // ------------------------------+
    6529              :     // ```
    6530              :     #[tokio::test]
    6531            2 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6532            2 :         let tenant_conf = TenantConf {
    6533            2 :             // Make compaction deterministic
    6534            2 :             gc_period: Duration::ZERO,
    6535            2 :             compaction_period: Duration::ZERO,
    6536            2 :             // Encourage creation of L1 layers
    6537            2 :             checkpoint_distance: 16 * 1024,
    6538            2 :             compaction_target_size: 8 * 1024,
    6539            2 :             ..TenantConf::default()
    6540            2 :         };
    6541            2 : 
    6542            2 :         let harness = TenantHarness::create_custom(
    6543            2 :             "test_get_vectored_key_gap",
    6544            2 :             tenant_conf,
    6545            2 :             TenantId::generate(),
    6546            2 :             ShardIdentity::unsharded(),
    6547            2 :             Generation::new(0xdeadbeef),
    6548            2 :         )
    6549            2 :         .await?;
    6550           20 :         let (tenant, ctx) = harness.load().await;
    6551            2 : 
    6552            2 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6553            2 :         let gap_at_key = current_key.add(100);
    6554            2 :         let mut current_lsn = Lsn(0x10);
    6555            2 : 
    6556            2 :         const KEY_COUNT: usize = 10_000;
    6557            2 : 
    6558            2 :         let timeline_id = TimelineId::generate();
    6559            2 :         let current_timeline = tenant
    6560            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6561            6 :             .await?;
    6562            2 : 
    6563            2 :         current_lsn += 0x100;
    6564            2 : 
    6565            2 :         let mut writer = current_timeline.writer().await;
    6566            2 :         writer
    6567            2 :             .put(
    6568            2 :                 gap_at_key,
    6569            2 :                 current_lsn,
    6570            2 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6571            2 :                 &ctx,
    6572            2 :             )
    6573            2 :             .await?;
    6574            2 :         writer.finish_write(current_lsn);
    6575            2 :         drop(writer);
    6576            2 : 
    6577            2 :         let mut latest_lsns = HashMap::new();
    6578            2 :         latest_lsns.insert(gap_at_key, current_lsn);
    6579            2 : 
    6580            2 :         current_timeline.freeze_and_flush().await?;
    6581            2 : 
    6582            2 :         let child_timeline_id = TimelineId::generate();
    6583            2 : 
    6584            2 :         tenant
    6585            2 :             .branch_timeline_test(
    6586            2 :                 &current_timeline,
    6587            2 :                 child_timeline_id,
    6588            2 :                 Some(current_lsn),
    6589            2 :                 &ctx,
    6590            2 :             )
    6591            2 :             .await?;
    6592            2 :         let child_timeline = tenant
    6593            2 :             .get_timeline(child_timeline_id, true)
    6594            2 :             .expect("Should have the branched timeline");
    6595            2 : 
    6596        20002 :         for i in 0..KEY_COUNT {
    6597        20000 :             if current_key == gap_at_key {
    6598            2 :                 current_key = current_key.next();
    6599            2 :                 continue;
    6600        19998 :             }
    6601        19998 : 
    6602        19998 :             current_lsn += 0x10;
    6603            2 : 
    6604        19998 :             let mut writer = child_timeline.writer().await;
    6605        19998 :             writer
    6606        19998 :                 .put(
    6607        19998 :                     current_key,
    6608        19998 :                     current_lsn,
    6609        19998 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6610        19998 :                     &ctx,
    6611        19998 :                 )
    6612           70 :                 .await?;
    6613        19998 :             writer.finish_write(current_lsn);
    6614        19998 :             drop(writer);
    6615        19998 : 
    6616        19998 :             latest_lsns.insert(current_key, current_lsn);
    6617        19998 :             current_key = current_key.next();
    6618        19998 : 
    6619        19998 :             // Flush every now and then to encourage layer file creation.
    6620        19998 :             if i % 500 == 0 {
    6621           44 :                 child_timeline.freeze_and_flush().await?;
    6622        19958 :             }
    6623            2 :         }
    6624            2 : 
    6625            2 :         child_timeline.freeze_and_flush().await?;
    6626            2 :         let mut flags = EnumSet::new();
    6627            2 :         flags.insert(CompactFlags::ForceRepartition);
    6628            2 :         child_timeline
    6629            2 :             .compact(&CancellationToken::new(), flags, &ctx)
    6630         1757 :             .await?;
    6631            2 : 
    6632            2 :         let key_near_end = {
    6633            2 :             let mut tmp = current_key;
    6634            2 :             tmp.field6 -= 10;
    6635            2 :             tmp
    6636            2 :         };
    6637            2 : 
    6638            2 :         let key_near_gap = {
    6639            2 :             let mut tmp = gap_at_key;
    6640            2 :             tmp.field6 -= 10;
    6641            2 :             tmp
    6642            2 :         };
    6643            2 : 
    6644            2 :         let read = KeySpace {
    6645            2 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6646            2 :         };
    6647            2 :         let results = child_timeline
    6648            2 :             .get_vectored_impl(
    6649            2 :                 read.clone(),
    6650            2 :                 current_lsn,
    6651            2 :                 &mut ValuesReconstructState::new(),
    6652            2 :                 &ctx,
    6653            2 :             )
    6654           16 :             .await?;
    6655            2 : 
    6656           44 :         for (key, img_res) in results {
    6657           42 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6658           42 :             assert_eq!(img_res?, expected);
    6659            2 :         }
    6660            2 : 
    6661            2 :         Ok(())
    6662            2 :     }
    6663              : 
    6664              :     // Test that vectored get descends into ancestor timelines correctly and
    6665              :     // does not return an image that's newer than requested.
    6666              :     //
    6667              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6668              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6669              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6670              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6671              :     // order to avoid returning an image that's too new. The test below constructs such
    6672              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6673              :     // ```
    6674              :     //    LSN
    6675              :     //     ^
    6676              :     //     |
    6677              :     //     |
    6678              :     // 500 | --------------------------------------> branch point
    6679              :     // 400 |        X
    6680              :     // 300 |        X
    6681              :     // 200 | --------------------------------------> requested lsn
    6682              :     // 100 |        X
    6683              :     //     |---------------------------------------> Key
    6684              :     //              |
    6685              :     //              ------> requested key
    6686              :     //
    6687              :     // Legend:
    6688              :     // * X - page images
    6689              :     // ```
    6690              :     #[tokio::test]
    6691            2 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6692            2 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6693           20 :         let (tenant, ctx) = harness.load().await;
    6694            2 : 
    6695            2 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6696            2 :         let end_key = start_key.add(1000);
    6697            2 :         let child_gap_at_key = start_key.add(500);
    6698            2 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6699            2 : 
    6700            2 :         let mut current_lsn = Lsn(0x10);
    6701            2 : 
    6702            2 :         let timeline_id = TimelineId::generate();
    6703            2 :         let parent_timeline = tenant
    6704            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6705            6 :             .await?;
    6706            2 : 
    6707            2 :         current_lsn += 0x100;
    6708            2 : 
    6709            8 :         for _ in 0..3 {
    6710            6 :             let mut key = start_key;
    6711         6006 :             while key < end_key {
    6712         6000 :                 current_lsn += 0x10;
    6713         6000 : 
    6714         6000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6715            2 : 
    6716         6000 :                 let mut writer = parent_timeline.writer().await;
    6717         6000 :                 writer
    6718         6000 :                     .put(
    6719         6000 :                         key,
    6720         6000 :                         current_lsn,
    6721         6000 :                         &Value::Image(test_img(&image_value)),
    6722         6000 :                         &ctx,
    6723         6000 :                     )
    6724            6 :                     .await?;
    6725         6000 :                 writer.finish_write(current_lsn);
    6726         6000 : 
    6727         6000 :                 if key == child_gap_at_key {
    6728            6 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6729         5994 :                 }
    6730            2 : 
    6731         6000 :                 key = key.next();
    6732            2 :             }
    6733            2 : 
    6734            6 :             parent_timeline.freeze_and_flush().await?;
    6735            2 :         }
    6736            2 : 
    6737            2 :         let child_timeline_id = TimelineId::generate();
    6738            2 : 
    6739            2 :         let child_timeline = tenant
    6740            2 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6741            2 :             .await?;
    6742            2 : 
    6743            2 :         let mut key = start_key;
    6744         2002 :         while key < end_key {
    6745         2000 :             if key == child_gap_at_key {
    6746            2 :                 key = key.next();
    6747            2 :                 continue;
    6748         1998 :             }
    6749         1998 : 
    6750         1998 :             current_lsn += 0x10;
    6751            2 : 
    6752         1998 :             let mut writer = child_timeline.writer().await;
    6753         1998 :             writer
    6754         1998 :                 .put(
    6755         1998 :                     key,
    6756         1998 :                     current_lsn,
    6757         1998 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6758         1998 :                     &ctx,
    6759         1998 :                 )
    6760           17 :                 .await?;
    6761         1998 :             writer.finish_write(current_lsn);
    6762         1998 : 
    6763         1998 :             key = key.next();
    6764            2 :         }
    6765            2 : 
    6766            2 :         child_timeline.freeze_and_flush().await?;
    6767            2 : 
    6768            2 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6769            2 :         let mut query_lsns = Vec::new();
    6770            6 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6771           36 :             for offset in lsn_offsets {
    6772           30 :                 query_lsns.push(Lsn(image_lsn
    6773           30 :                     .0
    6774           30 :                     .checked_add_signed(offset)
    6775           30 :                     .expect("Shouldn't overflow")));
    6776           30 :             }
    6777            2 :         }
    6778            2 : 
    6779           32 :         for query_lsn in query_lsns {
    6780           30 :             let results = child_timeline
    6781           30 :                 .get_vectored_impl(
    6782           30 :                     KeySpace {
    6783           30 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6784           30 :                     },
    6785           30 :                     query_lsn,
    6786           30 :                     &mut ValuesReconstructState::new(),
    6787           30 :                     &ctx,
    6788           30 :                 )
    6789           29 :                 .await;
    6790            2 : 
    6791           30 :             let expected_item = parent_gap_lsns
    6792           30 :                 .iter()
    6793           30 :                 .rev()
    6794           68 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6795           30 : 
    6796           30 :             info!(
    6797            2 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6798            2 :                 query_lsn, expected_item
    6799            2 :             );
    6800            2 : 
    6801           30 :             match expected_item {
    6802           26 :                 Some((_, img_value)) => {
    6803           26 :                     let key_results = results.expect("No vectored get error expected");
    6804           26 :                     let key_result = &key_results[&child_gap_at_key];
    6805           26 :                     let returned_img = key_result
    6806           26 :                         .as_ref()
    6807           26 :                         .expect("No page reconstruct error expected");
    6808           26 : 
    6809           26 :                     info!(
    6810            2 :                         "Vectored read at LSN {} returned image {}",
    6811            0 :                         query_lsn,
    6812            0 :                         std::str::from_utf8(returned_img)?
    6813            2 :                     );
    6814           26 :                     assert_eq!(*returned_img, test_img(img_value));
    6815            2 :                 }
    6816            2 :                 None => {
    6817            4 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6818            2 :                 }
    6819            2 :             }
    6820            2 :         }
    6821            2 : 
    6822            2 :         Ok(())
    6823            2 :     }
    6824              : 
    6825              :     #[tokio::test]
    6826            2 :     async fn test_random_updates() -> anyhow::Result<()> {
    6827            2 :         let names_algorithms = [
    6828            2 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    6829            2 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    6830            2 :         ];
    6831            6 :         for (name, algorithm) in names_algorithms {
    6832        96212 :             test_random_updates_algorithm(name, algorithm).await?;
    6833            2 :         }
    6834            2 :         Ok(())
    6835            2 :     }
    6836              : 
    6837            4 :     async fn test_random_updates_algorithm(
    6838            4 :         name: &'static str,
    6839            4 :         compaction_algorithm: CompactionAlgorithm,
    6840            4 :     ) -> anyhow::Result<()> {
    6841            4 :         let mut harness = TenantHarness::create(name).await?;
    6842            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6843            4 :             kind: compaction_algorithm,
    6844            4 :         };
    6845           40 :         let (tenant, ctx) = harness.load().await;
    6846            4 :         let tline = tenant
    6847            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6848           11 :             .await?;
    6849              : 
    6850              :         const NUM_KEYS: usize = 1000;
    6851            4 :         let cancel = CancellationToken::new();
    6852            4 : 
    6853            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6854            4 :         let mut test_key_end = test_key;
    6855            4 :         test_key_end.field6 = NUM_KEYS as u32;
    6856            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    6857            4 : 
    6858            4 :         let mut keyspace = KeySpaceAccum::new();
    6859            4 : 
    6860            4 :         // Track when each page was last modified. Used to assert that
    6861            4 :         // a read sees the latest page version.
    6862            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    6863            4 : 
    6864            4 :         let mut lsn = Lsn(0x10);
    6865              :         #[allow(clippy::needless_range_loop)]
    6866         4004 :         for blknum in 0..NUM_KEYS {
    6867         4000 :             lsn = Lsn(lsn.0 + 0x10);
    6868         4000 :             test_key.field6 = blknum as u32;
    6869         4000 :             let mut writer = tline.writer().await;
    6870         4000 :             writer
    6871         4000 :                 .put(
    6872         4000 :                     test_key,
    6873         4000 :                     lsn,
    6874         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6875         4000 :                     &ctx,
    6876         4000 :                 )
    6877            4 :                 .await?;
    6878         4000 :             writer.finish_write(lsn);
    6879         4000 :             updated[blknum] = lsn;
    6880         4000 :             drop(writer);
    6881         4000 : 
    6882         4000 :             keyspace.add_key(test_key);
    6883              :         }
    6884              : 
    6885          204 :         for _ in 0..50 {
    6886       200200 :             for _ in 0..NUM_KEYS {
    6887       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    6888       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6889       200000 :                 test_key.field6 = blknum as u32;
    6890       200000 :                 let mut writer = tline.writer().await;
    6891       200000 :                 writer
    6892       200000 :                     .put(
    6893       200000 :                         test_key,
    6894       200000 :                         lsn,
    6895       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6896       200000 :                         &ctx,
    6897       200000 :                     )
    6898          198 :                     .await?;
    6899       200000 :                 writer.finish_write(lsn);
    6900       200000 :                 drop(writer);
    6901       200000 :                 updated[blknum] = lsn;
    6902              :             }
    6903              : 
    6904              :             // Read all the blocks
    6905       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6906       200000 :                 test_key.field6 = blknum as u32;
    6907       200000 :                 assert_eq!(
    6908       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    6909       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6910              :                 );
    6911              :             }
    6912              : 
    6913              :             // Perform a cycle of flush, and GC
    6914          203 :             tline.freeze_and_flush().await?;
    6915          200 :             tenant
    6916          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    6917            0 :                 .await?;
    6918              :         }
    6919              : 
    6920            4 :         Ok(())
    6921            4 :     }
    6922              : 
    6923              :     #[tokio::test]
    6924            2 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    6925            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    6926            2 :             .await?
    6927            2 :             .load()
    6928           15 :             .await;
    6929            2 :         let mut tline = tenant
    6930            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6931            5 :             .await?;
    6932            2 : 
    6933            2 :         const NUM_KEYS: usize = 1000;
    6934            2 : 
    6935            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6936            2 : 
    6937            2 :         let mut keyspace = KeySpaceAccum::new();
    6938            2 : 
    6939            2 :         let cancel = CancellationToken::new();
    6940            2 : 
    6941            2 :         // Track when each page was last modified. Used to assert that
    6942            2 :         // a read sees the latest page version.
    6943            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    6944            2 : 
    6945            2 :         let mut lsn = Lsn(0x10);
    6946            2 :         #[allow(clippy::needless_range_loop)]
    6947         2002 :         for blknum in 0..NUM_KEYS {
    6948         2000 :             lsn = Lsn(lsn.0 + 0x10);
    6949         2000 :             test_key.field6 = blknum as u32;
    6950         2000 :             let mut writer = tline.writer().await;
    6951         2000 :             writer
    6952         2000 :                 .put(
    6953         2000 :                     test_key,
    6954         2000 :                     lsn,
    6955         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6956         2000 :                     &ctx,
    6957         2000 :                 )
    6958            2 :                 .await?;
    6959         2000 :             writer.finish_write(lsn);
    6960         2000 :             updated[blknum] = lsn;
    6961         2000 :             drop(writer);
    6962         2000 : 
    6963         2000 :             keyspace.add_key(test_key);
    6964            2 :         }
    6965            2 : 
    6966          102 :         for _ in 0..50 {
    6967          100 :             let new_tline_id = TimelineId::generate();
    6968          100 :             tenant
    6969          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    6970           92 :                 .await?;
    6971          100 :             tline = tenant
    6972          100 :                 .get_timeline(new_tline_id, true)
    6973          100 :                 .expect("Should have the branched timeline");
    6974            2 : 
    6975       100100 :             for _ in 0..NUM_KEYS {
    6976       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    6977       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6978       100000 :                 test_key.field6 = blknum as u32;
    6979       100000 :                 let mut writer = tline.writer().await;
    6980       100000 :                 writer
    6981       100000 :                     .put(
    6982       100000 :                         test_key,
    6983       100000 :                         lsn,
    6984       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6985       100000 :                         &ctx,
    6986       100000 :                     )
    6987          835 :                     .await?;
    6988       100000 :                 println!("updating {} at {}", blknum, lsn);
    6989       100000 :                 writer.finish_write(lsn);
    6990       100000 :                 drop(writer);
    6991       100000 :                 updated[blknum] = lsn;
    6992            2 :             }
    6993            2 : 
    6994            2 :             // Read all the blocks
    6995       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6996       100000 :                 test_key.field6 = blknum as u32;
    6997       100000 :                 assert_eq!(
    6998       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    6999       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7000            2 :                 );
    7001            2 :             }
    7002            2 : 
    7003            2 :             // Perform a cycle of flush, compact, and GC
    7004          102 :             tline.freeze_and_flush().await?;
    7005        15029 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7006          100 :             tenant
    7007          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7008            2 :                 .await?;
    7009            2 :         }
    7010            2 : 
    7011            2 :         Ok(())
    7012            2 :     }
    7013              : 
    7014              :     #[tokio::test]
    7015            2 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7016            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7017            2 :             .await?
    7018            2 :             .load()
    7019           20 :             .await;
    7020            2 :         let mut tline = tenant
    7021            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7022            6 :             .await?;
    7023            2 : 
    7024            2 :         const NUM_KEYS: usize = 100;
    7025            2 :         const NUM_TLINES: usize = 50;
    7026            2 : 
    7027            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7028            2 :         // Track page mutation lsns across different timelines.
    7029            2 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7030            2 : 
    7031            2 :         let mut lsn = Lsn(0x10);
    7032            2 : 
    7033            2 :         #[allow(clippy::needless_range_loop)]
    7034          102 :         for idx in 0..NUM_TLINES {
    7035          100 :             let new_tline_id = TimelineId::generate();
    7036          100 :             tenant
    7037          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7038           70 :                 .await?;
    7039          100 :             tline = tenant
    7040          100 :                 .get_timeline(new_tline_id, true)
    7041          100 :                 .expect("Should have the branched timeline");
    7042            2 : 
    7043        10100 :             for _ in 0..NUM_KEYS {
    7044        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    7045        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7046        10000 :                 test_key.field6 = blknum as u32;
    7047        10000 :                 let mut writer = tline.writer().await;
    7048        10000 :                 writer
    7049        10000 :                     .put(
    7050        10000 :                         test_key,
    7051        10000 :                         lsn,
    7052        10000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7053        10000 :                         &ctx,
    7054        10000 :                     )
    7055          107 :                     .await?;
    7056        10000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7057        10000 :                 writer.finish_write(lsn);
    7058        10000 :                 drop(writer);
    7059        10000 :                 updated[idx][blknum] = lsn;
    7060            2 :             }
    7061            2 :         }
    7062            2 : 
    7063            2 :         // Read pages from leaf timeline across all ancestors.
    7064          100 :         for (idx, lsns) in updated.iter().enumerate() {
    7065        10000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7066            2 :                 // Skip empty mutations.
    7067        10000 :                 if lsn.0 == 0 {
    7068         3673 :                     continue;
    7069         6327 :                 }
    7070         6327 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7071         6327 :                 test_key.field6 = blknum as u32;
    7072         6327 :                 assert_eq!(
    7073         6327 :                     tline.get(test_key, *lsn, &ctx).await?,
    7074         6327 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7075            2 :                 );
    7076            2 :             }
    7077            2 :         }
    7078            2 :         Ok(())
    7079            2 :     }
    7080              : 
    7081              :     #[tokio::test]
    7082            2 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7083            2 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7084            2 :             .await?
    7085            2 :             .load()
    7086           20 :             .await;
    7087            2 : 
    7088            2 :         let initdb_lsn = Lsn(0x20);
    7089            2 :         let utline = tenant
    7090            2 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7091            2 :             .await?;
    7092            2 :         let tline = utline.raw_timeline().unwrap();
    7093            2 : 
    7094            2 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7095            2 :         tline.maybe_spawn_flush_loop();
    7096            2 : 
    7097            2 :         // Make sure the timeline has the minimum set of required keys for operation.
    7098            2 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7099            2 :         // Except if you `put` at `initdb_lsn`.
    7100            2 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7101            2 :         // It uses `repartition()`, which assumes some keys to be present.
    7102            2 :         // Let's make sure the test timeline can handle that case.
    7103            2 :         {
    7104            2 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7105            2 :             assert_eq!(
    7106            2 :                 timeline::FlushLoopState::Running {
    7107            2 :                     expect_initdb_optimization: false,
    7108            2 :                     initdb_optimization_count: 0,
    7109            2 :                 },
    7110            2 :                 *state
    7111            2 :             );
    7112            2 :             *state = timeline::FlushLoopState::Running {
    7113            2 :                 expect_initdb_optimization: true,
    7114            2 :                 initdb_optimization_count: 0,
    7115            2 :             };
    7116            2 :         }
    7117            2 : 
    7118            2 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7119            2 :         // As explained above, the optimization requires some keys to be present.
    7120            2 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7121            2 :         // This is what `create_test_timeline` does, by the way.
    7122            2 :         let mut modification = tline.begin_modification(initdb_lsn);
    7123            2 :         modification
    7124            2 :             .init_empty_test_timeline()
    7125            2 :             .context("init_empty_test_timeline")?;
    7126            2 :         modification
    7127            2 :             .commit(&ctx)
    7128            2 :             .await
    7129            2 :             .context("commit init_empty_test_timeline modification")?;
    7130            2 : 
    7131            2 :         // Do the flush. The flush code will check the expectations that we set above.
    7132            2 :         tline.freeze_and_flush().await?;
    7133            2 : 
    7134            2 :         // assert freeze_and_flush exercised the initdb optimization
    7135            2 :         {
    7136            2 :             let state = tline.flush_loop_state.lock().unwrap();
    7137            2 :             let timeline::FlushLoopState::Running {
    7138            2 :                 expect_initdb_optimization,
    7139            2 :                 initdb_optimization_count,
    7140            2 :             } = *state
    7141            2 :             else {
    7142            2 :                 panic!("unexpected state: {:?}", *state);
    7143            2 :             };
    7144            2 :             assert!(expect_initdb_optimization);
    7145            2 :             assert!(initdb_optimization_count > 0);
    7146            2 :         }
    7147            2 :         Ok(())
    7148            2 :     }
    7149              : 
    7150              :     #[tokio::test]
    7151            2 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7152            2 :         let name = "test_create_guard_crash";
    7153            2 :         let harness = TenantHarness::create(name).await?;
    7154            2 :         {
    7155           20 :             let (tenant, ctx) = harness.load().await;
    7156            2 :             let tline = tenant
    7157            2 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7158            2 :                 .await?;
    7159            2 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7160            2 :             let raw_tline = tline.raw_timeline().unwrap();
    7161            2 :             raw_tline
    7162            2 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7163            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))
    7164            2 :                 .await;
    7165            2 :             std::mem::forget(tline);
    7166            2 :         }
    7167            2 : 
    7168           20 :         let (tenant, _) = harness.load().await;
    7169            2 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7170            2 :             Ok(_) => panic!("timeline should've been removed during load"),
    7171            2 :             Err(e) => {
    7172            2 :                 assert_eq!(
    7173            2 :                     e,
    7174            2 :                     GetTimelineError::NotFound {
    7175            2 :                         tenant_id: tenant.tenant_shard_id,
    7176            2 :                         timeline_id: TIMELINE_ID,
    7177            2 :                     }
    7178            2 :                 )
    7179            2 :             }
    7180            2 :         }
    7181            2 : 
    7182            2 :         assert!(!harness
    7183            2 :             .conf
    7184            2 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7185            2 :             .exists());
    7186            2 : 
    7187            2 :         Ok(())
    7188            2 :     }
    7189              : 
    7190              :     #[tokio::test]
    7191            2 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7192            2 :         let names_algorithms = [
    7193            2 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7194            2 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7195            2 :         ];
    7196            6 :         for (name, algorithm) in names_algorithms {
    7197        32561 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7198            2 :         }
    7199            2 :         Ok(())
    7200            2 :     }
    7201              : 
    7202            4 :     async fn test_read_at_max_lsn_algorithm(
    7203            4 :         name: &'static str,
    7204            4 :         compaction_algorithm: CompactionAlgorithm,
    7205            4 :     ) -> anyhow::Result<()> {
    7206            4 :         let mut harness = TenantHarness::create(name).await?;
    7207            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7208            4 :             kind: compaction_algorithm,
    7209            4 :         };
    7210           40 :         let (tenant, ctx) = harness.load().await;
    7211            4 :         let tline = tenant
    7212            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7213           11 :             .await?;
    7214              : 
    7215            4 :         let lsn = Lsn(0x10);
    7216            4 :         let compact = false;
    7217        32100 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7218              : 
    7219            4 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7220            4 :         let read_lsn = Lsn(u64::MAX - 1);
    7221              : 
    7222          410 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7223            4 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7224              : 
    7225            4 :         Ok(())
    7226            4 :     }
    7227              : 
    7228              :     #[tokio::test]
    7229            2 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7230            2 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7231           20 :         let (tenant, ctx) = harness.load().await;
    7232            2 :         let tline = tenant
    7233            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7234            6 :             .await?;
    7235            2 : 
    7236            2 :         const NUM_KEYS: usize = 1000;
    7237            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7238            2 : 
    7239            2 :         let cancel = CancellationToken::new();
    7240            2 : 
    7241            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7242            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7243            2 :         let mut test_key = base_key;
    7244            2 : 
    7245            2 :         // Track when each page was last modified. Used to assert that
    7246            2 :         // a read sees the latest page version.
    7247            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7248            2 : 
    7249            2 :         let mut lsn = Lsn(0x10);
    7250            2 :         #[allow(clippy::needless_range_loop)]
    7251         2002 :         for blknum in 0..NUM_KEYS {
    7252         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7253         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7254         2000 :             let mut writer = tline.writer().await;
    7255         2000 :             writer
    7256         2000 :                 .put(
    7257         2000 :                     test_key,
    7258         2000 :                     lsn,
    7259         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7260         2000 :                     &ctx,
    7261         2000 :                 )
    7262            2 :                 .await?;
    7263         2000 :             writer.finish_write(lsn);
    7264         2000 :             updated[blknum] = lsn;
    7265         2000 :             drop(writer);
    7266            2 :         }
    7267            2 : 
    7268            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7269            2 : 
    7270           24 :         for iter in 0..=10 {
    7271            2 :             // Read all the blocks
    7272        22000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7273        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7274        22000 :                 assert_eq!(
    7275        22000 :                     tline.get(test_key, lsn, &ctx).await?,
    7276        22000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7277            2 :                 );
    7278            2 :             }
    7279            2 : 
    7280           22 :             let mut cnt = 0;
    7281        22000 :             for (key, value) in tline
    7282           22 :                 .get_vectored_impl(
    7283           22 :                     keyspace.clone(),
    7284           22 :                     lsn,
    7285           22 :                     &mut ValuesReconstructState::default(),
    7286           22 :                     &ctx,
    7287           22 :                 )
    7288          770 :                 .await?
    7289            2 :             {
    7290        22000 :                 let blknum = key.field6 as usize;
    7291        22000 :                 let value = value?;
    7292        22000 :                 assert!(blknum % STEP == 0);
    7293        22000 :                 let blknum = blknum / STEP;
    7294        22000 :                 assert_eq!(
    7295        22000 :                     value,
    7296        22000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7297        22000 :                 );
    7298        22000 :                 cnt += 1;
    7299            2 :             }
    7300            2 : 
    7301           22 :             assert_eq!(cnt, NUM_KEYS);
    7302            2 : 
    7303        22022 :             for _ in 0..NUM_KEYS {
    7304        22000 :                 lsn = Lsn(lsn.0 + 0x10);
    7305        22000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7306        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7307        22000 :                 let mut writer = tline.writer().await;
    7308        22000 :                 writer
    7309        22000 :                     .put(
    7310        22000 :                         test_key,
    7311        22000 :                         lsn,
    7312        22000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7313        22000 :                         &ctx,
    7314        22000 :                     )
    7315          111 :                     .await?;
    7316        22000 :                 writer.finish_write(lsn);
    7317        22000 :                 drop(writer);
    7318        22000 :                 updated[blknum] = lsn;
    7319            2 :             }
    7320            2 : 
    7321            2 :             // Perform two cycles of flush, compact, and GC
    7322           66 :             for round in 0..2 {
    7323           44 :                 tline.freeze_and_flush().await?;
    7324           44 :                 tline
    7325           44 :                     .compact(
    7326           44 :                         &cancel,
    7327           44 :                         if iter % 5 == 0 && round == 0 {
    7328            6 :                             let mut flags = EnumSet::new();
    7329            6 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7330            6 :                             flags.insert(CompactFlags::ForceRepartition);
    7331            6 :                             flags
    7332            2 :                         } else {
    7333           38 :                             EnumSet::empty()
    7334            2 :                         },
    7335           44 :                         &ctx,
    7336            2 :                     )
    7337         6689 :                     .await?;
    7338           44 :                 tenant
    7339           44 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7340            2 :                     .await?;
    7341            2 :             }
    7342            2 :         }
    7343            2 : 
    7344            2 :         Ok(())
    7345            2 :     }
    7346              : 
    7347              :     #[tokio::test]
    7348            2 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7349            2 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7350           20 :         let (tenant, ctx) = harness.load().await;
    7351            2 :         let tline = tenant
    7352            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7353            6 :             .await?;
    7354            2 : 
    7355            2 :         let cancel = CancellationToken::new();
    7356            2 : 
    7357            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7358            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7359            2 :         let test_key = base_key;
    7360            2 :         let mut lsn = Lsn(0x10);
    7361            2 : 
    7362           42 :         for _ in 0..20 {
    7363           40 :             lsn = Lsn(lsn.0 + 0x10);
    7364           40 :             let mut writer = tline.writer().await;
    7365           40 :             writer
    7366           40 :                 .put(
    7367           40 :                     test_key,
    7368           40 :                     lsn,
    7369           40 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7370           40 :                     &ctx,
    7371           40 :                 )
    7372           20 :                 .await?;
    7373           40 :             writer.finish_write(lsn);
    7374           40 :             drop(writer);
    7375           41 :             tline.freeze_and_flush().await?; // force create a delta layer
    7376            2 :         }
    7377            2 : 
    7378            2 :         let before_num_l0_delta_files =
    7379            2 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7380            2 : 
    7381          110 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7382            2 : 
    7383            2 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7384            2 : 
    7385            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}");
    7386            2 : 
    7387            2 :         assert_eq!(
    7388            4 :             tline.get(test_key, lsn, &ctx).await?,
    7389            2 :             test_img(&format!("{} at {}", 0, lsn))
    7390            2 :         );
    7391            2 : 
    7392            2 :         Ok(())
    7393            2 :     }
    7394              : 
    7395              :     #[tokio::test]
    7396            2 :     async fn test_aux_file_e2e() {
    7397            2 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7398            2 : 
    7399           20 :         let (tenant, ctx) = harness.load().await;
    7400            2 : 
    7401            2 :         let mut lsn = Lsn(0x08);
    7402            2 : 
    7403            2 :         let tline: Arc<Timeline> = tenant
    7404            2 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7405            6 :             .await
    7406            2 :             .unwrap();
    7407            2 : 
    7408            2 :         {
    7409            2 :             lsn += 8;
    7410            2 :             let mut modification = tline.begin_modification(lsn);
    7411            2 :             modification
    7412            2 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7413            2 :                 .await
    7414            2 :                 .unwrap();
    7415            2 :             modification.commit(&ctx).await.unwrap();
    7416            2 :         }
    7417            2 : 
    7418            2 :         // we can read everything from the storage
    7419            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7420            2 :         assert_eq!(
    7421            2 :             files.get("pg_logical/mappings/test1"),
    7422            2 :             Some(&bytes::Bytes::from_static(b"first"))
    7423            2 :         );
    7424            2 : 
    7425            2 :         {
    7426            2 :             lsn += 8;
    7427            2 :             let mut modification = tline.begin_modification(lsn);
    7428            2 :             modification
    7429            2 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7430            2 :                 .await
    7431            2 :                 .unwrap();
    7432            2 :             modification.commit(&ctx).await.unwrap();
    7433            2 :         }
    7434            2 : 
    7435            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7436            2 :         assert_eq!(
    7437            2 :             files.get("pg_logical/mappings/test2"),
    7438            2 :             Some(&bytes::Bytes::from_static(b"second"))
    7439            2 :         );
    7440            2 : 
    7441            2 :         let child = tenant
    7442            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7443            2 :             .await
    7444            2 :             .unwrap();
    7445            2 : 
    7446            2 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    7447            2 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7448            2 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7449            2 :     }
    7450              : 
    7451              :     #[tokio::test]
    7452            2 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7453            2 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7454           20 :         let (tenant, ctx) = harness.load().await;
    7455            2 :         let tline = tenant
    7456            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7457            6 :             .await?;
    7458            2 : 
    7459            2 :         const NUM_KEYS: usize = 1000;
    7460            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7461            2 : 
    7462            2 :         let cancel = CancellationToken::new();
    7463            2 : 
    7464            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7465            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7466            2 :         let mut test_key = base_key;
    7467            2 :         let mut lsn = Lsn(0x10);
    7468            2 : 
    7469            8 :         async fn scan_with_statistics(
    7470            8 :             tline: &Timeline,
    7471            8 :             keyspace: &KeySpace,
    7472            8 :             lsn: Lsn,
    7473            8 :             ctx: &RequestContext,
    7474            8 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7475            8 :             let mut reconstruct_state = ValuesReconstructState::default();
    7476            8 :             let res = tline
    7477            8 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7478          239 :                 .await?;
    7479            8 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7480            8 :         }
    7481            2 : 
    7482            2 :         #[allow(clippy::needless_range_loop)]
    7483         2002 :         for blknum in 0..NUM_KEYS {
    7484         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7485         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7486         2000 :             let mut writer = tline.writer().await;
    7487         2000 :             writer
    7488         2000 :                 .put(
    7489         2000 :                     test_key,
    7490         2000 :                     lsn,
    7491         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7492         2000 :                     &ctx,
    7493         2000 :                 )
    7494            2 :                 .await?;
    7495         2000 :             writer.finish_write(lsn);
    7496         2000 :             drop(writer);
    7497            2 :         }
    7498            2 : 
    7499            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7500            2 : 
    7501           22 :         for iter in 1..=10 {
    7502        20020 :             for _ in 0..NUM_KEYS {
    7503        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7504        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7505        20000 :                 test_key.field6 = (blknum * STEP) as u32;
    7506        20000 :                 let mut writer = tline.writer().await;
    7507        20000 :                 writer
    7508        20000 :                     .put(
    7509        20000 :                         test_key,
    7510        20000 :                         lsn,
    7511        20000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7512        20000 :                         &ctx,
    7513        20000 :                     )
    7514           35 :                     .await?;
    7515        20000 :                 writer.finish_write(lsn);
    7516        20000 :                 drop(writer);
    7517            2 :             }
    7518            2 : 
    7519           20 :             tline.freeze_and_flush().await?;
    7520            2 : 
    7521           20 :             if iter % 5 == 0 {
    7522            4 :                 let (_, before_delta_file_accessed) =
    7523          231 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7524            4 :                 tline
    7525            4 :                     .compact(
    7526            4 :                         &cancel,
    7527            4 :                         {
    7528            4 :                             let mut flags = EnumSet::new();
    7529            4 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7530            4 :                             flags.insert(CompactFlags::ForceRepartition);
    7531            4 :                             flags
    7532            4 :                         },
    7533            4 :                         &ctx,
    7534            4 :                     )
    7535         4842 :                     .await?;
    7536            4 :                 let (_, after_delta_file_accessed) =
    7537            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7538            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}");
    7539            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.
    7540            4 :                 assert!(
    7541            4 :                     after_delta_file_accessed <= 2,
    7542            2 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7543            2 :                 );
    7544           16 :             }
    7545            2 :         }
    7546            2 : 
    7547            2 :         Ok(())
    7548            2 :     }
    7549              : 
    7550              :     #[tokio::test]
    7551            2 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7552            2 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7553           16 :         let (tenant, ctx) = harness.load().await;
    7554            2 : 
    7555            2 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7556            2 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7557            2 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7558            2 : 
    7559            2 :         let tline = tenant
    7560            2 :             .create_test_timeline_with_layers(
    7561            2 :                 TIMELINE_ID,
    7562            2 :                 Lsn(0x10),
    7563            2 :                 DEFAULT_PG_VERSION,
    7564            2 :                 &ctx,
    7565            2 :                 Vec::new(), // delta layers
    7566            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7567            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
    7568            2 :             )
    7569           13 :             .await?;
    7570            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7571            2 : 
    7572            2 :         let child = tenant
    7573            2 :             .branch_timeline_test_with_layers(
    7574            2 :                 &tline,
    7575            2 :                 NEW_TIMELINE_ID,
    7576            2 :                 Some(Lsn(0x20)),
    7577            2 :                 &ctx,
    7578            2 :                 Vec::new(), // delta layers
    7579            2 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7580            2 :                 Lsn(0x30),
    7581            2 :             )
    7582            9 :             .await
    7583            2 :             .unwrap();
    7584            2 : 
    7585            2 :         let lsn = Lsn(0x30);
    7586            2 : 
    7587            2 :         // test vectored get on parent timeline
    7588            2 :         assert_eq!(
    7589            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7590            2 :             Some(test_img("data key 1"))
    7591            2 :         );
    7592            2 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7593            3 :             .await
    7594            2 :             .unwrap_err()
    7595            2 :             .is_missing_key_error());
    7596            2 :         assert!(
    7597            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7598            2 :                 .await
    7599            2 :                 .unwrap_err()
    7600            2 :                 .is_missing_key_error()
    7601            2 :         );
    7602            2 : 
    7603            2 :         // test vectored get on child timeline
    7604            2 :         assert_eq!(
    7605            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7606            2 :             Some(test_img("data key 1"))
    7607            2 :         );
    7608            2 :         assert_eq!(
    7609            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7610            2 :             Some(test_img("data key 2"))
    7611            2 :         );
    7612            2 :         assert!(
    7613            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7614            2 :                 .await
    7615            2 :                 .unwrap_err()
    7616            2 :                 .is_missing_key_error()
    7617            2 :         );
    7618            2 : 
    7619            2 :         Ok(())
    7620            2 :     }
    7621              : 
    7622              :     #[tokio::test]
    7623            2 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7624            2 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7625           20 :         let (tenant, ctx) = harness.load().await;
    7626            2 : 
    7627            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7628            2 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7629            2 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7630            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7631            2 : 
    7632            2 :         let tline = tenant
    7633            2 :             .create_test_timeline_with_layers(
    7634            2 :                 TIMELINE_ID,
    7635            2 :                 Lsn(0x10),
    7636            2 :                 DEFAULT_PG_VERSION,
    7637            2 :                 &ctx,
    7638            2 :                 Vec::new(), // delta layers
    7639            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
    7640            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
    7641            2 :             )
    7642           13 :             .await?;
    7643            2 : 
    7644            2 :         let child = tenant
    7645            2 :             .branch_timeline_test_with_layers(
    7646            2 :                 &tline,
    7647            2 :                 NEW_TIMELINE_ID,
    7648            2 :                 Some(Lsn(0x20)),
    7649            2 :                 &ctx,
    7650            2 :                 Vec::new(), // delta layers
    7651            2 :                 vec![(
    7652            2 :                     Lsn(0x30),
    7653            2 :                     vec![(base_key_child, test_img("metadata key 2"))],
    7654            2 :                 )], // image layers
    7655            2 :                 Lsn(0x30),
    7656            2 :             )
    7657            8 :             .await
    7658            2 :             .unwrap();
    7659            2 : 
    7660            2 :         let lsn = Lsn(0x30);
    7661            2 : 
    7662            2 :         // test vectored get on parent timeline
    7663            2 :         assert_eq!(
    7664            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7665            2 :             Some(test_img("metadata key 1"))
    7666            2 :         );
    7667            2 :         assert_eq!(
    7668            2 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7669            2 :             None
    7670            2 :         );
    7671            2 :         assert_eq!(
    7672            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7673            2 :             None
    7674            2 :         );
    7675            2 : 
    7676            2 :         // test vectored get on child timeline
    7677            2 :         assert_eq!(
    7678            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7679            2 :             None
    7680            2 :         );
    7681            2 :         assert_eq!(
    7682            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7683            2 :             Some(test_img("metadata key 2"))
    7684            2 :         );
    7685            2 :         assert_eq!(
    7686            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7687            2 :             None
    7688            2 :         );
    7689            2 : 
    7690            2 :         Ok(())
    7691            2 :     }
    7692              : 
    7693           36 :     async fn get_vectored_impl_wrapper(
    7694           36 :         tline: &Arc<Timeline>,
    7695           36 :         key: Key,
    7696           36 :         lsn: Lsn,
    7697           36 :         ctx: &RequestContext,
    7698           36 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7699           36 :         let mut reconstruct_state = ValuesReconstructState::new();
    7700           36 :         let mut res = tline
    7701           36 :             .get_vectored_impl(
    7702           36 :                 KeySpace::single(key..key.next()),
    7703           36 :                 lsn,
    7704           36 :                 &mut reconstruct_state,
    7705           36 :                 ctx,
    7706           36 :             )
    7707           40 :             .await?;
    7708           30 :         Ok(res.pop_last().map(|(k, v)| {
    7709           18 :             assert_eq!(k, key);
    7710           18 :             v.unwrap()
    7711           30 :         }))
    7712           36 :     }
    7713              : 
    7714              :     #[tokio::test]
    7715            2 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    7716            2 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    7717           20 :         let (tenant, ctx) = harness.load().await;
    7718            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7719            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7720            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7721            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7722            2 : 
    7723            2 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    7724            2 :         // Lsn 0x30 key0, key3, no key1+key2
    7725            2 :         // Lsn 0x20 key1+key2 tomestones
    7726            2 :         // Lsn 0x10 key1 in image, key2 in delta
    7727            2 :         let tline = tenant
    7728            2 :             .create_test_timeline_with_layers(
    7729            2 :                 TIMELINE_ID,
    7730            2 :                 Lsn(0x10),
    7731            2 :                 DEFAULT_PG_VERSION,
    7732            2 :                 &ctx,
    7733            2 :                 // delta layers
    7734            2 :                 vec![
    7735            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7736            2 :                         Lsn(0x10)..Lsn(0x20),
    7737            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7738            2 :                     ),
    7739            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7740            2 :                         Lsn(0x20)..Lsn(0x30),
    7741            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7742            2 :                     ),
    7743            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7744            2 :                         Lsn(0x20)..Lsn(0x30),
    7745            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7746            2 :                     ),
    7747            2 :                 ],
    7748            2 :                 // image layers
    7749            2 :                 vec![
    7750            2 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    7751            2 :                     (
    7752            2 :                         Lsn(0x30),
    7753            2 :                         vec![
    7754            2 :                             (key0, test_img("metadata key 0")),
    7755            2 :                             (key3, test_img("metadata key 3")),
    7756            2 :                         ],
    7757            2 :                     ),
    7758            2 :                 ],
    7759            2 :                 Lsn(0x30),
    7760            2 :             )
    7761           40 :             .await?;
    7762            2 : 
    7763            2 :         let lsn = Lsn(0x30);
    7764            2 :         let old_lsn = Lsn(0x20);
    7765            2 : 
    7766            2 :         assert_eq!(
    7767            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    7768            2 :             Some(test_img("metadata key 0"))
    7769            2 :         );
    7770            2 :         assert_eq!(
    7771            2 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    7772            2 :             None,
    7773            2 :         );
    7774            2 :         assert_eq!(
    7775            2 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    7776            2 :             None,
    7777            2 :         );
    7778            2 :         assert_eq!(
    7779            8 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    7780            2 :             Some(Bytes::new()),
    7781            2 :         );
    7782            2 :         assert_eq!(
    7783            7 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    7784            2 :             Some(Bytes::new()),
    7785            2 :         );
    7786            2 :         assert_eq!(
    7787            2 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    7788            2 :             Some(test_img("metadata key 3"))
    7789            2 :         );
    7790            2 : 
    7791            2 :         Ok(())
    7792            2 :     }
    7793              : 
    7794              :     #[tokio::test]
    7795            2 :     async fn test_metadata_tombstone_image_creation() {
    7796            2 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    7797            2 :             .await
    7798            2 :             .unwrap();
    7799           20 :         let (tenant, ctx) = harness.load().await;
    7800            2 : 
    7801            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7802            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7803            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7804            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7805            2 : 
    7806            2 :         let tline = tenant
    7807            2 :             .create_test_timeline_with_layers(
    7808            2 :                 TIMELINE_ID,
    7809            2 :                 Lsn(0x10),
    7810            2 :                 DEFAULT_PG_VERSION,
    7811            2 :                 &ctx,
    7812            2 :                 // delta layers
    7813            2 :                 vec![
    7814            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7815            2 :                         Lsn(0x10)..Lsn(0x20),
    7816            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7817            2 :                     ),
    7818            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7819            2 :                         Lsn(0x20)..Lsn(0x30),
    7820            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7821            2 :                     ),
    7822            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7823            2 :                         Lsn(0x20)..Lsn(0x30),
    7824            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7825            2 :                     ),
    7826            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7827            2 :                         Lsn(0x30)..Lsn(0x40),
    7828            2 :                         vec![
    7829            2 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    7830            2 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    7831            2 :                         ],
    7832            2 :                     ),
    7833            2 :                 ],
    7834            2 :                 // image layers
    7835            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7836            2 :                 Lsn(0x40),
    7837            2 :             )
    7838           37 :             .await
    7839            2 :             .unwrap();
    7840            2 : 
    7841            2 :         let cancel = CancellationToken::new();
    7842            2 : 
    7843            2 :         tline
    7844            2 :             .compact(
    7845            2 :                 &cancel,
    7846            2 :                 {
    7847            2 :                     let mut flags = EnumSet::new();
    7848            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7849            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7850            2 :                     flags
    7851            2 :                 },
    7852            2 :                 &ctx,
    7853            2 :             )
    7854           62 :             .await
    7855            2 :             .unwrap();
    7856            2 : 
    7857            2 :         // Image layers are created at last_record_lsn
    7858            2 :         let images = tline
    7859            2 :             .inspect_image_layers(Lsn(0x40), &ctx)
    7860            8 :             .await
    7861            2 :             .unwrap()
    7862            2 :             .into_iter()
    7863           18 :             .filter(|(k, _)| k.is_metadata_key())
    7864            2 :             .collect::<Vec<_>>();
    7865            2 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    7866            2 :     }
    7867              : 
    7868              :     #[tokio::test]
    7869            2 :     async fn test_metadata_tombstone_empty_image_creation() {
    7870            2 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    7871            2 :             .await
    7872            2 :             .unwrap();
    7873           20 :         let (tenant, ctx) = harness.load().await;
    7874            2 : 
    7875            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7876            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7877            2 : 
    7878            2 :         let tline = tenant
    7879            2 :             .create_test_timeline_with_layers(
    7880            2 :                 TIMELINE_ID,
    7881            2 :                 Lsn(0x10),
    7882            2 :                 DEFAULT_PG_VERSION,
    7883            2 :                 &ctx,
    7884            2 :                 // delta layers
    7885            2 :                 vec![
    7886            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7887            2 :                         Lsn(0x10)..Lsn(0x20),
    7888            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7889            2 :                     ),
    7890            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7891            2 :                         Lsn(0x20)..Lsn(0x30),
    7892            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7893            2 :                     ),
    7894            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7895            2 :                         Lsn(0x20)..Lsn(0x30),
    7896            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7897            2 :                     ),
    7898            2 :                 ],
    7899            2 :                 // image layers
    7900            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7901            2 :                 Lsn(0x30),
    7902            2 :             )
    7903           31 :             .await
    7904            2 :             .unwrap();
    7905            2 : 
    7906            2 :         let cancel = CancellationToken::new();
    7907            2 : 
    7908            2 :         tline
    7909            2 :             .compact(
    7910            2 :                 &cancel,
    7911            2 :                 {
    7912            2 :                     let mut flags = EnumSet::new();
    7913            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7914            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7915            2 :                     flags
    7916            2 :                 },
    7917            2 :                 &ctx,
    7918            2 :             )
    7919           50 :             .await
    7920            2 :             .unwrap();
    7921            2 : 
    7922            2 :         // Image layers are created at last_record_lsn
    7923            2 :         let images = tline
    7924            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    7925            4 :             .await
    7926            2 :             .unwrap()
    7927            2 :             .into_iter()
    7928           14 :             .filter(|(k, _)| k.is_metadata_key())
    7929            2 :             .collect::<Vec<_>>();
    7930            2 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    7931            2 :     }
    7932              : 
    7933              :     #[tokio::test]
    7934            2 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    7935            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    7936           20 :         let (tenant, ctx) = harness.load().await;
    7937            2 : 
    7938          102 :         fn get_key(id: u32) -> Key {
    7939          102 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7940          102 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7941          102 :             key.field6 = id;
    7942          102 :             key
    7943          102 :         }
    7944            2 : 
    7945            2 :         // We create
    7946            2 :         // - one bottom-most image layer,
    7947            2 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    7948            2 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    7949            2 :         // - a delta layer D3 above the horizon.
    7950            2 :         //
    7951            2 :         //                             | D3 |
    7952            2 :         //  | D1 |
    7953            2 :         // -|    |-- gc horizon -----------------
    7954            2 :         //  |    |                | D2 |
    7955            2 :         // --------- img layer ------------------
    7956            2 :         //
    7957            2 :         // What we should expact from this compaction is:
    7958            2 :         //                             | D3 |
    7959            2 :         //  | Part of D1 |
    7960            2 :         // --------- img layer with D1+D2 at GC horizon------------------
    7961            2 : 
    7962            2 :         // img layer at 0x10
    7963            2 :         let img_layer = (0..10)
    7964           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    7965            2 :             .collect_vec();
    7966            2 : 
    7967            2 :         let delta1 = vec![
    7968            2 :             (
    7969            2 :                 get_key(1),
    7970            2 :                 Lsn(0x20),
    7971            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    7972            2 :             ),
    7973            2 :             (
    7974            2 :                 get_key(2),
    7975            2 :                 Lsn(0x30),
    7976            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    7977            2 :             ),
    7978            2 :             (
    7979            2 :                 get_key(3),
    7980            2 :                 Lsn(0x40),
    7981            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    7982            2 :             ),
    7983            2 :         ];
    7984            2 :         let delta2 = vec![
    7985            2 :             (
    7986            2 :                 get_key(5),
    7987            2 :                 Lsn(0x20),
    7988            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    7989            2 :             ),
    7990            2 :             (
    7991            2 :                 get_key(6),
    7992            2 :                 Lsn(0x20),
    7993            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    7994            2 :             ),
    7995            2 :         ];
    7996            2 :         let delta3 = vec![
    7997            2 :             (
    7998            2 :                 get_key(8),
    7999            2 :                 Lsn(0x48),
    8000            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    8001            2 :             ),
    8002            2 :             (
    8003            2 :                 get_key(9),
    8004            2 :                 Lsn(0x48),
    8005            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    8006            2 :             ),
    8007            2 :         ];
    8008            2 : 
    8009            2 :         let tline = tenant
    8010            2 :             .create_test_timeline_with_layers(
    8011            2 :                 TIMELINE_ID,
    8012            2 :                 Lsn(0x10),
    8013            2 :                 DEFAULT_PG_VERSION,
    8014            2 :                 &ctx,
    8015            2 :                 vec![
    8016            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8017            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8018            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8019            2 :                 ], // delta layers
    8020            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8021            2 :                 Lsn(0x50),
    8022            2 :             )
    8023           49 :             .await?;
    8024            2 :         {
    8025            2 :             // Update GC info
    8026            2 :             let mut guard = tline.gc_info.write().unwrap();
    8027            2 :             guard.cutoffs.time = Lsn(0x30);
    8028            2 :             guard.cutoffs.space = Lsn(0x30);
    8029            2 :         }
    8030            2 : 
    8031            2 :         let expected_result = [
    8032            2 :             Bytes::from_static(b"value 0@0x10"),
    8033            2 :             Bytes::from_static(b"value 1@0x20"),
    8034            2 :             Bytes::from_static(b"value 2@0x30"),
    8035            2 :             Bytes::from_static(b"value 3@0x40"),
    8036            2 :             Bytes::from_static(b"value 4@0x10"),
    8037            2 :             Bytes::from_static(b"value 5@0x20"),
    8038            2 :             Bytes::from_static(b"value 6@0x20"),
    8039            2 :             Bytes::from_static(b"value 7@0x10"),
    8040            2 :             Bytes::from_static(b"value 8@0x48"),
    8041            2 :             Bytes::from_static(b"value 9@0x48"),
    8042            2 :         ];
    8043            2 : 
    8044           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8045           20 :             assert_eq!(
    8046           20 :                 tline
    8047           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8048           30 :                     .await
    8049           20 :                     .unwrap(),
    8050            2 :                 expected
    8051            2 :             );
    8052            2 :         }
    8053            2 : 
    8054            2 :         let cancel = CancellationToken::new();
    8055            2 :         tline
    8056            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8057           56 :             .await
    8058            2 :             .unwrap();
    8059            2 : 
    8060           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8061           20 :             assert_eq!(
    8062           20 :                 tline
    8063           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8064           20 :                     .await
    8065           20 :                     .unwrap(),
    8066            2 :                 expected
    8067            2 :             );
    8068            2 :         }
    8069            2 : 
    8070            2 :         // Check if the image layer at the GC horizon contains exactly what we want
    8071            2 :         let image_at_gc_horizon = tline
    8072            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8073            2 :             .await
    8074            2 :             .unwrap()
    8075            2 :             .into_iter()
    8076           34 :             .filter(|(k, _)| k.is_metadata_key())
    8077            2 :             .collect::<Vec<_>>();
    8078            2 : 
    8079            2 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8080            2 :         let expected_result = [
    8081            2 :             Bytes::from_static(b"value 0@0x10"),
    8082            2 :             Bytes::from_static(b"value 1@0x20"),
    8083            2 :             Bytes::from_static(b"value 2@0x30"),
    8084            2 :             Bytes::from_static(b"value 3@0x10"),
    8085            2 :             Bytes::from_static(b"value 4@0x10"),
    8086            2 :             Bytes::from_static(b"value 5@0x20"),
    8087            2 :             Bytes::from_static(b"value 6@0x20"),
    8088            2 :             Bytes::from_static(b"value 7@0x10"),
    8089            2 :             Bytes::from_static(b"value 8@0x10"),
    8090            2 :             Bytes::from_static(b"value 9@0x10"),
    8091            2 :         ];
    8092           22 :         for idx in 0..10 {
    8093           20 :             assert_eq!(
    8094           20 :                 image_at_gc_horizon[idx],
    8095           20 :                 (get_key(idx as u32), expected_result[idx].clone())
    8096           20 :             );
    8097            2 :         }
    8098            2 : 
    8099            2 :         // Check if old layers are removed / new layers have the expected LSN
    8100            2 :         let all_layers = inspect_and_sort(&tline, None).await;
    8101            2 :         assert_eq!(
    8102            2 :             all_layers,
    8103            2 :             vec![
    8104            2 :                 // Image layer at GC horizon
    8105            2 :                 PersistentLayerKey {
    8106            2 :                     key_range: Key::MIN..Key::MAX,
    8107            2 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8108            2 :                     is_delta: false
    8109            2 :                 },
    8110            2 :                 // The delta layer below the horizon
    8111            2 :                 PersistentLayerKey {
    8112            2 :                     key_range: get_key(3)..get_key(4),
    8113            2 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8114            2 :                     is_delta: true
    8115            2 :                 },
    8116            2 :                 // The delta3 layer that should not be picked for the compaction
    8117            2 :                 PersistentLayerKey {
    8118            2 :                     key_range: get_key(8)..get_key(10),
    8119            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8120            2 :                     is_delta: true
    8121            2 :                 }
    8122            2 :             ]
    8123            2 :         );
    8124            2 : 
    8125            2 :         // increase GC horizon and compact again
    8126            2 :         {
    8127            2 :             // Update GC info
    8128            2 :             let mut guard = tline.gc_info.write().unwrap();
    8129            2 :             guard.cutoffs.time = Lsn(0x40);
    8130            2 :             guard.cutoffs.space = Lsn(0x40);
    8131            2 :         }
    8132            2 :         tline
    8133            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8134           44 :             .await
    8135            2 :             .unwrap();
    8136            2 : 
    8137            2 :         Ok(())
    8138            2 :     }
    8139              : 
    8140              :     #[cfg(feature = "testing")]
    8141              :     #[tokio::test]
    8142            2 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8143            2 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8144           20 :         let (tenant, ctx) = harness.load().await;
    8145            2 : 
    8146           24 :         fn get_key(id: u32) -> Key {
    8147           24 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8148           24 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8149           24 :             key.field6 = id;
    8150           24 :             key
    8151           24 :         }
    8152            2 : 
    8153            2 :         let delta1 = vec![
    8154            2 :             (
    8155            2 :                 get_key(1),
    8156            2 :                 Lsn(0x20),
    8157            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8158            2 :             ),
    8159            2 :             (
    8160            2 :                 get_key(1),
    8161            2 :                 Lsn(0x30),
    8162            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8163            2 :             ),
    8164            2 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8165            2 :             (
    8166            2 :                 get_key(2),
    8167            2 :                 Lsn(0x20),
    8168            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8169            2 :             ),
    8170            2 :             (
    8171            2 :                 get_key(2),
    8172            2 :                 Lsn(0x30),
    8173            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8174            2 :             ),
    8175            2 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8176            2 :             (
    8177            2 :                 get_key(3),
    8178            2 :                 Lsn(0x20),
    8179            2 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8180            2 :             ),
    8181            2 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8182            2 :             (
    8183            2 :                 get_key(4),
    8184            2 :                 Lsn(0x20),
    8185            2 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8186            2 :             ),
    8187            2 :         ];
    8188            2 :         let image1 = vec![(get_key(1), "0x10".into())];
    8189            2 : 
    8190            2 :         let tline = tenant
    8191            2 :             .create_test_timeline_with_layers(
    8192            2 :                 TIMELINE_ID,
    8193            2 :                 Lsn(0x10),
    8194            2 :                 DEFAULT_PG_VERSION,
    8195            2 :                 &ctx,
    8196            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8197            2 :                     Lsn(0x10)..Lsn(0x40),
    8198            2 :                     delta1,
    8199            2 :                 )], // delta layers
    8200            2 :                 vec![(Lsn(0x10), image1)], // image layers
    8201            2 :                 Lsn(0x50),
    8202            2 :             )
    8203           19 :             .await?;
    8204            2 : 
    8205            2 :         assert_eq!(
    8206            8 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8207            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8208            2 :         );
    8209            2 :         assert_eq!(
    8210            2 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8211            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8212            2 :         );
    8213            2 : 
    8214            2 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8215            2 : 
    8216            2 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8217            2 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8218            2 : 
    8219            2 :         Ok(())
    8220            2 :     }
    8221              : 
    8222              :     #[tokio::test(start_paused = true)]
    8223            2 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8224            2 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8225            2 :             .await
    8226            2 :             .unwrap()
    8227            2 :             .load()
    8228           20 :             .await;
    8229            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8230            2 :         // initial transition into AttachedSingle.
    8231            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8232            2 :         tokio::time::resume();
    8233            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8234            2 : 
    8235            2 :         let end_lsn = Lsn(0x100);
    8236            2 :         let image_layers = (0x20..=0x90)
    8237            2 :             .step_by(0x10)
    8238           16 :             .map(|n| {
    8239           16 :                 (
    8240           16 :                     Lsn(n),
    8241           16 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8242           16 :                 )
    8243           16 :             })
    8244            2 :             .collect();
    8245            2 : 
    8246            2 :         let timeline = tenant
    8247            2 :             .create_test_timeline_with_layers(
    8248            2 :                 TIMELINE_ID,
    8249            2 :                 Lsn(0x10),
    8250            2 :                 DEFAULT_PG_VERSION,
    8251            2 :                 &ctx,
    8252            2 :                 Vec::new(),
    8253            2 :                 image_layers,
    8254            2 :                 end_lsn,
    8255            2 :             )
    8256           61 :             .await?;
    8257            2 : 
    8258            2 :         let leased_lsns = [0x30, 0x50, 0x70];
    8259            2 :         let mut leases = Vec::new();
    8260            6 :         leased_lsns.iter().for_each(|n| {
    8261            6 :             leases.push(
    8262            6 :                 timeline
    8263            6 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8264            6 :                     .expect("lease request should succeed"),
    8265            6 :             );
    8266            6 :         });
    8267            2 : 
    8268            2 :         let updated_lease_0 = timeline
    8269            2 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8270            2 :             .expect("lease renewal should succeed");
    8271            2 :         assert_eq!(
    8272            2 :             updated_lease_0.valid_until, leases[0].valid_until,
    8273            2 :             " Renewing with shorter lease should not change the lease."
    8274            2 :         );
    8275            2 : 
    8276            2 :         let updated_lease_1 = timeline
    8277            2 :             .renew_lsn_lease(
    8278            2 :                 Lsn(leased_lsns[1]),
    8279            2 :                 timeline.get_lsn_lease_length() * 2,
    8280            2 :                 &ctx,
    8281            2 :             )
    8282            2 :             .expect("lease renewal should succeed");
    8283            2 :         assert!(
    8284            2 :             updated_lease_1.valid_until > leases[1].valid_until,
    8285            2 :             "Renewing with a long lease should renew lease with later expiration time."
    8286            2 :         );
    8287            2 : 
    8288            2 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8289            2 :         info!(
    8290            2 :             "latest_gc_cutoff_lsn: {}",
    8291            0 :             *timeline.get_latest_gc_cutoff_lsn()
    8292            2 :         );
    8293            2 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8294            2 : 
    8295            2 :         let res = tenant
    8296            2 :             .gc_iteration(
    8297            2 :                 Some(TIMELINE_ID),
    8298            2 :                 0,
    8299            2 :                 Duration::ZERO,
    8300            2 :                 &CancellationToken::new(),
    8301            2 :                 &ctx,
    8302            2 :             )
    8303            2 :             .await
    8304            2 :             .unwrap();
    8305            2 : 
    8306            2 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8307            2 :         // 0/10: initdb layer
    8308            2 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8309            2 :         assert_eq!(res.layers_needed_by_leases, 7);
    8310            2 :         // Keeping 0/90 b/c it is the latest layer.
    8311            2 :         assert_eq!(res.layers_not_updated, 1);
    8312            2 :         // Removed 0/80.
    8313            2 :         assert_eq!(res.layers_removed, 1);
    8314            2 : 
    8315            2 :         // Make lease on a already GC-ed LSN.
    8316            2 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8317            2 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    8318            2 :         timeline
    8319            2 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8320            2 :             .expect_err("lease request on GC-ed LSN should fail");
    8321            2 : 
    8322            2 :         // Should still be able to renew a currently valid lease
    8323            2 :         // Assumption: original lease to is still valid for 0/50.
    8324            2 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8325            2 :         timeline
    8326            2 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8327            2 :             .expect("lease renewal with validation should succeed");
    8328            2 : 
    8329            2 :         Ok(())
    8330            2 :     }
    8331              : 
    8332              :     #[cfg(feature = "testing")]
    8333              :     #[tokio::test]
    8334            2 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8335            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8336            2 :             "test_simple_bottom_most_compaction_deltas_1",
    8337            2 :             false,
    8338            2 :         )
    8339          243 :         .await
    8340            2 :     }
    8341              : 
    8342              :     #[cfg(feature = "testing")]
    8343              :     #[tokio::test]
    8344            2 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8345            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8346            2 :             "test_simple_bottom_most_compaction_deltas_2",
    8347            2 :             true,
    8348            2 :         )
    8349          221 :         .await
    8350            2 :     }
    8351              : 
    8352              :     #[cfg(feature = "testing")]
    8353            4 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8354            4 :         test_name: &'static str,
    8355            4 :         use_delta_bottom_layer: bool,
    8356            4 :     ) -> anyhow::Result<()> {
    8357            4 :         let harness = TenantHarness::create(test_name).await?;
    8358           40 :         let (tenant, ctx) = harness.load().await;
    8359              : 
    8360          276 :         fn get_key(id: u32) -> Key {
    8361          276 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8362          276 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8363          276 :             key.field6 = id;
    8364          276 :             key
    8365          276 :         }
    8366              : 
    8367              :         // We create
    8368              :         // - one bottom-most image layer,
    8369              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8370              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8371              :         // - a delta layer D3 above the horizon.
    8372              :         //
    8373              :         //                             | D3 |
    8374              :         //  | D1 |
    8375              :         // -|    |-- gc horizon -----------------
    8376              :         //  |    |                | D2 |
    8377              :         // --------- img layer ------------------
    8378              :         //
    8379              :         // What we should expact from this compaction is:
    8380              :         //                             | D3 |
    8381              :         //  | Part of D1 |
    8382              :         // --------- img layer with D1+D2 at GC horizon------------------
    8383              : 
    8384              :         // img layer at 0x10
    8385            4 :         let img_layer = (0..10)
    8386           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8387            4 :             .collect_vec();
    8388            4 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8389            4 :         let delta4 = (0..10)
    8390           40 :             .map(|id| {
    8391           40 :                 (
    8392           40 :                     get_key(id),
    8393           40 :                     Lsn(0x08),
    8394           40 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8395           40 :                 )
    8396           40 :             })
    8397            4 :             .collect_vec();
    8398            4 : 
    8399            4 :         let delta1 = vec![
    8400            4 :             (
    8401            4 :                 get_key(1),
    8402            4 :                 Lsn(0x20),
    8403            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8404            4 :             ),
    8405            4 :             (
    8406            4 :                 get_key(2),
    8407            4 :                 Lsn(0x30),
    8408            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8409            4 :             ),
    8410            4 :             (
    8411            4 :                 get_key(3),
    8412            4 :                 Lsn(0x28),
    8413            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8414            4 :             ),
    8415            4 :             (
    8416            4 :                 get_key(3),
    8417            4 :                 Lsn(0x30),
    8418            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8419            4 :             ),
    8420            4 :             (
    8421            4 :                 get_key(3),
    8422            4 :                 Lsn(0x40),
    8423            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8424            4 :             ),
    8425            4 :         ];
    8426            4 :         let delta2 = vec![
    8427            4 :             (
    8428            4 :                 get_key(5),
    8429            4 :                 Lsn(0x20),
    8430            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8431            4 :             ),
    8432            4 :             (
    8433            4 :                 get_key(6),
    8434            4 :                 Lsn(0x20),
    8435            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8436            4 :             ),
    8437            4 :         ];
    8438            4 :         let delta3 = vec![
    8439            4 :             (
    8440            4 :                 get_key(8),
    8441            4 :                 Lsn(0x48),
    8442            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8443            4 :             ),
    8444            4 :             (
    8445            4 :                 get_key(9),
    8446            4 :                 Lsn(0x48),
    8447            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8448            4 :             ),
    8449            4 :         ];
    8450              : 
    8451            4 :         let tline = if use_delta_bottom_layer {
    8452            2 :             tenant
    8453            2 :                 .create_test_timeline_with_layers(
    8454            2 :                     TIMELINE_ID,
    8455            2 :                     Lsn(0x08),
    8456            2 :                     DEFAULT_PG_VERSION,
    8457            2 :                     &ctx,
    8458            2 :                     vec![
    8459            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8460            2 :                             Lsn(0x08)..Lsn(0x10),
    8461            2 :                             delta4,
    8462            2 :                         ),
    8463            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8464            2 :                             Lsn(0x20)..Lsn(0x48),
    8465            2 :                             delta1,
    8466            2 :                         ),
    8467            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8468            2 :                             Lsn(0x20)..Lsn(0x48),
    8469            2 :                             delta2,
    8470            2 :                         ),
    8471            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8472            2 :                             Lsn(0x48)..Lsn(0x50),
    8473            2 :                             delta3,
    8474            2 :                         ),
    8475            2 :                     ], // delta layers
    8476            2 :                     vec![], // image layers
    8477            2 :                     Lsn(0x50),
    8478            2 :                 )
    8479           30 :                 .await?
    8480              :         } else {
    8481            2 :             tenant
    8482            2 :                 .create_test_timeline_with_layers(
    8483            2 :                     TIMELINE_ID,
    8484            2 :                     Lsn(0x10),
    8485            2 :                     DEFAULT_PG_VERSION,
    8486            2 :                     &ctx,
    8487            2 :                     vec![
    8488            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8489            2 :                             Lsn(0x10)..Lsn(0x48),
    8490            2 :                             delta1,
    8491            2 :                         ),
    8492            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8493            2 :                             Lsn(0x10)..Lsn(0x48),
    8494            2 :                             delta2,
    8495            2 :                         ),
    8496            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8497            2 :                             Lsn(0x48)..Lsn(0x50),
    8498            2 :                             delta3,
    8499            2 :                         ),
    8500            2 :                     ], // delta layers
    8501            2 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8502            2 :                     Lsn(0x50),
    8503            2 :                 )
    8504           49 :                 .await?
    8505              :         };
    8506            4 :         {
    8507            4 :             // Update GC info
    8508            4 :             let mut guard = tline.gc_info.write().unwrap();
    8509            4 :             *guard = GcInfo {
    8510            4 :                 retain_lsns: vec![],
    8511            4 :                 cutoffs: GcCutoffs {
    8512            4 :                     time: Lsn(0x30),
    8513            4 :                     space: Lsn(0x30),
    8514            4 :                 },
    8515            4 :                 leases: Default::default(),
    8516            4 :                 within_ancestor_pitr: false,
    8517            4 :             };
    8518            4 :         }
    8519            4 : 
    8520            4 :         let expected_result = [
    8521            4 :             Bytes::from_static(b"value 0@0x10"),
    8522            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8523            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8524            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8525            4 :             Bytes::from_static(b"value 4@0x10"),
    8526            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8527            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8528            4 :             Bytes::from_static(b"value 7@0x10"),
    8529            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8530            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8531            4 :         ];
    8532            4 : 
    8533            4 :         let expected_result_at_gc_horizon = [
    8534            4 :             Bytes::from_static(b"value 0@0x10"),
    8535            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8536            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8537            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8538            4 :             Bytes::from_static(b"value 4@0x10"),
    8539            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8540            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8541            4 :             Bytes::from_static(b"value 7@0x10"),
    8542            4 :             Bytes::from_static(b"value 8@0x10"),
    8543            4 :             Bytes::from_static(b"value 9@0x10"),
    8544            4 :         ];
    8545              : 
    8546           44 :         for idx in 0..10 {
    8547           40 :             assert_eq!(
    8548           40 :                 tline
    8549           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8550           60 :                     .await
    8551           40 :                     .unwrap(),
    8552           40 :                 &expected_result[idx]
    8553              :             );
    8554           40 :             assert_eq!(
    8555           40 :                 tline
    8556           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8557           31 :                     .await
    8558           40 :                     .unwrap(),
    8559           40 :                 &expected_result_at_gc_horizon[idx]
    8560              :             );
    8561              :         }
    8562              : 
    8563            4 :         let cancel = CancellationToken::new();
    8564            4 :         tline
    8565            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8566          109 :             .await
    8567            4 :             .unwrap();
    8568              : 
    8569           44 :         for idx in 0..10 {
    8570           40 :             assert_eq!(
    8571           40 :                 tline
    8572           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8573           39 :                     .await
    8574           40 :                     .unwrap(),
    8575           40 :                 &expected_result[idx]
    8576              :             );
    8577           40 :             assert_eq!(
    8578           40 :                 tline
    8579           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8580           21 :                     .await
    8581           40 :                     .unwrap(),
    8582           40 :                 &expected_result_at_gc_horizon[idx]
    8583              :             );
    8584              :         }
    8585              : 
    8586              :         // increase GC horizon and compact again
    8587            4 :         {
    8588            4 :             // Update GC info
    8589            4 :             let mut guard = tline.gc_info.write().unwrap();
    8590            4 :             guard.cutoffs.time = Lsn(0x40);
    8591            4 :             guard.cutoffs.space = Lsn(0x40);
    8592            4 :         }
    8593            4 :         tline
    8594            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8595           85 :             .await
    8596            4 :             .unwrap();
    8597            4 : 
    8598            4 :         Ok(())
    8599            4 :     }
    8600              : 
    8601              :     #[cfg(feature = "testing")]
    8602              :     #[tokio::test]
    8603            2 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8604            2 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8605           20 :         let (tenant, ctx) = harness.load().await;
    8606            2 :         let tline = tenant
    8607            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8608            6 :             .await?;
    8609            2 :         tline.force_advance_lsn(Lsn(0x70));
    8610            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8611            2 :         let history = vec![
    8612            2 :             (
    8613            2 :                 key,
    8614            2 :                 Lsn(0x10),
    8615            2 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8616            2 :             ),
    8617            2 :             (
    8618            2 :                 key,
    8619            2 :                 Lsn(0x20),
    8620            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8621            2 :             ),
    8622            2 :             (
    8623            2 :                 key,
    8624            2 :                 Lsn(0x30),
    8625            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8626            2 :             ),
    8627            2 :             (
    8628            2 :                 key,
    8629            2 :                 Lsn(0x40),
    8630            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8631            2 :             ),
    8632            2 :             (
    8633            2 :                 key,
    8634            2 :                 Lsn(0x50),
    8635            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8636            2 :             ),
    8637            2 :             (
    8638            2 :                 key,
    8639            2 :                 Lsn(0x60),
    8640            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8641            2 :             ),
    8642            2 :             (
    8643            2 :                 key,
    8644            2 :                 Lsn(0x70),
    8645            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8646            2 :             ),
    8647            2 :             (
    8648            2 :                 key,
    8649            2 :                 Lsn(0x80),
    8650            2 :                 Value::Image(Bytes::copy_from_slice(
    8651            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8652            2 :                 )),
    8653            2 :             ),
    8654            2 :             (
    8655            2 :                 key,
    8656            2 :                 Lsn(0x90),
    8657            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8658            2 :             ),
    8659            2 :         ];
    8660            2 :         let res = tline
    8661            2 :             .generate_key_retention(
    8662            2 :                 key,
    8663            2 :                 &history,
    8664            2 :                 Lsn(0x60),
    8665            2 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8666            2 :                 3,
    8667            2 :                 None,
    8668            2 :             )
    8669            2 :             .await
    8670            2 :             .unwrap();
    8671            2 :         let expected_res = KeyHistoryRetention {
    8672            2 :             below_horizon: vec![
    8673            2 :                 (
    8674            2 :                     Lsn(0x20),
    8675            2 :                     KeyLogAtLsn(vec![(
    8676            2 :                         Lsn(0x20),
    8677            2 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8678            2 :                     )]),
    8679            2 :                 ),
    8680            2 :                 (
    8681            2 :                     Lsn(0x40),
    8682            2 :                     KeyLogAtLsn(vec![
    8683            2 :                         (
    8684            2 :                             Lsn(0x30),
    8685            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8686            2 :                         ),
    8687            2 :                         (
    8688            2 :                             Lsn(0x40),
    8689            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8690            2 :                         ),
    8691            2 :                     ]),
    8692            2 :                 ),
    8693            2 :                 (
    8694            2 :                     Lsn(0x50),
    8695            2 :                     KeyLogAtLsn(vec![(
    8696            2 :                         Lsn(0x50),
    8697            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    8698            2 :                     )]),
    8699            2 :                 ),
    8700            2 :                 (
    8701            2 :                     Lsn(0x60),
    8702            2 :                     KeyLogAtLsn(vec![(
    8703            2 :                         Lsn(0x60),
    8704            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8705            2 :                     )]),
    8706            2 :                 ),
    8707            2 :             ],
    8708            2 :             above_horizon: KeyLogAtLsn(vec![
    8709            2 :                 (
    8710            2 :                     Lsn(0x70),
    8711            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8712            2 :                 ),
    8713            2 :                 (
    8714            2 :                     Lsn(0x80),
    8715            2 :                     Value::Image(Bytes::copy_from_slice(
    8716            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8717            2 :                     )),
    8718            2 :                 ),
    8719            2 :                 (
    8720            2 :                     Lsn(0x90),
    8721            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8722            2 :                 ),
    8723            2 :             ]),
    8724            2 :         };
    8725            2 :         assert_eq!(res, expected_res);
    8726            2 : 
    8727            2 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    8728            2 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    8729            2 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    8730            2 :         // For example, we have
    8731            2 :         // ```plain
    8732            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    8733            2 :         // ```
    8734            2 :         // Now the GC horizon moves up, and we have
    8735            2 :         // ```plain
    8736            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    8737            2 :         // ```
    8738            2 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    8739            2 :         // We will end up with
    8740            2 :         // ```plain
    8741            2 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    8742            2 :         // ```
    8743            2 :         // Now we run the GC-compaction, and this key does not have a full history.
    8744            2 :         // We should be able to handle this partial history and drop everything before the
    8745            2 :         // gc_horizon image.
    8746            2 : 
    8747            2 :         let history = vec![
    8748            2 :             (
    8749            2 :                 key,
    8750            2 :                 Lsn(0x20),
    8751            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8752            2 :             ),
    8753            2 :             (
    8754            2 :                 key,
    8755            2 :                 Lsn(0x30),
    8756            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8757            2 :             ),
    8758            2 :             (
    8759            2 :                 key,
    8760            2 :                 Lsn(0x40),
    8761            2 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8762            2 :             ),
    8763            2 :             (
    8764            2 :                 key,
    8765            2 :                 Lsn(0x50),
    8766            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8767            2 :             ),
    8768            2 :             (
    8769            2 :                 key,
    8770            2 :                 Lsn(0x60),
    8771            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8772            2 :             ),
    8773            2 :             (
    8774            2 :                 key,
    8775            2 :                 Lsn(0x70),
    8776            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8777            2 :             ),
    8778            2 :             (
    8779            2 :                 key,
    8780            2 :                 Lsn(0x80),
    8781            2 :                 Value::Image(Bytes::copy_from_slice(
    8782            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8783            2 :                 )),
    8784            2 :             ),
    8785            2 :             (
    8786            2 :                 key,
    8787            2 :                 Lsn(0x90),
    8788            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8789            2 :             ),
    8790            2 :         ];
    8791            2 :         let res = tline
    8792            2 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    8793            2 :             .await
    8794            2 :             .unwrap();
    8795            2 :         let expected_res = KeyHistoryRetention {
    8796            2 :             below_horizon: vec![
    8797            2 :                 (
    8798            2 :                     Lsn(0x40),
    8799            2 :                     KeyLogAtLsn(vec![(
    8800            2 :                         Lsn(0x40),
    8801            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8802            2 :                     )]),
    8803            2 :                 ),
    8804            2 :                 (
    8805            2 :                     Lsn(0x50),
    8806            2 :                     KeyLogAtLsn(vec![(
    8807            2 :                         Lsn(0x50),
    8808            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8809            2 :                     )]),
    8810            2 :                 ),
    8811            2 :                 (
    8812            2 :                     Lsn(0x60),
    8813            2 :                     KeyLogAtLsn(vec![(
    8814            2 :                         Lsn(0x60),
    8815            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8816            2 :                     )]),
    8817            2 :                 ),
    8818            2 :             ],
    8819            2 :             above_horizon: KeyLogAtLsn(vec![
    8820            2 :                 (
    8821            2 :                     Lsn(0x70),
    8822            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8823            2 :                 ),
    8824            2 :                 (
    8825            2 :                     Lsn(0x80),
    8826            2 :                     Value::Image(Bytes::copy_from_slice(
    8827            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8828            2 :                     )),
    8829            2 :                 ),
    8830            2 :                 (
    8831            2 :                     Lsn(0x90),
    8832            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8833            2 :                 ),
    8834            2 :             ]),
    8835            2 :         };
    8836            2 :         assert_eq!(res, expected_res);
    8837            2 : 
    8838            2 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    8839            2 :         // the ancestor image in the test case.
    8840            2 : 
    8841            2 :         let history = vec![
    8842            2 :             (
    8843            2 :                 key,
    8844            2 :                 Lsn(0x20),
    8845            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8846            2 :             ),
    8847            2 :             (
    8848            2 :                 key,
    8849            2 :                 Lsn(0x30),
    8850            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8851            2 :             ),
    8852            2 :             (
    8853            2 :                 key,
    8854            2 :                 Lsn(0x40),
    8855            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8856            2 :             ),
    8857            2 :             (
    8858            2 :                 key,
    8859            2 :                 Lsn(0x70),
    8860            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8861            2 :             ),
    8862            2 :         ];
    8863            2 :         let res = tline
    8864            2 :             .generate_key_retention(
    8865            2 :                 key,
    8866            2 :                 &history,
    8867            2 :                 Lsn(0x60),
    8868            2 :                 &[],
    8869            2 :                 3,
    8870            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    8871            2 :             )
    8872            2 :             .await
    8873            2 :             .unwrap();
    8874            2 :         let expected_res = KeyHistoryRetention {
    8875            2 :             below_horizon: vec![(
    8876            2 :                 Lsn(0x60),
    8877            2 :                 KeyLogAtLsn(vec![(
    8878            2 :                     Lsn(0x60),
    8879            2 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    8880            2 :                 )]),
    8881            2 :             )],
    8882            2 :             above_horizon: KeyLogAtLsn(vec![(
    8883            2 :                 Lsn(0x70),
    8884            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8885            2 :             )]),
    8886            2 :         };
    8887            2 :         assert_eq!(res, expected_res);
    8888            2 : 
    8889            2 :         let history = vec![
    8890            2 :             (
    8891            2 :                 key,
    8892            2 :                 Lsn(0x20),
    8893            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8894            2 :             ),
    8895            2 :             (
    8896            2 :                 key,
    8897            2 :                 Lsn(0x40),
    8898            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8899            2 :             ),
    8900            2 :             (
    8901            2 :                 key,
    8902            2 :                 Lsn(0x60),
    8903            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8904            2 :             ),
    8905            2 :             (
    8906            2 :                 key,
    8907            2 :                 Lsn(0x70),
    8908            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8909            2 :             ),
    8910            2 :         ];
    8911            2 :         let res = tline
    8912            2 :             .generate_key_retention(
    8913            2 :                 key,
    8914            2 :                 &history,
    8915            2 :                 Lsn(0x60),
    8916            2 :                 &[Lsn(0x30)],
    8917            2 :                 3,
    8918            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    8919            2 :             )
    8920            2 :             .await
    8921            2 :             .unwrap();
    8922            2 :         let expected_res = KeyHistoryRetention {
    8923            2 :             below_horizon: vec![
    8924            2 :                 (
    8925            2 :                     Lsn(0x30),
    8926            2 :                     KeyLogAtLsn(vec![(
    8927            2 :                         Lsn(0x20),
    8928            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8929            2 :                     )]),
    8930            2 :                 ),
    8931            2 :                 (
    8932            2 :                     Lsn(0x60),
    8933            2 :                     KeyLogAtLsn(vec![(
    8934            2 :                         Lsn(0x60),
    8935            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    8936            2 :                     )]),
    8937            2 :                 ),
    8938            2 :             ],
    8939            2 :             above_horizon: KeyLogAtLsn(vec![(
    8940            2 :                 Lsn(0x70),
    8941            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8942            2 :             )]),
    8943            2 :         };
    8944            2 :         assert_eq!(res, expected_res);
    8945            2 : 
    8946            2 :         Ok(())
    8947            2 :     }
    8948              : 
    8949              :     #[cfg(feature = "testing")]
    8950              :     #[tokio::test]
    8951            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    8952            2 :         let harness =
    8953            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    8954           20 :         let (tenant, ctx) = harness.load().await;
    8955            2 : 
    8956          518 :         fn get_key(id: u32) -> Key {
    8957          518 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8958          518 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8959          518 :             key.field6 = id;
    8960          518 :             key
    8961          518 :         }
    8962            2 : 
    8963            2 :         let img_layer = (0..10)
    8964           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8965            2 :             .collect_vec();
    8966            2 : 
    8967            2 :         let delta1 = vec![
    8968            2 :             (
    8969            2 :                 get_key(1),
    8970            2 :                 Lsn(0x20),
    8971            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8972            2 :             ),
    8973            2 :             (
    8974            2 :                 get_key(2),
    8975            2 :                 Lsn(0x30),
    8976            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8977            2 :             ),
    8978            2 :             (
    8979            2 :                 get_key(3),
    8980            2 :                 Lsn(0x28),
    8981            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8982            2 :             ),
    8983            2 :             (
    8984            2 :                 get_key(3),
    8985            2 :                 Lsn(0x30),
    8986            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8987            2 :             ),
    8988            2 :             (
    8989            2 :                 get_key(3),
    8990            2 :                 Lsn(0x40),
    8991            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8992            2 :             ),
    8993            2 :         ];
    8994            2 :         let delta2 = vec![
    8995            2 :             (
    8996            2 :                 get_key(5),
    8997            2 :                 Lsn(0x20),
    8998            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8999            2 :             ),
    9000            2 :             (
    9001            2 :                 get_key(6),
    9002            2 :                 Lsn(0x20),
    9003            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9004            2 :             ),
    9005            2 :         ];
    9006            2 :         let delta3 = vec![
    9007            2 :             (
    9008            2 :                 get_key(8),
    9009            2 :                 Lsn(0x48),
    9010            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9011            2 :             ),
    9012            2 :             (
    9013            2 :                 get_key(9),
    9014            2 :                 Lsn(0x48),
    9015            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9016            2 :             ),
    9017            2 :         ];
    9018            2 : 
    9019            2 :         let tline = tenant
    9020            2 :             .create_test_timeline_with_layers(
    9021            2 :                 TIMELINE_ID,
    9022            2 :                 Lsn(0x10),
    9023            2 :                 DEFAULT_PG_VERSION,
    9024            2 :                 &ctx,
    9025            2 :                 vec![
    9026            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9027            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9028            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9029            2 :                 ], // delta layers
    9030            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9031            2 :                 Lsn(0x50),
    9032            2 :             )
    9033           49 :             .await?;
    9034            2 :         {
    9035            2 :             // Update GC info
    9036            2 :             let mut guard = tline.gc_info.write().unwrap();
    9037            2 :             *guard = GcInfo {
    9038            2 :                 retain_lsns: vec![
    9039            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9040            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9041            2 :                 ],
    9042            2 :                 cutoffs: GcCutoffs {
    9043            2 :                     time: Lsn(0x30),
    9044            2 :                     space: Lsn(0x30),
    9045            2 :                 },
    9046            2 :                 leases: Default::default(),
    9047            2 :                 within_ancestor_pitr: false,
    9048            2 :             };
    9049            2 :         }
    9050            2 : 
    9051            2 :         let expected_result = [
    9052            2 :             Bytes::from_static(b"value 0@0x10"),
    9053            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9054            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9055            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9056            2 :             Bytes::from_static(b"value 4@0x10"),
    9057            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9058            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9059            2 :             Bytes::from_static(b"value 7@0x10"),
    9060            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9061            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9062            2 :         ];
    9063            2 : 
    9064            2 :         let expected_result_at_gc_horizon = [
    9065            2 :             Bytes::from_static(b"value 0@0x10"),
    9066            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9067            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9068            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9069            2 :             Bytes::from_static(b"value 4@0x10"),
    9070            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9071            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9072            2 :             Bytes::from_static(b"value 7@0x10"),
    9073            2 :             Bytes::from_static(b"value 8@0x10"),
    9074            2 :             Bytes::from_static(b"value 9@0x10"),
    9075            2 :         ];
    9076            2 : 
    9077            2 :         let expected_result_at_lsn_20 = [
    9078            2 :             Bytes::from_static(b"value 0@0x10"),
    9079            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9080            2 :             Bytes::from_static(b"value 2@0x10"),
    9081            2 :             Bytes::from_static(b"value 3@0x10"),
    9082            2 :             Bytes::from_static(b"value 4@0x10"),
    9083            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9084            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9085            2 :             Bytes::from_static(b"value 7@0x10"),
    9086            2 :             Bytes::from_static(b"value 8@0x10"),
    9087            2 :             Bytes::from_static(b"value 9@0x10"),
    9088            2 :         ];
    9089            2 : 
    9090            2 :         let expected_result_at_lsn_10 = [
    9091            2 :             Bytes::from_static(b"value 0@0x10"),
    9092            2 :             Bytes::from_static(b"value 1@0x10"),
    9093            2 :             Bytes::from_static(b"value 2@0x10"),
    9094            2 :             Bytes::from_static(b"value 3@0x10"),
    9095            2 :             Bytes::from_static(b"value 4@0x10"),
    9096            2 :             Bytes::from_static(b"value 5@0x10"),
    9097            2 :             Bytes::from_static(b"value 6@0x10"),
    9098            2 :             Bytes::from_static(b"value 7@0x10"),
    9099            2 :             Bytes::from_static(b"value 8@0x10"),
    9100            2 :             Bytes::from_static(b"value 9@0x10"),
    9101            2 :         ];
    9102            2 : 
    9103           12 :         let verify_result = || async {
    9104           12 :             let gc_horizon = {
    9105           12 :                 let gc_info = tline.gc_info.read().unwrap();
    9106           12 :                 gc_info.cutoffs.time
    9107            2 :             };
    9108          132 :             for idx in 0..10 {
    9109          120 :                 assert_eq!(
    9110          120 :                     tline
    9111          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9112          124 :                         .await
    9113          120 :                         .unwrap(),
    9114          120 :                     &expected_result[idx]
    9115            2 :                 );
    9116          120 :                 assert_eq!(
    9117          120 :                     tline
    9118          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9119           95 :                         .await
    9120          120 :                         .unwrap(),
    9121          120 :                     &expected_result_at_gc_horizon[idx]
    9122            2 :                 );
    9123          120 :                 assert_eq!(
    9124          120 :                     tline
    9125          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9126           82 :                         .await
    9127          120 :                         .unwrap(),
    9128          120 :                     &expected_result_at_lsn_20[idx]
    9129            2 :                 );
    9130          120 :                 assert_eq!(
    9131          120 :                     tline
    9132          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9133           60 :                         .await
    9134          120 :                         .unwrap(),
    9135          120 :                     &expected_result_at_lsn_10[idx]
    9136            2 :                 );
    9137            2 :             }
    9138           24 :         };
    9139            2 : 
    9140           69 :         verify_result().await;
    9141            2 : 
    9142            2 :         let cancel = CancellationToken::new();
    9143            2 :         let mut dryrun_flags = EnumSet::new();
    9144            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9145            2 : 
    9146            2 :         tline
    9147            2 :             .compact_with_gc(
    9148            2 :                 &cancel,
    9149            2 :                 CompactOptions {
    9150            2 :                     flags: dryrun_flags,
    9151            2 :                     compact_range: None,
    9152            2 :                 },
    9153            2 :                 &ctx,
    9154            2 :             )
    9155           48 :             .await
    9156            2 :             .unwrap();
    9157            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
    9158            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9159           57 :         verify_result().await;
    9160            2 : 
    9161            2 :         tline
    9162            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9163           50 :             .await
    9164            2 :             .unwrap();
    9165           64 :         verify_result().await;
    9166            2 : 
    9167            2 :         // compact again
    9168            2 :         tline
    9169            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9170           39 :             .await
    9171            2 :             .unwrap();
    9172           57 :         verify_result().await;
    9173            2 : 
    9174            2 :         // increase GC horizon and compact again
    9175            2 :         {
    9176            2 :             // Update GC info
    9177            2 :             let mut guard = tline.gc_info.write().unwrap();
    9178            2 :             guard.cutoffs.time = Lsn(0x38);
    9179            2 :             guard.cutoffs.space = Lsn(0x38);
    9180            2 :         }
    9181            2 :         tline
    9182            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9183           40 :             .await
    9184            2 :             .unwrap();
    9185           57 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9186            2 : 
    9187            2 :         // not increasing the GC horizon and compact again
    9188            2 :         tline
    9189            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9190           41 :             .await
    9191            2 :             .unwrap();
    9192           57 :         verify_result().await;
    9193            2 : 
    9194            2 :         Ok(())
    9195            2 :     }
    9196              : 
    9197              :     #[cfg(feature = "testing")]
    9198              :     #[tokio::test]
    9199            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9200            2 :     {
    9201            2 :         let harness =
    9202            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9203            2 :                 .await?;
    9204           20 :         let (tenant, ctx) = harness.load().await;
    9205            2 : 
    9206          352 :         fn get_key(id: u32) -> Key {
    9207          352 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9208          352 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9209          352 :             key.field6 = id;
    9210          352 :             key
    9211          352 :         }
    9212            2 : 
    9213            2 :         let img_layer = (0..10)
    9214           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9215            2 :             .collect_vec();
    9216            2 : 
    9217            2 :         let delta1 = vec![
    9218            2 :             (
    9219            2 :                 get_key(1),
    9220            2 :                 Lsn(0x20),
    9221            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9222            2 :             ),
    9223            2 :             (
    9224            2 :                 get_key(1),
    9225            2 :                 Lsn(0x28),
    9226            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9227            2 :             ),
    9228            2 :         ];
    9229            2 :         let delta2 = vec![
    9230            2 :             (
    9231            2 :                 get_key(1),
    9232            2 :                 Lsn(0x30),
    9233            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9234            2 :             ),
    9235            2 :             (
    9236            2 :                 get_key(1),
    9237            2 :                 Lsn(0x38),
    9238            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9239            2 :             ),
    9240            2 :         ];
    9241            2 :         let delta3 = vec![
    9242            2 :             (
    9243            2 :                 get_key(8),
    9244            2 :                 Lsn(0x48),
    9245            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9246            2 :             ),
    9247            2 :             (
    9248            2 :                 get_key(9),
    9249            2 :                 Lsn(0x48),
    9250            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9251            2 :             ),
    9252            2 :         ];
    9253            2 : 
    9254            2 :         let tline = tenant
    9255            2 :             .create_test_timeline_with_layers(
    9256            2 :                 TIMELINE_ID,
    9257            2 :                 Lsn(0x10),
    9258            2 :                 DEFAULT_PG_VERSION,
    9259            2 :                 &ctx,
    9260            2 :                 vec![
    9261            2 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9262            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9263            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9264            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9265            2 :                 ], // delta layers
    9266            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9267            2 :                 Lsn(0x50),
    9268            2 :             )
    9269           49 :             .await?;
    9270            2 :         {
    9271            2 :             // Update GC info
    9272            2 :             let mut guard = tline.gc_info.write().unwrap();
    9273            2 :             *guard = GcInfo {
    9274            2 :                 retain_lsns: vec![
    9275            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9276            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9277            2 :                 ],
    9278            2 :                 cutoffs: GcCutoffs {
    9279            2 :                     time: Lsn(0x30),
    9280            2 :                     space: Lsn(0x30),
    9281            2 :                 },
    9282            2 :                 leases: Default::default(),
    9283            2 :                 within_ancestor_pitr: false,
    9284            2 :             };
    9285            2 :         }
    9286            2 : 
    9287            2 :         let expected_result = [
    9288            2 :             Bytes::from_static(b"value 0@0x10"),
    9289            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9290            2 :             Bytes::from_static(b"value 2@0x10"),
    9291            2 :             Bytes::from_static(b"value 3@0x10"),
    9292            2 :             Bytes::from_static(b"value 4@0x10"),
    9293            2 :             Bytes::from_static(b"value 5@0x10"),
    9294            2 :             Bytes::from_static(b"value 6@0x10"),
    9295            2 :             Bytes::from_static(b"value 7@0x10"),
    9296            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9297            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9298            2 :         ];
    9299            2 : 
    9300            2 :         let expected_result_at_gc_horizon = [
    9301            2 :             Bytes::from_static(b"value 0@0x10"),
    9302            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9303            2 :             Bytes::from_static(b"value 2@0x10"),
    9304            2 :             Bytes::from_static(b"value 3@0x10"),
    9305            2 :             Bytes::from_static(b"value 4@0x10"),
    9306            2 :             Bytes::from_static(b"value 5@0x10"),
    9307            2 :             Bytes::from_static(b"value 6@0x10"),
    9308            2 :             Bytes::from_static(b"value 7@0x10"),
    9309            2 :             Bytes::from_static(b"value 8@0x10"),
    9310            2 :             Bytes::from_static(b"value 9@0x10"),
    9311            2 :         ];
    9312            2 : 
    9313            2 :         let expected_result_at_lsn_20 = [
    9314            2 :             Bytes::from_static(b"value 0@0x10"),
    9315            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9316            2 :             Bytes::from_static(b"value 2@0x10"),
    9317            2 :             Bytes::from_static(b"value 3@0x10"),
    9318            2 :             Bytes::from_static(b"value 4@0x10"),
    9319            2 :             Bytes::from_static(b"value 5@0x10"),
    9320            2 :             Bytes::from_static(b"value 6@0x10"),
    9321            2 :             Bytes::from_static(b"value 7@0x10"),
    9322            2 :             Bytes::from_static(b"value 8@0x10"),
    9323            2 :             Bytes::from_static(b"value 9@0x10"),
    9324            2 :         ];
    9325            2 : 
    9326            2 :         let expected_result_at_lsn_10 = [
    9327            2 :             Bytes::from_static(b"value 0@0x10"),
    9328            2 :             Bytes::from_static(b"value 1@0x10"),
    9329            2 :             Bytes::from_static(b"value 2@0x10"),
    9330            2 :             Bytes::from_static(b"value 3@0x10"),
    9331            2 :             Bytes::from_static(b"value 4@0x10"),
    9332            2 :             Bytes::from_static(b"value 5@0x10"),
    9333            2 :             Bytes::from_static(b"value 6@0x10"),
    9334            2 :             Bytes::from_static(b"value 7@0x10"),
    9335            2 :             Bytes::from_static(b"value 8@0x10"),
    9336            2 :             Bytes::from_static(b"value 9@0x10"),
    9337            2 :         ];
    9338            2 : 
    9339            8 :         let verify_result = || async {
    9340            8 :             let gc_horizon = {
    9341            8 :                 let gc_info = tline.gc_info.read().unwrap();
    9342            8 :                 gc_info.cutoffs.time
    9343            2 :             };
    9344           88 :             for idx in 0..10 {
    9345           80 :                 assert_eq!(
    9346           80 :                     tline
    9347           80 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9348           76 :                         .await
    9349           80 :                         .unwrap(),
    9350           80 :                     &expected_result[idx]
    9351            2 :                 );
    9352           80 :                 assert_eq!(
    9353           80 :                     tline
    9354           80 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9355           46 :                         .await
    9356           80 :                         .unwrap(),
    9357           80 :                     &expected_result_at_gc_horizon[idx]
    9358            2 :                 );
    9359           80 :                 assert_eq!(
    9360           80 :                     tline
    9361           80 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9362           48 :                         .await
    9363           80 :                         .unwrap(),
    9364           80 :                     &expected_result_at_lsn_20[idx]
    9365            2 :                 );
    9366           80 :                 assert_eq!(
    9367           80 :                     tline
    9368           80 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9369           41 :                         .await
    9370           80 :                         .unwrap(),
    9371           80 :                     &expected_result_at_lsn_10[idx]
    9372            2 :                 );
    9373            2 :             }
    9374           16 :         };
    9375            2 : 
    9376           61 :         verify_result().await;
    9377            2 : 
    9378            2 :         let cancel = CancellationToken::new();
    9379            2 :         let mut dryrun_flags = EnumSet::new();
    9380            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9381            2 : 
    9382            2 :         tline
    9383            2 :             .compact_with_gc(
    9384            2 :                 &cancel,
    9385            2 :                 CompactOptions {
    9386            2 :                     flags: dryrun_flags,
    9387            2 :                     compact_range: None,
    9388            2 :                 },
    9389            2 :                 &ctx,
    9390            2 :             )
    9391           49 :             .await
    9392            2 :             .unwrap();
    9393            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
    9394            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9395           49 :         verify_result().await;
    9396            2 : 
    9397            2 :         tline
    9398            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9399           53 :             .await
    9400            2 :             .unwrap();
    9401           54 :         verify_result().await;
    9402            2 : 
    9403            2 :         // compact again
    9404            2 :         tline
    9405            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9406           39 :             .await
    9407            2 :             .unwrap();
    9408           47 :         verify_result().await;
    9409            2 : 
    9410            2 :         Ok(())
    9411            2 :     }
    9412              : 
    9413              :     #[cfg(feature = "testing")]
    9414              :     #[tokio::test]
    9415            2 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9416            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9417           17 :         let (tenant, ctx) = harness.load().await;
    9418            2 : 
    9419          126 :         fn get_key(id: u32) -> Key {
    9420          126 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9421          126 :             key.field6 = id;
    9422          126 :             key
    9423          126 :         }
    9424            2 : 
    9425            2 :         let img_layer = (0..10)
    9426           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9427            2 :             .collect_vec();
    9428            2 : 
    9429            2 :         let delta1 = vec![
    9430            2 :             (
    9431            2 :                 get_key(1),
    9432            2 :                 Lsn(0x20),
    9433            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9434            2 :             ),
    9435            2 :             (
    9436            2 :                 get_key(2),
    9437            2 :                 Lsn(0x30),
    9438            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9439            2 :             ),
    9440            2 :             (
    9441            2 :                 get_key(3),
    9442            2 :                 Lsn(0x28),
    9443            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9444            2 :             ),
    9445            2 :             (
    9446            2 :                 get_key(3),
    9447            2 :                 Lsn(0x30),
    9448            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9449            2 :             ),
    9450            2 :             (
    9451            2 :                 get_key(3),
    9452            2 :                 Lsn(0x40),
    9453            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9454            2 :             ),
    9455            2 :         ];
    9456            2 :         let delta2 = vec![
    9457            2 :             (
    9458            2 :                 get_key(5),
    9459            2 :                 Lsn(0x20),
    9460            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9461            2 :             ),
    9462            2 :             (
    9463            2 :                 get_key(6),
    9464            2 :                 Lsn(0x20),
    9465            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9466            2 :             ),
    9467            2 :         ];
    9468            2 :         let delta3 = vec![
    9469            2 :             (
    9470            2 :                 get_key(8),
    9471            2 :                 Lsn(0x48),
    9472            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9473            2 :             ),
    9474            2 :             (
    9475            2 :                 get_key(9),
    9476            2 :                 Lsn(0x48),
    9477            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9478            2 :             ),
    9479            2 :         ];
    9480            2 : 
    9481            2 :         let parent_tline = tenant
    9482            2 :             .create_test_timeline_with_layers(
    9483            2 :                 TIMELINE_ID,
    9484            2 :                 Lsn(0x10),
    9485            2 :                 DEFAULT_PG_VERSION,
    9486            2 :                 &ctx,
    9487            2 :                 vec![],                       // delta layers
    9488            2 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9489            2 :                 Lsn(0x18),
    9490            2 :             )
    9491           30 :             .await?;
    9492            2 : 
    9493            2 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9494            2 : 
    9495            2 :         let branch_tline = tenant
    9496            2 :             .branch_timeline_test_with_layers(
    9497            2 :                 &parent_tline,
    9498            2 :                 NEW_TIMELINE_ID,
    9499            2 :                 Some(Lsn(0x18)),
    9500            2 :                 &ctx,
    9501            2 :                 vec![
    9502            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9503            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9504            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9505            2 :                 ], // delta layers
    9506            2 :                 vec![], // image layers
    9507            2 :                 Lsn(0x50),
    9508            2 :             )
    9509           19 :             .await?;
    9510            2 : 
    9511            2 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9512            2 : 
    9513            2 :         {
    9514            2 :             // Update GC info
    9515            2 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9516            2 :             *guard = GcInfo {
    9517            2 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9518            2 :                 cutoffs: GcCutoffs {
    9519            2 :                     time: Lsn(0x10),
    9520            2 :                     space: Lsn(0x10),
    9521            2 :                 },
    9522            2 :                 leases: Default::default(),
    9523            2 :                 within_ancestor_pitr: false,
    9524            2 :             };
    9525            2 :         }
    9526            2 : 
    9527            2 :         {
    9528            2 :             // Update GC info
    9529            2 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9530            2 :             *guard = GcInfo {
    9531            2 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9532            2 :                 cutoffs: GcCutoffs {
    9533            2 :                     time: Lsn(0x50),
    9534            2 :                     space: Lsn(0x50),
    9535            2 :                 },
    9536            2 :                 leases: Default::default(),
    9537            2 :                 within_ancestor_pitr: false,
    9538            2 :             };
    9539            2 :         }
    9540            2 : 
    9541            2 :         let expected_result_at_gc_horizon = [
    9542            2 :             Bytes::from_static(b"value 0@0x10"),
    9543            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9544            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9545            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9546            2 :             Bytes::from_static(b"value 4@0x10"),
    9547            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9548            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9549            2 :             Bytes::from_static(b"value 7@0x10"),
    9550            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9551            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9552            2 :         ];
    9553            2 : 
    9554            2 :         let expected_result_at_lsn_40 = [
    9555            2 :             Bytes::from_static(b"value 0@0x10"),
    9556            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9557            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9558            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9559            2 :             Bytes::from_static(b"value 4@0x10"),
    9560            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9561            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9562            2 :             Bytes::from_static(b"value 7@0x10"),
    9563            2 :             Bytes::from_static(b"value 8@0x10"),
    9564            2 :             Bytes::from_static(b"value 9@0x10"),
    9565            2 :         ];
    9566            2 : 
    9567            4 :         let verify_result = || async {
    9568           44 :             for idx in 0..10 {
    9569           40 :                 assert_eq!(
    9570           40 :                     branch_tline
    9571           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9572           50 :                         .await
    9573           40 :                         .unwrap(),
    9574           40 :                     &expected_result_at_gc_horizon[idx]
    9575            2 :                 );
    9576           40 :                 assert_eq!(
    9577           40 :                     branch_tline
    9578           40 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9579           31 :                         .await
    9580           40 :                         .unwrap(),
    9581           40 :                     &expected_result_at_lsn_40[idx]
    9582            2 :                 );
    9583            2 :             }
    9584            8 :         };
    9585            2 : 
    9586           45 :         verify_result().await;
    9587            2 : 
    9588            2 :         let cancel = CancellationToken::new();
    9589            2 :         branch_tline
    9590            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9591           17 :             .await
    9592            2 :             .unwrap();
    9593            2 : 
    9594           36 :         verify_result().await;
    9595            2 : 
    9596            2 :         Ok(())
    9597            2 :     }
    9598              : 
    9599              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9600              :     // Create an image arrangement where we have to read at different LSN ranges
    9601              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9602              :     // a delta layer. Like so:
    9603              :     //
    9604              :     //     A      B
    9605              :     // +----------------+ -> delta_layer
    9606              :     // |                |                           ^ lsn
    9607              :     // |       =========|-> nested_image_layer      |
    9608              :     // |       C        |                           |
    9609              :     // +----------------+                           |
    9610              :     // ======== -> baseline_image_layer             +-------> key
    9611              :     //
    9612              :     //
    9613              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9614              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9615              :     #[cfg(feature = "testing")]
    9616              :     #[tokio::test]
    9617            2 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9618            2 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9619           20 :         let (tenant, ctx) = harness.load().await;
    9620            2 : 
    9621            2 :         let will_init_keys = [2, 6];
    9622           44 :         fn get_key(id: u32) -> Key {
    9623           44 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9624           44 :             key.field6 = id;
    9625           44 :             key
    9626           44 :         }
    9627            2 : 
    9628            2 :         let mut expected_key_values = HashMap::new();
    9629            2 : 
    9630            2 :         let baseline_image_layer_lsn = Lsn(0x10);
    9631            2 :         let mut baseline_img_layer = Vec::new();
    9632           12 :         for i in 0..5 {
    9633           10 :             let key = get_key(i);
    9634           10 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
    9635           10 : 
    9636           10 :             let removed = expected_key_values.insert(key, value.clone());
    9637           10 :             assert!(removed.is_none());
    9638            2 : 
    9639           10 :             baseline_img_layer.push((key, Bytes::from(value)));
    9640            2 :         }
    9641            2 : 
    9642            2 :         let nested_image_layer_lsn = Lsn(0x50);
    9643            2 :         let mut nested_img_layer = Vec::new();
    9644           12 :         for i in 5..10 {
    9645           10 :             let key = get_key(i);
    9646           10 :             let value = format!("value {i}@{nested_image_layer_lsn}");
    9647           10 : 
    9648           10 :             let removed = expected_key_values.insert(key, value.clone());
    9649           10 :             assert!(removed.is_none());
    9650            2 : 
    9651           10 :             nested_img_layer.push((key, Bytes::from(value)));
    9652            2 :         }
    9653            2 : 
    9654            2 :         let mut delta_layer_spec = Vec::default();
    9655            2 :         let delta_layer_start_lsn = Lsn(0x20);
    9656            2 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
    9657            2 : 
    9658           22 :         for i in 0..10 {
    9659           20 :             let key = get_key(i);
    9660           20 :             let key_in_nested = nested_img_layer
    9661           20 :                 .iter()
    9662           80 :                 .any(|(key_with_img, _)| *key_with_img == key);
    9663           20 :             let lsn = {
    9664           20 :                 if key_in_nested {
    9665           10 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
    9666            2 :                 } else {
    9667           10 :                     delta_layer_start_lsn
    9668            2 :                 }
    9669            2 :             };
    9670            2 : 
    9671           20 :             let will_init = will_init_keys.contains(&i);
    9672           20 :             if will_init {
    9673            4 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
    9674            4 : 
    9675            4 :                 expected_key_values.insert(key, "".to_string());
    9676           16 :             } else {
    9677           16 :                 let delta = format!("@{lsn}");
    9678           16 :                 delta_layer_spec.push((
    9679           16 :                     key,
    9680           16 :                     lsn,
    9681           16 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
    9682           16 :                 ));
    9683           16 : 
    9684           16 :                 expected_key_values
    9685           16 :                     .get_mut(&key)
    9686           16 :                     .expect("An image exists for each key")
    9687           16 :                     .push_str(delta.as_str());
    9688           16 :             }
    9689           20 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
    9690            2 :         }
    9691            2 : 
    9692            2 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
    9693            2 : 
    9694            2 :         assert!(
    9695            2 :             nested_image_layer_lsn > delta_layer_start_lsn
    9696            2 :                 && nested_image_layer_lsn < delta_layer_end_lsn
    9697            2 :         );
    9698            2 : 
    9699            2 :         let tline = tenant
    9700            2 :             .create_test_timeline_with_layers(
    9701            2 :                 TIMELINE_ID,
    9702            2 :                 baseline_image_layer_lsn,
    9703            2 :                 DEFAULT_PG_VERSION,
    9704            2 :                 &ctx,
    9705            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9706            2 :                     delta_layer_start_lsn..delta_layer_end_lsn,
    9707            2 :                     delta_layer_spec,
    9708            2 :                 )], // delta layers
    9709            2 :                 vec![
    9710            2 :                     (baseline_image_layer_lsn, baseline_img_layer),
    9711            2 :                     (nested_image_layer_lsn, nested_img_layer),
    9712            2 :                 ], // image layers
    9713            2 :                 delta_layer_end_lsn,
    9714            2 :             )
    9715           42 :             .await?;
    9716            2 : 
    9717            2 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
    9718            2 :         let results = tline
    9719            2 :             .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
    9720           13 :             .await
    9721            2 :             .expect("No vectored errors");
    9722           22 :         for (key, res) in results {
    9723           20 :             let value = res.expect("No key errors");
    9724           20 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
    9725           20 :             assert_eq!(value, Bytes::from(expected_value));
    9726            2 :         }
    9727            2 : 
    9728            2 :         Ok(())
    9729            2 :     }
    9730              : 
    9731          142 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
    9732          142 :         (
    9733          142 :             k1.is_delta,
    9734          142 :             k1.key_range.start,
    9735          142 :             k1.key_range.end,
    9736          142 :             k1.lsn_range.start,
    9737          142 :             k1.lsn_range.end,
    9738          142 :         )
    9739          142 :             .cmp(&(
    9740          142 :                 k2.is_delta,
    9741          142 :                 k2.key_range.start,
    9742          142 :                 k2.key_range.end,
    9743          142 :                 k2.lsn_range.start,
    9744          142 :                 k2.lsn_range.end,
    9745          142 :             ))
    9746          142 :     }
    9747              : 
    9748           12 :     async fn inspect_and_sort(
    9749           12 :         tline: &Arc<Timeline>,
    9750           12 :         filter: Option<std::ops::Range<Key>>,
    9751           12 :     ) -> Vec<PersistentLayerKey> {
    9752           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
    9753           12 :         if let Some(filter) = filter {
    9754           64 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
    9755           10 :         }
    9756           12 :         all_layers.sort_by(sort_layer_key);
    9757           12 :         all_layers
    9758           12 :     }
    9759              : 
    9760              :     #[cfg(feature = "testing")]
    9761           10 :     fn check_layer_map_key_eq(
    9762           10 :         mut left: Vec<PersistentLayerKey>,
    9763           10 :         mut right: Vec<PersistentLayerKey>,
    9764           10 :     ) {
    9765           10 :         left.sort_by(sort_layer_key);
    9766           10 :         right.sort_by(sort_layer_key);
    9767           10 :         if left != right {
    9768            0 :             eprintln!("---LEFT---");
    9769            0 :             for left in left.iter() {
    9770            0 :                 eprintln!("{}", left);
    9771            0 :             }
    9772            0 :             eprintln!("---RIGHT---");
    9773            0 :             for right in right.iter() {
    9774            0 :                 eprintln!("{}", right);
    9775            0 :             }
    9776            0 :             assert_eq!(left, right);
    9777           10 :         }
    9778           10 :     }
    9779              : 
    9780              :     #[cfg(feature = "testing")]
    9781              :     #[tokio::test]
    9782            2 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
    9783            2 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
    9784           20 :         let (tenant, ctx) = harness.load().await;
    9785            2 : 
    9786          182 :         fn get_key(id: u32) -> Key {
    9787          182 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9788          182 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9789          182 :             key.field6 = id;
    9790          182 :             key
    9791          182 :         }
    9792            2 : 
    9793            2 :         // img layer at 0x10
    9794            2 :         let img_layer = (0..10)
    9795           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9796            2 :             .collect_vec();
    9797            2 : 
    9798            2 :         let delta1 = vec![
    9799            2 :             (
    9800            2 :                 get_key(1),
    9801            2 :                 Lsn(0x20),
    9802            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    9803            2 :             ),
    9804            2 :             (
    9805            2 :                 get_key(2),
    9806            2 :                 Lsn(0x30),
    9807            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    9808            2 :             ),
    9809            2 :             (
    9810            2 :                 get_key(3),
    9811            2 :                 Lsn(0x40),
    9812            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    9813            2 :             ),
    9814            2 :         ];
    9815            2 :         let delta2 = vec![
    9816            2 :             (
    9817            2 :                 get_key(5),
    9818            2 :                 Lsn(0x20),
    9819            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    9820            2 :             ),
    9821            2 :             (
    9822            2 :                 get_key(6),
    9823            2 :                 Lsn(0x20),
    9824            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    9825            2 :             ),
    9826            2 :         ];
    9827            2 :         let delta3 = vec![
    9828            2 :             (
    9829            2 :                 get_key(8),
    9830            2 :                 Lsn(0x48),
    9831            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    9832            2 :             ),
    9833            2 :             (
    9834            2 :                 get_key(9),
    9835            2 :                 Lsn(0x48),
    9836            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    9837            2 :             ),
    9838            2 :         ];
    9839            2 : 
    9840            2 :         let tline = tenant
    9841            2 :             .create_test_timeline_with_layers(
    9842            2 :                 TIMELINE_ID,
    9843            2 :                 Lsn(0x10),
    9844            2 :                 DEFAULT_PG_VERSION,
    9845            2 :                 &ctx,
    9846            2 :                 vec![
    9847            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9848            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9849            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9850            2 :                 ], // delta layers
    9851            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9852            2 :                 Lsn(0x50),
    9853            2 :             )
    9854           49 :             .await?;
    9855            2 : 
    9856            2 :         {
    9857            2 :             // Update GC info
    9858            2 :             let mut guard = tline.gc_info.write().unwrap();
    9859            2 :             *guard = GcInfo {
    9860            2 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
    9861            2 :                 cutoffs: GcCutoffs {
    9862            2 :                     time: Lsn(0x30),
    9863            2 :                     space: Lsn(0x30),
    9864            2 :                 },
    9865            2 :                 leases: Default::default(),
    9866            2 :                 within_ancestor_pitr: false,
    9867            2 :             };
    9868            2 :         }
    9869            2 : 
    9870            2 :         let cancel = CancellationToken::new();
    9871            2 : 
    9872            2 :         // Do a partial compaction on key range 0..2
    9873            2 :         tline
    9874            2 :             .partial_compact_with_gc(get_key(0)..get_key(2), &cancel, EnumSet::new(), &ctx)
    9875           25 :             .await
    9876            2 :             .unwrap();
    9877            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9878            2 :         check_layer_map_key_eq(
    9879            2 :             all_layers,
    9880            2 :             vec![
    9881            2 :                 // newly-generated image layer for the partial compaction range 0-2
    9882            2 :                 PersistentLayerKey {
    9883            2 :                     key_range: get_key(0)..get_key(2),
    9884            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9885            2 :                     is_delta: false,
    9886            2 :                 },
    9887            2 :                 PersistentLayerKey {
    9888            2 :                     key_range: get_key(0)..get_key(10),
    9889            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9890            2 :                     is_delta: false,
    9891            2 :                 },
    9892            2 :                 // delta1 is split and the second part is rewritten
    9893            2 :                 PersistentLayerKey {
    9894            2 :                     key_range: get_key(2)..get_key(4),
    9895            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9896            2 :                     is_delta: true,
    9897            2 :                 },
    9898            2 :                 PersistentLayerKey {
    9899            2 :                     key_range: get_key(5)..get_key(7),
    9900            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9901            2 :                     is_delta: true,
    9902            2 :                 },
    9903            2 :                 PersistentLayerKey {
    9904            2 :                     key_range: get_key(8)..get_key(10),
    9905            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9906            2 :                     is_delta: true,
    9907            2 :                 },
    9908            2 :             ],
    9909            2 :         );
    9910            2 : 
    9911            2 :         // Do a partial compaction on key range 2..4
    9912            2 :         tline
    9913            2 :             .partial_compact_with_gc(get_key(2)..get_key(4), &cancel, EnumSet::new(), &ctx)
    9914           15 :             .await
    9915            2 :             .unwrap();
    9916            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9917            2 :         check_layer_map_key_eq(
    9918            2 :             all_layers,
    9919            2 :             vec![
    9920            2 :                 PersistentLayerKey {
    9921            2 :                     key_range: get_key(0)..get_key(2),
    9922            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9923            2 :                     is_delta: false,
    9924            2 :                 },
    9925            2 :                 PersistentLayerKey {
    9926            2 :                     key_range: get_key(0)..get_key(10),
    9927            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9928            2 :                     is_delta: false,
    9929            2 :                 },
    9930            2 :                 // image layer generated for the compaction range 2-4
    9931            2 :                 PersistentLayerKey {
    9932            2 :                     key_range: get_key(2)..get_key(4),
    9933            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9934            2 :                     is_delta: false,
    9935            2 :                 },
    9936            2 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
    9937            2 :                 PersistentLayerKey {
    9938            2 :                     key_range: get_key(2)..get_key(4),
    9939            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9940            2 :                     is_delta: true,
    9941            2 :                 },
    9942            2 :                 PersistentLayerKey {
    9943            2 :                     key_range: get_key(5)..get_key(7),
    9944            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9945            2 :                     is_delta: true,
    9946            2 :                 },
    9947            2 :                 PersistentLayerKey {
    9948            2 :                     key_range: get_key(8)..get_key(10),
    9949            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9950            2 :                     is_delta: true,
    9951            2 :                 },
    9952            2 :             ],
    9953            2 :         );
    9954            2 : 
    9955            2 :         // Do a partial compaction on key range 4..9
    9956            2 :         tline
    9957            2 :             .partial_compact_with_gc(get_key(4)..get_key(9), &cancel, EnumSet::new(), &ctx)
    9958           23 :             .await
    9959            2 :             .unwrap();
    9960            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9961            2 :         check_layer_map_key_eq(
    9962            2 :             all_layers,
    9963            2 :             vec![
    9964            2 :                 PersistentLayerKey {
    9965            2 :                     key_range: get_key(0)..get_key(2),
    9966            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9967            2 :                     is_delta: false,
    9968            2 :                 },
    9969            2 :                 PersistentLayerKey {
    9970            2 :                     key_range: get_key(0)..get_key(10),
    9971            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9972            2 :                     is_delta: false,
    9973            2 :                 },
    9974            2 :                 PersistentLayerKey {
    9975            2 :                     key_range: get_key(2)..get_key(4),
    9976            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9977            2 :                     is_delta: false,
    9978            2 :                 },
    9979            2 :                 PersistentLayerKey {
    9980            2 :                     key_range: get_key(2)..get_key(4),
    9981            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9982            2 :                     is_delta: true,
    9983            2 :                 },
    9984            2 :                 // image layer generated for this compaction range
    9985            2 :                 PersistentLayerKey {
    9986            2 :                     key_range: get_key(4)..get_key(9),
    9987            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9988            2 :                     is_delta: false,
    9989            2 :                 },
    9990            2 :                 PersistentLayerKey {
    9991            2 :                     key_range: get_key(8)..get_key(10),
    9992            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9993            2 :                     is_delta: true,
    9994            2 :                 },
    9995            2 :             ],
    9996            2 :         );
    9997            2 : 
    9998            2 :         // Do a partial compaction on key range 9..10
    9999            2 :         tline
   10000            2 :             .partial_compact_with_gc(get_key(9)..get_key(10), &cancel, EnumSet::new(), &ctx)
   10001            9 :             .await
   10002            2 :             .unwrap();
   10003            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10004            2 :         check_layer_map_key_eq(
   10005            2 :             all_layers,
   10006            2 :             vec![
   10007            2 :                 PersistentLayerKey {
   10008            2 :                     key_range: get_key(0)..get_key(2),
   10009            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10010            2 :                     is_delta: false,
   10011            2 :                 },
   10012            2 :                 PersistentLayerKey {
   10013            2 :                     key_range: get_key(0)..get_key(10),
   10014            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10015            2 :                     is_delta: false,
   10016            2 :                 },
   10017            2 :                 PersistentLayerKey {
   10018            2 :                     key_range: get_key(2)..get_key(4),
   10019            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10020            2 :                     is_delta: false,
   10021            2 :                 },
   10022            2 :                 PersistentLayerKey {
   10023            2 :                     key_range: get_key(2)..get_key(4),
   10024            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10025            2 :                     is_delta: true,
   10026            2 :                 },
   10027            2 :                 PersistentLayerKey {
   10028            2 :                     key_range: get_key(4)..get_key(9),
   10029            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10030            2 :                     is_delta: false,
   10031            2 :                 },
   10032            2 :                 // image layer generated for the compaction range
   10033            2 :                 PersistentLayerKey {
   10034            2 :                     key_range: get_key(9)..get_key(10),
   10035            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10036            2 :                     is_delta: false,
   10037            2 :                 },
   10038            2 :                 PersistentLayerKey {
   10039            2 :                     key_range: get_key(8)..get_key(10),
   10040            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10041            2 :                     is_delta: true,
   10042            2 :                 },
   10043            2 :             ],
   10044            2 :         );
   10045            2 : 
   10046            2 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10047            2 :         tline
   10048            2 :             .partial_compact_with_gc(get_key(0)..get_key(10), &cancel, EnumSet::new(), &ctx)
   10049           48 :             .await
   10050            2 :             .unwrap();
   10051            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10052            2 :         check_layer_map_key_eq(
   10053            2 :             all_layers,
   10054            2 :             vec![
   10055            2 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10056            2 :                 PersistentLayerKey {
   10057            2 :                     key_range: get_key(0)..get_key(10),
   10058            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10059            2 :                     is_delta: false,
   10060            2 :                 },
   10061            2 :                 PersistentLayerKey {
   10062            2 :                     key_range: get_key(2)..get_key(4),
   10063            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10064            2 :                     is_delta: true,
   10065            2 :                 },
   10066            2 :                 PersistentLayerKey {
   10067            2 :                     key_range: get_key(8)..get_key(10),
   10068            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10069            2 :                     is_delta: true,
   10070            2 :                 },
   10071            2 :             ],
   10072            2 :         );
   10073            2 : 
   10074            2 :         Ok(())
   10075            2 :     }
   10076              : 
   10077              :     #[cfg(feature = "testing")]
   10078              :     #[tokio::test]
   10079            2 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10080            2 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10081            2 :             .await
   10082            2 :             .unwrap();
   10083           20 :         let (tenant, ctx) = harness.load().await;
   10084            2 :         let tline_parent = tenant
   10085            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10086            6 :             .await
   10087            2 :             .unwrap();
   10088            2 :         let tline_child = tenant
   10089            2 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10090            2 :             .await
   10091            2 :             .unwrap();
   10092            2 :         {
   10093            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10094            2 :             assert_eq!(
   10095            2 :                 gc_info_parent.retain_lsns,
   10096            2 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10097            2 :             );
   10098            2 :         }
   10099            2 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10100            2 :         tline_child
   10101            2 :             .remote_client
   10102            2 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10103            2 :             .unwrap();
   10104            2 :         tline_child.remote_client.wait_completion().await.unwrap();
   10105            2 :         offload_timeline(&tenant, &tline_child)
   10106            2 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10107           10 :             .await.unwrap();
   10108            2 :         let child_timeline_id = tline_child.timeline_id;
   10109            2 :         Arc::try_unwrap(tline_child).unwrap();
   10110            2 : 
   10111            2 :         {
   10112            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10113            2 :             assert_eq!(
   10114            2 :                 gc_info_parent.retain_lsns,
   10115            2 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10116            2 :             );
   10117            2 :         }
   10118            2 : 
   10119            2 :         tenant
   10120            2 :             .get_offloaded_timeline(child_timeline_id)
   10121            2 :             .unwrap()
   10122            2 :             .defuse_for_tenant_drop();
   10123            2 : 
   10124            2 :         Ok(())
   10125            2 :     }
   10126              : }
        

Generated by: LCOV version 2.1-beta