LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 043b8f570674166113a32da8d85a877835e253a5.info Lines: 75.0 % 7202 5403
Test Date: 2024-11-14 12:23:54 Functions: 56.8 % 421 239

            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::Weak;
      43              : use std::time::SystemTime;
      44              : use storage_broker::BrokerClientChannel;
      45              : use timeline::offload::offload_timeline;
      46              : use tokio::io::BufReader;
      47              : use tokio::sync::watch;
      48              : use tokio::task::JoinSet;
      49              : use tokio_util::sync::CancellationToken;
      50              : use tracing::*;
      51              : use upload_queue::NotInitialized;
      52              : use utils::backoff;
      53              : use utils::circuit_breaker::CircuitBreaker;
      54              : use utils::completion;
      55              : use utils::crashsafe::path_with_suffix_extension;
      56              : use utils::failpoint_support;
      57              : use utils::fs_ext;
      58              : use utils::pausable_failpoint;
      59              : use utils::sync::gate::Gate;
      60              : use utils::sync::gate::GateGuard;
      61              : use utils::timeout::timeout_cancellable;
      62              : use utils::timeout::TimeoutCancellableError;
      63              : use utils::zstd::create_zst_tarball;
      64              : use utils::zstd::extract_zst_tarball;
      65              : 
      66              : use self::config::AttachedLocationConfig;
      67              : use self::config::AttachmentMode;
      68              : use self::config::LocationConf;
      69              : use self::config::TenantConf;
      70              : use self::metadata::TimelineMetadata;
      71              : use self::mgr::GetActiveTenantError;
      72              : use self::mgr::GetTenantError;
      73              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      74              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      75              : use self::timeline::uninit::TimelineCreateGuard;
      76              : use self::timeline::uninit::TimelineExclusionError;
      77              : use self::timeline::uninit::UninitializedTimeline;
      78              : use self::timeline::EvictionTaskTenantState;
      79              : use self::timeline::GcCutoffs;
      80              : use self::timeline::TimelineDeleteProgress;
      81              : use self::timeline::TimelineResources;
      82              : use self::timeline::WaitLsnError;
      83              : use crate::config::PageServerConf;
      84              : use crate::context::{DownloadBehavior, RequestContext};
      85              : use crate::deletion_queue::DeletionQueueClient;
      86              : use crate::deletion_queue::DeletionQueueError;
      87              : use crate::import_datadir;
      88              : use crate::is_uninit_mark;
      89              : use crate::l0_flush::L0FlushGlobalState;
      90              : use crate::metrics::TENANT;
      91              : use crate::metrics::{
      92              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
      93              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
      94              : };
      95              : use crate::task_mgr;
      96              : use crate::task_mgr::TaskKind;
      97              : use crate::tenant::config::LocationMode;
      98              : use crate::tenant::config::TenantConfOpt;
      99              : use crate::tenant::gc_result::GcResult;
     100              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     101              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     102              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     103              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     104              : use crate::tenant::storage_layer::DeltaLayer;
     105              : use crate::tenant::storage_layer::ImageLayer;
     106              : use crate::walingest::WalLagCooldown;
     107              : use crate::walredo;
     108              : use crate::InitializationOrder;
     109              : use std::collections::hash_map::Entry;
     110              : use std::collections::HashMap;
     111              : use std::collections::HashSet;
     112              : use std::fmt::Debug;
     113              : use std::fmt::Display;
     114              : use std::fs;
     115              : use std::fs::File;
     116              : use std::sync::atomic::{AtomicU64, Ordering};
     117              : use std::sync::Arc;
     118              : use std::sync::Mutex;
     119              : use std::time::{Duration, Instant};
     120              : 
     121              : use crate::span;
     122              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     123              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     124              : use crate::virtual_file::VirtualFile;
     125              : use crate::walredo::PostgresRedoManager;
     126              : use crate::TEMP_FILE_SUFFIX;
     127              : use once_cell::sync::Lazy;
     128              : pub use pageserver_api::models::TenantState;
     129              : use tokio::sync::Semaphore;
     130              : 
     131            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     132              : use utils::{
     133              :     crashsafe,
     134              :     generation::Generation,
     135              :     id::TimelineId,
     136              :     lsn::{Lsn, RecordLsn},
     137              : };
     138              : 
     139              : pub mod blob_io;
     140              : pub mod block_io;
     141              : pub mod vectored_blob_io;
     142              : 
     143              : pub mod disk_btree;
     144              : pub(crate) mod ephemeral_file;
     145              : pub mod layer_map;
     146              : 
     147              : pub mod metadata;
     148              : pub mod remote_timeline_client;
     149              : pub mod storage_layer;
     150              : 
     151              : pub mod checks;
     152              : pub mod config;
     153              : pub mod mgr;
     154              : pub mod secondary;
     155              : pub mod tasks;
     156              : pub mod upload_queue;
     157              : 
     158              : pub(crate) mod timeline;
     159              : 
     160              : pub mod size;
     161              : 
     162              : mod gc_block;
     163              : mod gc_result;
     164              : pub(crate) mod throttle;
     165              : 
     166              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     167              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     168              : 
     169              : // re-export for use in walreceiver
     170              : pub use crate::tenant::timeline::WalReceiverInfo;
     171              : 
     172              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     173              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     174              : 
     175              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     176              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     177              : 
     178              : /// References to shared objects that are passed into each tenant, such
     179              : /// as the shared remote storage client and process initialization state.
     180              : #[derive(Clone)]
     181              : pub struct TenantSharedResources {
     182              :     pub broker_client: storage_broker::BrokerClientChannel,
     183              :     pub remote_storage: GenericRemoteStorage,
     184              :     pub deletion_queue_client: DeletionQueueClient,
     185              :     pub l0_flush_global_state: L0FlushGlobalState,
     186              : }
     187              : 
     188              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     189              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     190              : /// in this struct.
     191              : pub(super) struct AttachedTenantConf {
     192              :     tenant_conf: TenantConfOpt,
     193              :     location: AttachedLocationConfig,
     194              :     /// The deadline before which we are blocked from GC so that
     195              :     /// leases have a chance to be renewed.
     196              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     197              : }
     198              : 
     199              : impl AttachedTenantConf {
     200          190 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     201              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     202              :         //
     203              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     204              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     205              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     206          190 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     207          190 :             Some(
     208          190 :                 tokio::time::Instant::now()
     209          190 :                     + tenant_conf
     210          190 :                         .lsn_lease_length
     211          190 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     212          190 :             )
     213              :         } else {
     214              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     215              :             // because we don't do GC in these modes.
     216            0 :             None
     217              :         };
     218              : 
     219          190 :         Self {
     220          190 :             tenant_conf,
     221          190 :             location,
     222          190 :             lsn_lease_deadline,
     223          190 :         }
     224          190 :     }
     225              : 
     226          190 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     227          190 :         match &location_conf.mode {
     228          190 :             LocationMode::Attached(attach_conf) => {
     229          190 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     230              :             }
     231              :             LocationMode::Secondary(_) => {
     232            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     233              :             }
     234              :         }
     235          190 :     }
     236              : 
     237          762 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     238          762 :         self.lsn_lease_deadline
     239          762 :             .map(|d| tokio::time::Instant::now() < d)
     240          762 :             .unwrap_or(false)
     241          762 :     }
     242              : }
     243              : struct TimelinePreload {
     244              :     timeline_id: TimelineId,
     245              :     client: RemoteTimelineClient,
     246              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     247              : }
     248              : 
     249              : pub(crate) struct TenantPreload {
     250              :     tenant_manifest: TenantManifest,
     251              :     timelines: HashMap<TimelineId, TimelinePreload>,
     252              : }
     253              : 
     254              : /// When we spawn a tenant, there is a special mode for tenant creation that
     255              : /// avoids trying to read anything from remote storage.
     256              : pub(crate) enum SpawnMode {
     257              :     /// Activate as soon as possible
     258              :     Eager,
     259              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     260              :     Lazy,
     261              : }
     262              : 
     263              : ///
     264              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     265              : ///
     266              : pub struct Tenant {
     267              :     // Global pageserver config parameters
     268              :     pub conf: &'static PageServerConf,
     269              : 
     270              :     /// The value creation timestamp, used to measure activation delay, see:
     271              :     /// <https://github.com/neondatabase/neon/issues/4025>
     272              :     constructed_at: Instant,
     273              : 
     274              :     state: watch::Sender<TenantState>,
     275              : 
     276              :     // Overridden tenant-specific config parameters.
     277              :     // We keep TenantConfOpt sturct here to preserve the information
     278              :     // about parameters that are not set.
     279              :     // This is necessary to allow global config updates.
     280              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     281              : 
     282              :     tenant_shard_id: TenantShardId,
     283              : 
     284              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     285              :     shard_identity: ShardIdentity,
     286              : 
     287              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     288              :     /// Does not change over the lifetime of the [`Tenant`] object.
     289              :     ///
     290              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     291              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     292              :     generation: Generation,
     293              : 
     294              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     295              : 
     296              :     /// During timeline creation, we first insert the TimelineId to the
     297              :     /// creating map, then `timelines`, then remove it from the creating map.
     298              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     299              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     300              : 
     301              :     /// Possibly offloaded and archived timelines
     302              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     303              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     304              : 
     305              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     306              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     307              :     /// each other (this could be optimized to coalesce writes if necessary).
     308              :     ///
     309              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     310              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     311              : 
     312              :     // This mutex prevents creation of new timelines during GC.
     313              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     314              :     // `timelines` mutex during all GC iteration
     315              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     316              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     317              :     // timeout...
     318              :     gc_cs: tokio::sync::Mutex<()>,
     319              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     320              : 
     321              :     // provides access to timeline data sitting in the remote storage
     322              :     pub(crate) remote_storage: GenericRemoteStorage,
     323              : 
     324              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     325              :     deletion_queue_client: DeletionQueueClient,
     326              : 
     327              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     328              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     329              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     330              : 
     331              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     332              : 
     333              :     /// Track repeated failures to compact, so that we can back off.
     334              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     335              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     336              : 
     337              :     /// If the tenant is in Activating state, notify this to encourage it
     338              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     339              :     /// background warmup.
     340              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     341              : 
     342              :     /// Time it took for the tenant to activate. Zero if not active yet.
     343              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     344              : 
     345              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     346              :     // Timelines' cancellation token.
     347              :     pub(crate) cancel: CancellationToken,
     348              : 
     349              :     // Users of the Tenant such as the page service must take this Gate to avoid
     350              :     // trying to use a Tenant which is shutting down.
     351              :     pub(crate) gate: Gate,
     352              : 
     353              :     /// Throttle applied at the top of [`Timeline::get`].
     354              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     355              :     pub(crate) timeline_get_throttle:
     356              :         Arc<throttle::Throttle<crate::metrics::tenant_throttling::TimelineGet>>,
     357              : 
     358              :     /// An ongoing timeline detach concurrency limiter.
     359              :     ///
     360              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     361              :     /// to have two running at the same time. A different one can be started if an earlier one
     362              :     /// has failed for whatever reason.
     363              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     364              : 
     365              :     /// `index_part.json` based gc blocking reason tracking.
     366              :     ///
     367              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     368              :     /// proceeding.
     369              :     pub(crate) gc_block: gc_block::GcBlock,
     370              : 
     371              :     l0_flush_global_state: L0FlushGlobalState,
     372              : }
     373              : 
     374              : impl std::fmt::Debug for Tenant {
     375            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     376            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     377            0 :     }
     378              : }
     379              : 
     380              : pub(crate) enum WalRedoManager {
     381              :     Prod(WalredoManagerId, PostgresRedoManager),
     382              :     #[cfg(test)]
     383              :     Test(harness::TestRedoManager),
     384              : }
     385              : 
     386            0 : #[derive(thiserror::Error, Debug)]
     387              : #[error("pageserver is shutting down")]
     388              : pub(crate) struct GlobalShutDown;
     389              : 
     390              : impl WalRedoManager {
     391            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     392            0 :         let id = WalredoManagerId::next();
     393            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     394            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     395            0 :         match &mut *guard {
     396            0 :             Some(map) => {
     397            0 :                 map.insert(id, Arc::downgrade(&arc));
     398            0 :                 Ok(arc)
     399              :             }
     400            0 :             None => Err(GlobalShutDown),
     401              :         }
     402            0 :     }
     403              : }
     404              : 
     405              : impl Drop for WalRedoManager {
     406           10 :     fn drop(&mut self) {
     407           10 :         match self {
     408            0 :             Self::Prod(id, _) => {
     409            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     410            0 :                 if let Some(map) = &mut *guard {
     411            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     412            0 :                 }
     413              :             }
     414              :             #[cfg(test)]
     415           10 :             Self::Test(_) => {
     416           10 :                 // Not applicable to test redo manager
     417           10 :             }
     418              :         }
     419           10 :     }
     420              : }
     421              : 
     422              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     423              : /// the walredo processes outside of the regular order.
     424              : ///
     425              : /// This is necessary to work around a systemd bug where it freezes if there are
     426              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     427              : #[allow(clippy::type_complexity)]
     428              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     429              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     430            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     431              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     432              : pub(crate) struct WalredoManagerId(u64);
     433              : impl WalredoManagerId {
     434            0 :     pub fn next() -> Self {
     435              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     436            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     437            0 :         if id == 0 {
     438            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     439            0 :         }
     440            0 :         Self(id)
     441            0 :     }
     442              : }
     443              : 
     444              : #[cfg(test)]
     445              : impl From<harness::TestRedoManager> for WalRedoManager {
     446          190 :     fn from(mgr: harness::TestRedoManager) -> Self {
     447          190 :         Self::Test(mgr)
     448          190 :     }
     449              : }
     450              : 
     451              : impl WalRedoManager {
     452            6 :     pub(crate) async fn shutdown(&self) -> bool {
     453            6 :         match self {
     454            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     455              :             #[cfg(test)]
     456              :             Self::Test(_) => {
     457              :                 // Not applicable to test redo manager
     458            6 :                 true
     459              :             }
     460              :         }
     461            6 :     }
     462              : 
     463            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     464            0 :         match self {
     465            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     466            0 :             #[cfg(test)]
     467            0 :             Self::Test(_) => {
     468            0 :                 // Not applicable to test redo manager
     469            0 :             }
     470            0 :         }
     471            0 :     }
     472              : 
     473              :     /// # Cancel-Safety
     474              :     ///
     475              :     /// This method is cancellation-safe.
     476          410 :     pub async fn request_redo(
     477          410 :         &self,
     478          410 :         key: pageserver_api::key::Key,
     479          410 :         lsn: Lsn,
     480          410 :         base_img: Option<(Lsn, bytes::Bytes)>,
     481          410 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     482          410 :         pg_version: u32,
     483          410 :     ) -> Result<bytes::Bytes, walredo::Error> {
     484          410 :         match self {
     485            0 :             Self::Prod(_, mgr) => {
     486            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     487            0 :                     .await
     488              :             }
     489              :             #[cfg(test)]
     490          410 :             Self::Test(mgr) => {
     491          410 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     492            0 :                     .await
     493              :             }
     494              :         }
     495          410 :     }
     496              : 
     497            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     498            0 :         match self {
     499            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     500            0 :             #[cfg(test)]
     501            0 :             WalRedoManager::Test(_) => None,
     502            0 :         }
     503            0 :     }
     504              : }
     505              : 
     506              : /// A very lightweight memory representation of an offloaded timeline.
     507              : ///
     508              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     509              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     510              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     511              : /// more offloaded timelines than we can manage ones that aren't.
     512              : pub struct OffloadedTimeline {
     513              :     pub tenant_shard_id: TenantShardId,
     514              :     pub timeline_id: TimelineId,
     515              :     pub ancestor_timeline_id: Option<TimelineId>,
     516              :     /// Whether to retain the branch lsn at the ancestor or not
     517              :     pub ancestor_retain_lsn: Option<Lsn>,
     518              : 
     519              :     /// When the timeline was archived.
     520              :     ///
     521              :     /// Present for future flattening deliberations.
     522              :     pub archived_at: NaiveDateTime,
     523              : 
     524              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     525              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     526              :     pub delete_progress: TimelineDeleteProgress,
     527              : }
     528              : 
     529              : impl OffloadedTimeline {
     530              :     /// Obtains an offloaded timeline from a given timeline object.
     531              :     ///
     532              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     533              :     /// the timeline is not in a stopped state.
     534              :     /// Panics if the timeline is not archived.
     535            0 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     536            0 :         let ancestor_retain_lsn = timeline
     537            0 :             .get_ancestor_timeline_id()
     538            0 :             .map(|_timeline_id| timeline.get_ancestor_lsn());
     539            0 :         let archived_at = timeline
     540            0 :             .remote_client
     541            0 :             .archived_at_stopped_queue()?
     542            0 :             .expect("must be called on an archived timeline");
     543            0 :         Ok(Self {
     544            0 :             tenant_shard_id: timeline.tenant_shard_id,
     545            0 :             timeline_id: timeline.timeline_id,
     546            0 :             ancestor_timeline_id: timeline.get_ancestor_timeline_id(),
     547            0 :             ancestor_retain_lsn,
     548            0 :             archived_at,
     549            0 : 
     550            0 :             delete_progress: timeline.delete_progress.clone(),
     551            0 :         })
     552            0 :     }
     553            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     554            0 :         let OffloadedTimelineManifest {
     555            0 :             timeline_id,
     556            0 :             ancestor_timeline_id,
     557            0 :             ancestor_retain_lsn,
     558            0 :             archived_at,
     559            0 :         } = *manifest;
     560            0 :         Self {
     561            0 :             tenant_shard_id,
     562            0 :             timeline_id,
     563            0 :             ancestor_timeline_id,
     564            0 :             ancestor_retain_lsn,
     565            0 :             archived_at,
     566            0 :             delete_progress: TimelineDeleteProgress::default(),
     567            0 :         }
     568            0 :     }
     569            0 :     fn manifest(&self) -> OffloadedTimelineManifest {
     570            0 :         let Self {
     571            0 :             timeline_id,
     572            0 :             ancestor_timeline_id,
     573            0 :             ancestor_retain_lsn,
     574            0 :             archived_at,
     575            0 :             ..
     576            0 :         } = self;
     577            0 :         OffloadedTimelineManifest {
     578            0 :             timeline_id: *timeline_id,
     579            0 :             ancestor_timeline_id: *ancestor_timeline_id,
     580            0 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     581            0 :             archived_at: *archived_at,
     582            0 :         }
     583            0 :     }
     584              : }
     585              : 
     586              : impl fmt::Debug for OffloadedTimeline {
     587            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     588            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     589            0 :     }
     590              : }
     591              : 
     592              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     593              : pub enum MaybeOffloaded {
     594              :     Yes,
     595              :     No,
     596              : }
     597              : 
     598              : #[derive(Clone, Debug)]
     599              : pub enum TimelineOrOffloaded {
     600              :     Timeline(Arc<Timeline>),
     601              :     Offloaded(Arc<OffloadedTimeline>),
     602              : }
     603              : 
     604              : impl TimelineOrOffloaded {
     605            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     606            0 :         match self {
     607            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     608            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     609              :             }
     610            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     611            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     612              :             }
     613              :         }
     614            0 :     }
     615            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     616            0 :         self.arc_ref().tenant_shard_id()
     617            0 :     }
     618            0 :     pub fn timeline_id(&self) -> TimelineId {
     619            0 :         self.arc_ref().timeline_id()
     620            0 :     }
     621            0 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     622            0 :         match self {
     623            0 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     624            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     625              :         }
     626            0 :     }
     627            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     628            0 :         match self {
     629            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     630            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     631              :         }
     632            0 :     }
     633              : }
     634              : 
     635              : pub enum TimelineOrOffloadedArcRef<'a> {
     636              :     Timeline(&'a Arc<Timeline>),
     637              :     Offloaded(&'a Arc<OffloadedTimeline>),
     638              : }
     639              : 
     640              : impl TimelineOrOffloadedArcRef<'_> {
     641            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     642            0 :         match self {
     643            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     644            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     645              :         }
     646            0 :     }
     647            0 :     pub fn timeline_id(&self) -> TimelineId {
     648            0 :         match self {
     649            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     650            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     651              :         }
     652            0 :     }
     653              : }
     654              : 
     655              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     656            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     657            0 :         Self::Timeline(timeline)
     658            0 :     }
     659              : }
     660              : 
     661              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     662            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     663            0 :         Self::Offloaded(timeline)
     664            0 :     }
     665              : }
     666              : 
     667            0 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     668              : pub enum GetTimelineError {
     669              :     #[error("Timeline is shutting down")]
     670              :     ShuttingDown,
     671              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     672              :     NotActive {
     673              :         tenant_id: TenantShardId,
     674              :         timeline_id: TimelineId,
     675              :         state: TimelineState,
     676              :     },
     677              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     678              :     NotFound {
     679              :         tenant_id: TenantShardId,
     680              :         timeline_id: TimelineId,
     681              :     },
     682              : }
     683              : 
     684            0 : #[derive(Debug, thiserror::Error)]
     685              : pub enum LoadLocalTimelineError {
     686              :     #[error("FailedToLoad")]
     687              :     Load(#[source] anyhow::Error),
     688              :     #[error("FailedToResumeDeletion")]
     689              :     ResumeDeletion(#[source] anyhow::Error),
     690              : }
     691              : 
     692            0 : #[derive(thiserror::Error)]
     693              : pub enum DeleteTimelineError {
     694              :     #[error("NotFound")]
     695              :     NotFound,
     696              : 
     697              :     #[error("HasChildren")]
     698              :     HasChildren(Vec<TimelineId>),
     699              : 
     700              :     #[error("Timeline deletion is already in progress")]
     701              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     702              : 
     703              :     #[error(transparent)]
     704              :     Other(#[from] anyhow::Error),
     705              : }
     706              : 
     707              : impl Debug for DeleteTimelineError {
     708            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     709            0 :         match self {
     710            0 :             Self::NotFound => write!(f, "NotFound"),
     711            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     712            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     713            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     714              :         }
     715            0 :     }
     716              : }
     717              : 
     718            0 : #[derive(thiserror::Error)]
     719              : pub enum TimelineArchivalError {
     720              :     #[error("NotFound")]
     721              :     NotFound,
     722              : 
     723              :     #[error("Timeout")]
     724              :     Timeout,
     725              : 
     726              :     #[error("Cancelled")]
     727              :     Cancelled,
     728              : 
     729              :     #[error("ancestor is archived: {}", .0)]
     730              :     HasArchivedParent(TimelineId),
     731              : 
     732              :     #[error("HasUnarchivedChildren")]
     733              :     HasUnarchivedChildren(Vec<TimelineId>),
     734              : 
     735              :     #[error("Timeline archival is already in progress")]
     736              :     AlreadyInProgress,
     737              : 
     738              :     #[error(transparent)]
     739              :     Other(anyhow::Error),
     740              : }
     741              : 
     742            0 : #[derive(thiserror::Error, Debug)]
     743              : pub(crate) enum TenantManifestError {
     744              :     #[error("Remote storage error: {0}")]
     745              :     RemoteStorage(anyhow::Error),
     746              : 
     747              :     #[error("Cancelled")]
     748              :     Cancelled,
     749              : }
     750              : 
     751              : impl From<TenantManifestError> for TimelineArchivalError {
     752            0 :     fn from(e: TenantManifestError) -> Self {
     753            0 :         match e {
     754            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     755            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     756              :         }
     757            0 :     }
     758              : }
     759              : 
     760              : impl Debug for TimelineArchivalError {
     761            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     762            0 :         match self {
     763            0 :             Self::NotFound => write!(f, "NotFound"),
     764            0 :             Self::Timeout => write!(f, "Timeout"),
     765            0 :             Self::Cancelled => write!(f, "Cancelled"),
     766            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     767            0 :             Self::HasUnarchivedChildren(c) => {
     768            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     769              :             }
     770            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     771            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     772              :         }
     773            0 :     }
     774              : }
     775              : 
     776              : pub enum SetStoppingError {
     777              :     AlreadyStopping(completion::Barrier),
     778              :     Broken,
     779              : }
     780              : 
     781              : impl Debug for SetStoppingError {
     782            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     783            0 :         match self {
     784            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     785            0 :             Self::Broken => write!(f, "Broken"),
     786              :         }
     787            0 :     }
     788              : }
     789              : 
     790              : /// Arguments to [`Tenant::create_timeline`].
     791              : ///
     792              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     793              : /// is `None`, the result of the timeline create call is not deterministic.
     794              : ///
     795              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     796              : #[derive(Debug)]
     797              : pub(crate) enum CreateTimelineParams {
     798              :     Bootstrap(CreateTimelineParamsBootstrap),
     799              :     Branch(CreateTimelineParamsBranch),
     800              : }
     801              : 
     802              : #[derive(Debug)]
     803              : pub(crate) struct CreateTimelineParamsBootstrap {
     804              :     pub(crate) new_timeline_id: TimelineId,
     805              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     806              :     pub(crate) pg_version: u32,
     807              : }
     808              : 
     809              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     810              : #[derive(Debug)]
     811              : pub(crate) struct CreateTimelineParamsBranch {
     812              :     pub(crate) new_timeline_id: TimelineId,
     813              :     pub(crate) ancestor_timeline_id: TimelineId,
     814              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     815              : }
     816              : 
     817              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`].
     818              : ///
     819              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     820              : ///
     821              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     822              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     823              : ///
     824              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     825              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     826              : ///
     827              : /// Notes:
     828              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     829              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     830              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     831              : ///
     832              : #[derive(Debug, Clone, PartialEq, Eq)]
     833              : pub(crate) enum CreateTimelineIdempotency {
     834              :     /// NB: special treatment, see comment in [`Self`].
     835              :     FailWithConflict,
     836              :     Bootstrap {
     837              :         pg_version: u32,
     838              :     },
     839              :     /// NB: branches always have the same `pg_version` as their ancestor.
     840              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     841              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     842              :     /// determining the child branch pg_version.
     843              :     Branch {
     844              :         ancestor_timeline_id: TimelineId,
     845              :         ancestor_start_lsn: Lsn,
     846              :     },
     847              : }
     848              : 
     849              : /// What is returned by [`Tenant::start_creating_timeline`].
     850              : #[must_use]
     851              : enum StartCreatingTimelineResult<'t> {
     852              :     CreateGuard(TimelineCreateGuard<'t>),
     853              :     Idempotent(Arc<Timeline>),
     854              : }
     855              : 
     856              : /// What is returned by [`Tenant::create_timeline`].
     857              : enum CreateTimelineResult {
     858              :     Created(Arc<Timeline>),
     859              :     Idempotent(Arc<Timeline>),
     860              : }
     861              : 
     862              : impl CreateTimelineResult {
     863            0 :     fn discriminant(&self) -> &'static str {
     864            0 :         match self {
     865            0 :             Self::Created(_) => "Created",
     866            0 :             Self::Idempotent(_) => "Idempotent",
     867              :         }
     868            0 :     }
     869            0 :     fn timeline(&self) -> &Arc<Timeline> {
     870            0 :         match self {
     871            0 :             Self::Created(t) | Self::Idempotent(t) => t,
     872            0 :         }
     873            0 :     }
     874              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     875              :     #[cfg(test)]
     876          228 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     877          228 :         match self {
     878          228 :             Self::Created(t) | Self::Idempotent(t) => t,
     879          228 :         }
     880          228 :     }
     881              : }
     882              : 
     883            2 : #[derive(thiserror::Error, Debug)]
     884              : pub enum CreateTimelineError {
     885              :     #[error("creation of timeline with the given ID is in progress")]
     886              :     AlreadyCreating,
     887              :     #[error("timeline already exists with different parameters")]
     888              :     Conflict,
     889              :     #[error(transparent)]
     890              :     AncestorLsn(anyhow::Error),
     891              :     #[error("ancestor timeline is not active")]
     892              :     AncestorNotActive,
     893              :     #[error("ancestor timeline is archived")]
     894              :     AncestorArchived,
     895              :     #[error("tenant shutting down")]
     896              :     ShuttingDown,
     897              :     #[error(transparent)]
     898              :     Other(#[from] anyhow::Error),
     899              : }
     900              : 
     901              : #[derive(thiserror::Error, Debug)]
     902              : enum InitdbError {
     903              :     Other(anyhow::Error),
     904              :     Cancelled,
     905              :     Spawn(std::io::Result<()>),
     906              :     Failed(std::process::ExitStatus, Vec<u8>),
     907              : }
     908              : 
     909              : impl fmt::Display for InitdbError {
     910            0 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     911            0 :         match self {
     912            0 :             InitdbError::Cancelled => write!(f, "Operation was cancelled"),
     913            0 :             InitdbError::Spawn(e) => write!(f, "Spawn error: {:?}", e),
     914            0 :             InitdbError::Failed(status, stderr) => write!(
     915            0 :                 f,
     916            0 :                 "Command failed with status {:?}: {}",
     917            0 :                 status,
     918            0 :                 String::from_utf8_lossy(stderr)
     919            0 :             ),
     920            0 :             InitdbError::Other(e) => write!(f, "Error: {:?}", e),
     921              :         }
     922            0 :     }
     923              : }
     924              : 
     925              : impl From<std::io::Error> for InitdbError {
     926            0 :     fn from(error: std::io::Error) -> Self {
     927            0 :         InitdbError::Spawn(Err(error))
     928            0 :     }
     929              : }
     930              : 
     931              : enum CreateTimelineCause {
     932              :     Load,
     933              :     Delete,
     934              : }
     935              : 
     936            0 : #[derive(thiserror::Error, Debug)]
     937              : pub(crate) enum GcError {
     938              :     // The tenant is shutting down
     939              :     #[error("tenant shutting down")]
     940              :     TenantCancelled,
     941              : 
     942              :     // The tenant is shutting down
     943              :     #[error("timeline shutting down")]
     944              :     TimelineCancelled,
     945              : 
     946              :     // The tenant is in a state inelegible to run GC
     947              :     #[error("not active")]
     948              :     NotActive,
     949              : 
     950              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
     951              :     #[error("not active")]
     952              :     BadLsn { why: String },
     953              : 
     954              :     // A remote storage error while scheduling updates after compaction
     955              :     #[error(transparent)]
     956              :     Remote(anyhow::Error),
     957              : 
     958              :     // An error reading while calculating GC cutoffs
     959              :     #[error(transparent)]
     960              :     GcCutoffs(PageReconstructError),
     961              : 
     962              :     // If GC was invoked for a particular timeline, this error means it didn't exist
     963              :     #[error("timeline not found")]
     964              :     TimelineNotFound,
     965              : }
     966              : 
     967              : impl From<PageReconstructError> for GcError {
     968            0 :     fn from(value: PageReconstructError) -> Self {
     969            0 :         match value {
     970            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
     971            0 :             other => Self::GcCutoffs(other),
     972              :         }
     973            0 :     }
     974              : }
     975              : 
     976              : impl From<NotInitialized> for GcError {
     977            0 :     fn from(value: NotInitialized) -> Self {
     978            0 :         match value {
     979            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
     980            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
     981              :         }
     982            0 :     }
     983              : }
     984              : 
     985              : impl From<timeline::layer_manager::Shutdown> for GcError {
     986            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
     987            0 :         GcError::TimelineCancelled
     988            0 :     }
     989              : }
     990              : 
     991            0 : #[derive(thiserror::Error, Debug)]
     992              : pub(crate) enum LoadConfigError {
     993              :     #[error("TOML deserialization error: '{0}'")]
     994              :     DeserializeToml(#[from] toml_edit::de::Error),
     995              : 
     996              :     #[error("Config not found at {0}")]
     997              :     NotFound(Utf8PathBuf),
     998              : }
     999              : 
    1000              : impl Tenant {
    1001              :     /// Yet another helper for timeline initialization.
    1002              :     ///
    1003              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1004              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1005              :     /// - Downloads remote index file and adds remote files to the layer map
    1006              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1007              :     ///
    1008              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1009              :     /// it is marked as Active.
    1010              :     #[allow(clippy::too_many_arguments)]
    1011            6 :     async fn timeline_init_and_sync(
    1012            6 :         &self,
    1013            6 :         timeline_id: TimelineId,
    1014            6 :         resources: TimelineResources,
    1015            6 :         index_part: IndexPart,
    1016            6 :         metadata: TimelineMetadata,
    1017            6 :         ancestor: Option<Arc<Timeline>>,
    1018            6 :         _ctx: &RequestContext,
    1019            6 :     ) -> anyhow::Result<()> {
    1020            6 :         let tenant_id = self.tenant_shard_id;
    1021              : 
    1022            6 :         let idempotency = if metadata.ancestor_timeline().is_none() {
    1023            4 :             CreateTimelineIdempotency::Bootstrap {
    1024            4 :                 pg_version: metadata.pg_version(),
    1025            4 :             }
    1026              :         } else {
    1027            2 :             CreateTimelineIdempotency::Branch {
    1028            2 :                 ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1029            2 :                 ancestor_start_lsn: metadata.ancestor_lsn(),
    1030            2 :             }
    1031              :         };
    1032              : 
    1033            6 :         let timeline = self.create_timeline_struct(
    1034            6 :             timeline_id,
    1035            6 :             &metadata,
    1036            6 :             ancestor.clone(),
    1037            6 :             resources,
    1038            6 :             CreateTimelineCause::Load,
    1039            6 :             idempotency.clone(),
    1040            6 :         )?;
    1041            6 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1042            6 :         anyhow::ensure!(
    1043            6 :             disk_consistent_lsn.is_valid(),
    1044            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1045              :         );
    1046            6 :         assert_eq!(
    1047            6 :             disk_consistent_lsn,
    1048            6 :             metadata.disk_consistent_lsn(),
    1049            0 :             "these are used interchangeably"
    1050              :         );
    1051              : 
    1052            6 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1053              : 
    1054            6 :         timeline
    1055            6 :             .load_layer_map(disk_consistent_lsn, index_part)
    1056            0 :             .await
    1057            6 :             .with_context(|| {
    1058            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1059            6 :             })?;
    1060              : 
    1061              :         {
    1062              :             // avoiding holding it across awaits
    1063            6 :             let mut timelines_accessor = self.timelines.lock().unwrap();
    1064            6 :             match timelines_accessor.entry(timeline_id) {
    1065              :                 // We should never try and load the same timeline twice during startup
    1066              :                 Entry::Occupied(_) => {
    1067            0 :                     unreachable!(
    1068            0 :                         "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1069            0 :                     );
    1070              :                 }
    1071            6 :                 Entry::Vacant(v) => {
    1072            6 :                     v.insert(Arc::clone(&timeline));
    1073            6 :                     timeline.maybe_spawn_flush_loop();
    1074            6 :                 }
    1075            6 :             }
    1076            6 :         };
    1077            6 : 
    1078            6 :         // Sanity check: a timeline should have some content.
    1079            6 :         anyhow::ensure!(
    1080            6 :             ancestor.is_some()
    1081            4 :                 || timeline
    1082            4 :                     .layers
    1083            4 :                     .read()
    1084            0 :                     .await
    1085            4 :                     .layer_map()
    1086            4 :                     .expect("currently loading, layer manager cannot be shutdown already")
    1087            4 :                     .iter_historic_layers()
    1088            4 :                     .next()
    1089            4 :                     .is_some(),
    1090            0 :             "Timeline has no ancestor and no layer files"
    1091              :         );
    1092              : 
    1093            6 :         Ok(())
    1094            6 :     }
    1095              : 
    1096              :     /// Attach a tenant that's available in cloud storage.
    1097              :     ///
    1098              :     /// This returns quickly, after just creating the in-memory object
    1099              :     /// Tenant struct and launching a background task to download
    1100              :     /// the remote index files.  On return, the tenant is most likely still in
    1101              :     /// Attaching state, and it will become Active once the background task
    1102              :     /// finishes. You can use wait_until_active() to wait for the task to
    1103              :     /// complete.
    1104              :     ///
    1105              :     #[allow(clippy::too_many_arguments)]
    1106            0 :     pub(crate) fn spawn(
    1107            0 :         conf: &'static PageServerConf,
    1108            0 :         tenant_shard_id: TenantShardId,
    1109            0 :         resources: TenantSharedResources,
    1110            0 :         attached_conf: AttachedTenantConf,
    1111            0 :         shard_identity: ShardIdentity,
    1112            0 :         init_order: Option<InitializationOrder>,
    1113            0 :         mode: SpawnMode,
    1114            0 :         ctx: &RequestContext,
    1115            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1116            0 :         let wal_redo_manager =
    1117            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1118              : 
    1119              :         let TenantSharedResources {
    1120            0 :             broker_client,
    1121            0 :             remote_storage,
    1122            0 :             deletion_queue_client,
    1123            0 :             l0_flush_global_state,
    1124            0 :         } = resources;
    1125            0 : 
    1126            0 :         let attach_mode = attached_conf.location.attach_mode;
    1127            0 :         let generation = attached_conf.location.generation;
    1128            0 : 
    1129            0 :         let tenant = Arc::new(Tenant::new(
    1130            0 :             TenantState::Attaching,
    1131            0 :             conf,
    1132            0 :             attached_conf,
    1133            0 :             shard_identity,
    1134            0 :             Some(wal_redo_manager),
    1135            0 :             tenant_shard_id,
    1136            0 :             remote_storage.clone(),
    1137            0 :             deletion_queue_client,
    1138            0 :             l0_flush_global_state,
    1139            0 :         ));
    1140            0 : 
    1141            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1142            0 :         // we shut down while attaching.
    1143            0 :         let attach_gate_guard = tenant
    1144            0 :             .gate
    1145            0 :             .enter()
    1146            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1147            0 : 
    1148            0 :         // Do all the hard work in the background
    1149            0 :         let tenant_clone = Arc::clone(&tenant);
    1150            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1151            0 :         task_mgr::spawn(
    1152            0 :             &tokio::runtime::Handle::current(),
    1153            0 :             TaskKind::Attach,
    1154            0 :             tenant_shard_id,
    1155            0 :             None,
    1156            0 :             "attach tenant",
    1157            0 :             async move {
    1158            0 : 
    1159            0 :                 info!(
    1160              :                     ?attach_mode,
    1161            0 :                     "Attaching tenant"
    1162              :                 );
    1163              : 
    1164            0 :                 let _gate_guard = attach_gate_guard;
    1165            0 : 
    1166            0 :                 // Is this tenant being spawned as part of process startup?
    1167            0 :                 let starting_up = init_order.is_some();
    1168            0 :                 scopeguard::defer! {
    1169            0 :                     if starting_up {
    1170            0 :                         TENANT.startup_complete.inc();
    1171            0 :                     }
    1172            0 :                 }
    1173              : 
    1174              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1175              :                 enum BrokenVerbosity {
    1176              :                     Error,
    1177              :                     Info
    1178              :                 }
    1179            0 :                 let make_broken =
    1180            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1181            0 :                         match verbosity {
    1182              :                             BrokenVerbosity::Info => {
    1183            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1184              :                             },
    1185              :                             BrokenVerbosity::Error => {
    1186            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1187              :                             }
    1188              :                         }
    1189            0 :                         t.state.send_modify(|state| {
    1190            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1191            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1192            0 :                             assert!(
    1193            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1194            0 :                                 "the attach task owns the tenant state until activation is complete"
    1195              :                             );
    1196              : 
    1197            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1198            0 :                         });
    1199            0 :                     };
    1200              : 
    1201              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1202            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1203            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1204            0 :                     return Ok(());
    1205            0 :                 }
    1206            0 : 
    1207            0 :                 let mut init_order = init_order;
    1208            0 :                 // take the completion because initial tenant loading will complete when all of
    1209            0 :                 // these tasks complete.
    1210            0 :                 let _completion = init_order
    1211            0 :                     .as_mut()
    1212            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1213            0 :                 let remote_load_completion = init_order
    1214            0 :                     .as_mut()
    1215            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1216              : 
    1217              :                 enum AttachType<'a> {
    1218              :                     /// We are attaching this tenant lazily in the background.
    1219              :                     Warmup {
    1220              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1221              :                         during_startup: bool
    1222              :                     },
    1223              :                     /// We are attaching this tenant as soon as we can, because for example an
    1224              :                     /// endpoint tried to access it.
    1225              :                     OnDemand,
    1226              :                     /// During normal operations after startup, we are attaching a tenant, and
    1227              :                     /// eager attach was requested.
    1228              :                     Normal,
    1229              :                 }
    1230              : 
    1231            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1232              :                     // Before doing any I/O, wait for at least one of:
    1233              :                     // - A client attempting to access to this tenant (on-demand loading)
    1234              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1235              : 
    1236            0 :                     tokio::select!(
    1237            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1238            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1239            0 :                             tracing::info!("Activating tenant (on-demand)");
    1240            0 :                             AttachType::OnDemand
    1241              :                         },
    1242            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1243            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1244            0 :                             tracing::info!("Activating tenant (warmup)");
    1245            0 :                             AttachType::Warmup {
    1246            0 :                                 _permit,
    1247            0 :                                 during_startup: init_order.is_some()
    1248            0 :                             }
    1249              :                         }
    1250            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1251              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1252              :                             // stayed in Activating for such a long time that shutdown found it in
    1253              :                             // that state.
    1254            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1255              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1256              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1257              :                             // just shutting down), but ensures progress.
    1258            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1259            0 :                             return Ok(());
    1260              :                         },
    1261              :                     )
    1262              :                 } else {
    1263              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1264              :                     // concurrent_tenant_warmup queue
    1265            0 :                     AttachType::Normal
    1266              :                 };
    1267              : 
    1268            0 :                 let preload = match &mode {
    1269              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1270            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1271            0 :                         let res = tenant_clone
    1272            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1273            0 :                             .await;
    1274            0 :                         match res {
    1275            0 :                             Ok(p) => Some(p),
    1276            0 :                             Err(e) => {
    1277            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1278            0 :                                 return Ok(());
    1279              :                             }
    1280              :                         }
    1281              :                     }
    1282              : 
    1283              :                 };
    1284              : 
    1285              :                 // Remote preload is complete.
    1286            0 :                 drop(remote_load_completion);
    1287            0 : 
    1288            0 : 
    1289            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1290            0 :                 let attach_start = std::time::Instant::now();
    1291            0 :                 let attached = {
    1292            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1293            0 :                     tenant_clone.attach(preload, &ctx).await
    1294              :                 };
    1295            0 :                 let attach_duration = attach_start.elapsed();
    1296            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1297            0 : 
    1298            0 :                 match attached {
    1299              :                     Ok(()) => {
    1300            0 :                         info!("attach finished, activating");
    1301            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1302              :                     }
    1303            0 :                     Err(e) => {
    1304            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1305            0 :                     }
    1306              :                 }
    1307              : 
    1308              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1309              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1310              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1311              :                 //
    1312              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1313              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1314              :                 // then warmup will wait for that before proceeding to the next tenant.
    1315            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1316            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1317            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1318            0 :                     while futs.next().await.is_some() {}
    1319            0 :                     tracing::info!("Warm-up complete");
    1320            0 :                 }
    1321              : 
    1322            0 :                 Ok(())
    1323            0 :             }
    1324            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1325              :         );
    1326            0 :         Ok(tenant)
    1327            0 :     }
    1328              : 
    1329          190 :     #[instrument(skip_all)]
    1330              :     pub(crate) async fn preload(
    1331              :         self: &Arc<Self>,
    1332              :         remote_storage: &GenericRemoteStorage,
    1333              :         cancel: CancellationToken,
    1334              :     ) -> anyhow::Result<TenantPreload> {
    1335              :         span::debug_assert_current_span_has_tenant_id();
    1336              :         // Get list of remote timelines
    1337              :         // download index files for every tenant timeline
    1338              :         info!("listing remote timelines");
    1339              :         let (remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1340              :             remote_storage,
    1341              :             self.tenant_shard_id,
    1342              :             cancel.clone(),
    1343              :         )
    1344              :         .await?;
    1345              :         let (offloaded_add, tenant_manifest) =
    1346              :             match remote_timeline_client::download_tenant_manifest(
    1347              :                 remote_storage,
    1348              :                 &self.tenant_shard_id,
    1349              :                 self.generation,
    1350              :                 &cancel,
    1351              :             )
    1352              :             .await
    1353              :             {
    1354              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1355              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1356              :                     tenant_manifest,
    1357              :                 ),
    1358              :                 Err(DownloadError::NotFound) => {
    1359              :                     ("no manifest".to_string(), TenantManifest::empty())
    1360              :                 }
    1361              :                 Err(e) => Err(e)?,
    1362              :             };
    1363              : 
    1364              :         info!(
    1365              :             "found {} timelines, and {offloaded_add}",
    1366              :             remote_timeline_ids.len()
    1367              :         );
    1368              : 
    1369              :         for k in other_keys {
    1370              :             warn!("Unexpected non timeline key {k}");
    1371              :         }
    1372              : 
    1373              :         Ok(TenantPreload {
    1374              :             tenant_manifest,
    1375              :             timelines: self
    1376              :                 .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1377              :                 .await?,
    1378              :         })
    1379              :     }
    1380              : 
    1381              :     ///
    1382              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1383              :     ///
    1384              :     /// No background tasks are started as part of this routine.
    1385              :     ///
    1386          190 :     async fn attach(
    1387          190 :         self: &Arc<Tenant>,
    1388          190 :         preload: Option<TenantPreload>,
    1389          190 :         ctx: &RequestContext,
    1390          190 :     ) -> anyhow::Result<()> {
    1391          190 :         span::debug_assert_current_span_has_tenant_id();
    1392          190 : 
    1393          190 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1394              : 
    1395          190 :         let Some(preload) = preload else {
    1396            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1397              :         };
    1398              : 
    1399          190 :         let mut offloaded_timeline_ids = HashSet::new();
    1400          190 :         let mut offloaded_timelines_list = Vec::new();
    1401          190 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1402            0 :             let timeline_id = timeline_manifest.timeline_id;
    1403            0 :             let offloaded_timeline =
    1404            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1405            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1406            0 :             offloaded_timeline_ids.insert(timeline_id);
    1407            0 :         }
    1408              : 
    1409          190 :         let mut timelines_to_resume_deletions = vec![];
    1410          190 : 
    1411          190 :         let mut remote_index_and_client = HashMap::new();
    1412          190 :         let mut timeline_ancestors = HashMap::new();
    1413          190 :         let mut existent_timelines = HashSet::new();
    1414          196 :         for (timeline_id, preload) in preload.timelines {
    1415            6 :             if offloaded_timeline_ids.remove(&timeline_id) {
    1416              :                 // The timeline is offloaded, skip loading it.
    1417            0 :                 continue;
    1418            6 :             }
    1419            6 :             let index_part = match preload.index_part {
    1420            6 :                 Ok(i) => {
    1421            6 :                     debug!("remote index part exists for timeline {timeline_id}");
    1422              :                     // We found index_part on the remote, this is the standard case.
    1423            6 :                     existent_timelines.insert(timeline_id);
    1424            6 :                     i
    1425              :                 }
    1426              :                 Err(DownloadError::NotFound) => {
    1427              :                     // There is no index_part on the remote. We only get here
    1428              :                     // if there is some prefix for the timeline in the remote storage.
    1429              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1430              :                     // remnant from a prior incomplete creation or deletion attempt.
    1431              :                     // Delete the local directory as the deciding criterion for a
    1432              :                     // timeline's existence is presence of index_part.
    1433            0 :                     info!(%timeline_id, "index_part not found on remote");
    1434            0 :                     continue;
    1435              :                 }
    1436            0 :                 Err(DownloadError::Fatal(why)) => {
    1437            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1438            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1439            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1440            0 :                     anyhow::bail!(why.to_string());
    1441              :                 }
    1442            0 :                 Err(e) => {
    1443            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1444            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1445            0 :                     // as it might be a temporary issue and we don't want to re-download
    1446            0 :                     // everything after it resolves.
    1447            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1448              : 
    1449            0 :                     existent_timelines.insert(timeline_id);
    1450            0 :                     continue;
    1451              :                 }
    1452              :             };
    1453            6 :             match index_part {
    1454            6 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1455            6 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1456            6 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1457            6 :                 }
    1458            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1459            0 :                     info!(
    1460            0 :                         "timeline {} is deleted, picking to resume deletion",
    1461              :                         timeline_id
    1462              :                     );
    1463            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1464              :                 }
    1465              :             }
    1466              :         }
    1467              : 
    1468          190 :         let mut gc_blocks = HashMap::new();
    1469              : 
    1470              :         // For every timeline, download the metadata file, scan the local directory,
    1471              :         // and build a layer map that contains an entry for each remote and local
    1472              :         // layer file.
    1473          190 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1474          196 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1475            6 :             let (index_part, remote_client) = remote_index_and_client
    1476            6 :                 .remove(&timeline_id)
    1477            6 :                 .expect("just put it in above");
    1478              : 
    1479            6 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1480              :                 // could just filter these away, but it helps while testing
    1481            0 :                 anyhow::ensure!(
    1482            0 :                     !blocking.reasons.is_empty(),
    1483            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1484              :                 );
    1485            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1486            0 :                 assert!(prev.is_none());
    1487            6 :             }
    1488              : 
    1489              :             // TODO again handle early failure
    1490            6 :             self.load_remote_timeline(
    1491            6 :                 timeline_id,
    1492            6 :                 index_part,
    1493            6 :                 remote_metadata,
    1494            6 :                 TimelineResources {
    1495            6 :                     remote_client,
    1496            6 :                     timeline_get_throttle: self.timeline_get_throttle.clone(),
    1497            6 :                     l0_flush_global_state: self.l0_flush_global_state.clone(),
    1498            6 :                 },
    1499            6 :                 ctx,
    1500            6 :             )
    1501            3 :             .await
    1502            6 :             .with_context(|| {
    1503            0 :                 format!(
    1504            0 :                     "failed to load remote timeline {} for tenant {}",
    1505            0 :                     timeline_id, self.tenant_shard_id
    1506            0 :                 )
    1507            6 :             })?;
    1508              :         }
    1509              : 
    1510              :         // Walk through deleted timelines, resume deletion
    1511          190 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1512            0 :             remote_timeline_client
    1513            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1514            0 :                 .context("init queue stopped")
    1515            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1516              : 
    1517            0 :             DeleteTimelineFlow::resume_deletion(
    1518            0 :                 Arc::clone(self),
    1519            0 :                 timeline_id,
    1520            0 :                 &index_part.metadata,
    1521            0 :                 remote_timeline_client,
    1522            0 :             )
    1523            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1524            0 :             .await
    1525            0 :             .context("resume_deletion")
    1526            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1527              :         }
    1528              :         // Complete deletions for offloaded timeline id's.
    1529          190 :         offloaded_timelines_list
    1530          190 :             .retain(|(offloaded_id, _offloaded)| {
    1531            0 :                 // At this point, offloaded_timeline_ids has the list of all offloaded timelines
    1532            0 :                 // without a prefix in S3, so they are inexistent.
    1533            0 :                 // In the end, existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1534            0 :                 // If there is a dangling reference in another location, they need to be cleaned up.
    1535            0 :                 let delete = offloaded_timeline_ids.contains(offloaded_id);
    1536            0 :                 if delete {
    1537            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1538            0 :                 }
    1539            0 :                 !delete
    1540          190 :         });
    1541          190 :         if !offloaded_timelines_list.is_empty() {
    1542            0 :             tracing::info!(
    1543            0 :                 "Tenant has {} offloaded timelines",
    1544            0 :                 offloaded_timelines_list.len()
    1545              :             );
    1546          190 :         }
    1547          190 :         {
    1548          190 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1549          190 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1550          190 :         }
    1551          190 :         if !offloaded_timeline_ids.is_empty() {
    1552            0 :             self.store_tenant_manifest().await?;
    1553          190 :         }
    1554              : 
    1555              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1556              :         // IndexPart is the source of truth.
    1557          190 :         self.clean_up_timelines(&existent_timelines)?;
    1558              : 
    1559          190 :         self.gc_block.set_scanned(gc_blocks);
    1560          190 : 
    1561          190 :         fail::fail_point!("attach-before-activate", |_| {
    1562            0 :             anyhow::bail!("attach-before-activate");
    1563          190 :         });
    1564          190 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1565              : 
    1566          190 :         info!("Done");
    1567              : 
    1568          190 :         Ok(())
    1569          190 :     }
    1570              : 
    1571              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1572              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1573              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1574          190 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1575          190 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1576              : 
    1577          190 :         let entries = match timelines_dir.read_dir_utf8() {
    1578          190 :             Ok(d) => d,
    1579            0 :             Err(e) => {
    1580            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1581            0 :                     return Ok(());
    1582              :                 } else {
    1583            0 :                     return Err(e).context("list timelines directory for tenant");
    1584              :                 }
    1585              :             }
    1586              :         };
    1587              : 
    1588          198 :         for entry in entries {
    1589            8 :             let entry = entry.context("read timeline dir entry")?;
    1590            8 :             let entry_path = entry.path();
    1591              : 
    1592            8 :             let purge = if crate::is_temporary(entry_path)
    1593              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1594            8 :                 || is_uninit_mark(entry_path)
    1595            8 :                 || crate::is_delete_mark(entry_path)
    1596              :             {
    1597            0 :                 true
    1598              :             } else {
    1599            8 :                 match TimelineId::try_from(entry_path.file_name()) {
    1600            8 :                     Ok(i) => {
    1601            8 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1602            8 :                         !existent_timelines.contains(&i)
    1603              :                     }
    1604            0 :                     Err(e) => {
    1605            0 :                         tracing::warn!(
    1606            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1607              :                         );
    1608              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1609            0 :                         false
    1610              :                     }
    1611              :                 }
    1612              :             };
    1613              : 
    1614            8 :             if purge {
    1615            2 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1616            2 :                 if let Err(e) = match entry.file_type() {
    1617            2 :                     Ok(t) => if t.is_dir() {
    1618            2 :                         std::fs::remove_dir_all(entry_path)
    1619              :                     } else {
    1620            0 :                         std::fs::remove_file(entry_path)
    1621              :                     }
    1622            2 :                     .or_else(fs_ext::ignore_not_found),
    1623            0 :                     Err(e) => Err(e),
    1624              :                 } {
    1625            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1626            2 :                 }
    1627            6 :             }
    1628              :         }
    1629              : 
    1630          190 :         Ok(())
    1631          190 :     }
    1632              : 
    1633              :     /// Get sum of all remote timelines sizes
    1634              :     ///
    1635              :     /// This function relies on the index_part instead of listing the remote storage
    1636            0 :     pub fn remote_size(&self) -> u64 {
    1637            0 :         let mut size = 0;
    1638              : 
    1639            0 :         for timeline in self.list_timelines() {
    1640            0 :             size += timeline.remote_client.get_remote_physical_size();
    1641            0 :         }
    1642              : 
    1643            0 :         size
    1644            0 :     }
    1645              : 
    1646            6 :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1647              :     async fn load_remote_timeline(
    1648              :         &self,
    1649              :         timeline_id: TimelineId,
    1650              :         index_part: IndexPart,
    1651              :         remote_metadata: TimelineMetadata,
    1652              :         resources: TimelineResources,
    1653              :         ctx: &RequestContext,
    1654              :     ) -> anyhow::Result<()> {
    1655              :         span::debug_assert_current_span_has_tenant_id();
    1656              : 
    1657              :         info!("downloading index file for timeline {}", timeline_id);
    1658              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1659              :             .await
    1660              :             .context("Failed to create new timeline directory")?;
    1661              : 
    1662              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1663              :             let timelines = self.timelines.lock().unwrap();
    1664              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1665            0 :                 || {
    1666            0 :                     anyhow::anyhow!(
    1667            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1668            0 :                     )
    1669            0 :                 },
    1670              :             )?))
    1671              :         } else {
    1672              :             None
    1673              :         };
    1674              : 
    1675              :         self.timeline_init_and_sync(
    1676              :             timeline_id,
    1677              :             resources,
    1678              :             index_part,
    1679              :             remote_metadata,
    1680              :             ancestor,
    1681              :             ctx,
    1682              :         )
    1683              :         .await
    1684              :     }
    1685              : 
    1686          190 :     async fn load_timelines_metadata(
    1687          190 :         self: &Arc<Tenant>,
    1688          190 :         timeline_ids: HashSet<TimelineId>,
    1689          190 :         remote_storage: &GenericRemoteStorage,
    1690          190 :         cancel: CancellationToken,
    1691          190 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1692          190 :         let mut part_downloads = JoinSet::new();
    1693          196 :         for timeline_id in timeline_ids {
    1694            6 :             let cancel_clone = cancel.clone();
    1695            6 :             part_downloads.spawn(
    1696            6 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1697            6 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1698              :             );
    1699              :         }
    1700              : 
    1701          190 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1702              : 
    1703              :         loop {
    1704          196 :             tokio::select!(
    1705          196 :                 next = part_downloads.join_next() => {
    1706          196 :                     match next {
    1707            6 :                         Some(result) => {
    1708            6 :                             let preload = result.context("join preload task")?;
    1709            6 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1710              :                         },
    1711              :                         None => {
    1712          190 :                             break;
    1713              :                         }
    1714              :                     }
    1715              :                 },
    1716          196 :                 _ = cancel.cancelled() => {
    1717            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1718              :                 }
    1719              :             )
    1720              :         }
    1721              : 
    1722          190 :         Ok(timeline_preloads)
    1723          190 :     }
    1724              : 
    1725            6 :     fn build_timeline_client(
    1726            6 :         &self,
    1727            6 :         timeline_id: TimelineId,
    1728            6 :         remote_storage: GenericRemoteStorage,
    1729            6 :     ) -> RemoteTimelineClient {
    1730            6 :         RemoteTimelineClient::new(
    1731            6 :             remote_storage.clone(),
    1732            6 :             self.deletion_queue_client.clone(),
    1733            6 :             self.conf,
    1734            6 :             self.tenant_shard_id,
    1735            6 :             timeline_id,
    1736            6 :             self.generation,
    1737            6 :         )
    1738            6 :     }
    1739              : 
    1740            6 :     fn load_timeline_metadata(
    1741            6 :         self: &Arc<Tenant>,
    1742            6 :         timeline_id: TimelineId,
    1743            6 :         remote_storage: GenericRemoteStorage,
    1744            6 :         cancel: CancellationToken,
    1745            6 :     ) -> impl Future<Output = TimelinePreload> {
    1746            6 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1747            6 :         async move {
    1748            6 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1749            6 :             debug!("starting index part download");
    1750              : 
    1751           15 :             let index_part = client.download_index_file(&cancel).await;
    1752              : 
    1753            6 :             debug!("finished index part download");
    1754              : 
    1755            6 :             TimelinePreload {
    1756            6 :                 client,
    1757            6 :                 timeline_id,
    1758            6 :                 index_part,
    1759            6 :             }
    1760            6 :         }
    1761            6 :     }
    1762              : 
    1763            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1764            0 :         timeline_id: TimelineId,
    1765            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1766            0 :     ) -> Result<(), TimelineArchivalError> {
    1767            0 :         let children: Vec<TimelineId> = timelines
    1768            0 :             .iter()
    1769            0 :             .filter_map(|(id, entry)| {
    1770            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1771            0 :                     return None;
    1772            0 :                 }
    1773            0 :                 if entry.is_archived() == Some(true) {
    1774            0 :                     return None;
    1775            0 :                 }
    1776            0 :                 Some(*id)
    1777            0 :             })
    1778            0 :             .collect();
    1779            0 : 
    1780            0 :         if !children.is_empty() {
    1781            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1782            0 :         }
    1783            0 :         Ok(())
    1784            0 :     }
    1785              : 
    1786            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1787            0 :         ancestor_timeline_id: TimelineId,
    1788            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1789            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1790            0 :             '_,
    1791            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1792            0 :         >,
    1793            0 :     ) -> Result<(), TimelineArchivalError> {
    1794            0 :         let has_archived_parent =
    1795            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    1796            0 :                 ancestor_timeline.is_archived() == Some(true)
    1797            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    1798            0 :                 true
    1799              :             } else {
    1800            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    1801            0 :                 if cfg!(debug_assertions) {
    1802            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    1803            0 :                 }
    1804            0 :                 return Err(TimelineArchivalError::NotFound);
    1805              :             };
    1806            0 :         if has_archived_parent {
    1807            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    1808            0 :                 ancestor_timeline_id,
    1809            0 :             ));
    1810            0 :         }
    1811            0 :         Ok(())
    1812            0 :     }
    1813              : 
    1814            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    1815            0 :         timeline: &Arc<Timeline>,
    1816            0 :     ) -> Result<(), TimelineArchivalError> {
    1817            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    1818            0 :             if ancestor_timeline.is_archived() == Some(true) {
    1819            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    1820            0 :                     ancestor_timeline.timeline_id,
    1821            0 :                 ));
    1822            0 :             }
    1823            0 :         }
    1824            0 :         Ok(())
    1825            0 :     }
    1826              : 
    1827              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    1828              :     ///
    1829              :     /// Counterpart to [`offload_timeline`].
    1830            0 :     async fn unoffload_timeline(
    1831            0 :         self: &Arc<Self>,
    1832            0 :         timeline_id: TimelineId,
    1833            0 :         broker_client: storage_broker::BrokerClientChannel,
    1834            0 :         ctx: RequestContext,
    1835            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    1836            0 :         info!("unoffloading timeline");
    1837              : 
    1838              :         // We activate the timeline below manually, so this must be called on an active timeline.
    1839              :         // We expect callers of this function to ensure this.
    1840            0 :         match self.current_state() {
    1841              :             TenantState::Activating { .. }
    1842              :             | TenantState::Attaching
    1843              :             | TenantState::Broken { .. } => {
    1844            0 :                 panic!("Timeline expected to be active")
    1845              :             }
    1846            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    1847            0 :             TenantState::Active => {}
    1848            0 :         }
    1849            0 :         let cancel = self.cancel.clone();
    1850            0 : 
    1851            0 :         // Protect against concurrent attempts to use this TimelineId
    1852            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    1853            0 :         let allow_offloaded = true;
    1854            0 :         let _create_guard = self
    1855            0 :             .create_timeline_create_guard(
    1856            0 :                 timeline_id,
    1857            0 :                 CreateTimelineIdempotency::FailWithConflict,
    1858            0 :                 allow_offloaded,
    1859            0 :             )
    1860            0 :             .map_err(|err| match err {
    1861            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    1862              :                 TimelineExclusionError::AlreadyExists { .. } => {
    1863            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    1864              :                 }
    1865            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    1866            0 :             })?;
    1867              : 
    1868            0 :         let timeline_preload = self
    1869            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    1870            0 :             .await;
    1871              : 
    1872            0 :         let index_part = match timeline_preload.index_part {
    1873            0 :             Ok(index_part) => {
    1874            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    1875            0 :                 index_part
    1876              :             }
    1877              :             Err(DownloadError::NotFound) => {
    1878            0 :                 error!(%timeline_id, "index_part not found on remote");
    1879            0 :                 return Err(TimelineArchivalError::NotFound);
    1880              :             }
    1881            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    1882            0 :             Err(e) => {
    1883            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    1884            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1885            0 :                 return Err(TimelineArchivalError::Other(
    1886            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    1887            0 :                 ));
    1888              :             }
    1889              :         };
    1890            0 :         let index_part = match index_part {
    1891            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    1892            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    1893            0 :                 info!("timeline is deleted according to index_part.json");
    1894            0 :                 return Err(TimelineArchivalError::NotFound);
    1895              :             }
    1896              :         };
    1897            0 :         let remote_metadata = index_part.metadata.clone();
    1898            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    1899            0 :         self.load_remote_timeline(
    1900            0 :             timeline_id,
    1901            0 :             index_part,
    1902            0 :             remote_metadata,
    1903            0 :             timeline_resources,
    1904            0 :             &ctx,
    1905            0 :         )
    1906            0 :         .await
    1907            0 :         .with_context(|| {
    1908            0 :             format!(
    1909            0 :                 "failed to load remote timeline {} for tenant {}",
    1910            0 :                 timeline_id, self.tenant_shard_id
    1911            0 :             )
    1912            0 :         })
    1913            0 :         .map_err(TimelineArchivalError::Other)?;
    1914              : 
    1915            0 :         let timeline = {
    1916            0 :             let timelines = self.timelines.lock().unwrap();
    1917            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    1918            0 :                 warn!("timeline not available directly after attach");
    1919              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    1920              :                 // which puts the timeline into timelines, and our look into the timeline map.
    1921            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    1922            0 :                     "timeline not available directly after attach"
    1923            0 :                 )));
    1924              :             };
    1925            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    1926            0 :             if offloaded_timelines.remove(&timeline_id).is_none() {
    1927            0 :                 warn!("timeline already removed from offloaded timelines");
    1928            0 :             }
    1929            0 :             Arc::clone(timeline)
    1930            0 :         };
    1931            0 : 
    1932            0 :         // Upload new list of offloaded timelines to S3
    1933            0 :         self.store_tenant_manifest().await?;
    1934              : 
    1935              :         // Activate the timeline (if it makes sense)
    1936            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    1937            0 :             let background_jobs_can_start = None;
    1938            0 :             timeline.activate(
    1939            0 :                 self.clone(),
    1940            0 :                 broker_client.clone(),
    1941            0 :                 background_jobs_can_start,
    1942            0 :                 &ctx,
    1943            0 :             );
    1944            0 :         }
    1945              : 
    1946            0 :         info!("timeline unoffloading complete");
    1947            0 :         Ok(timeline)
    1948            0 :     }
    1949              : 
    1950            0 :     pub(crate) async fn apply_timeline_archival_config(
    1951            0 :         self: &Arc<Self>,
    1952            0 :         timeline_id: TimelineId,
    1953            0 :         new_state: TimelineArchivalState,
    1954            0 :         broker_client: storage_broker::BrokerClientChannel,
    1955            0 :         ctx: RequestContext,
    1956            0 :     ) -> Result<(), TimelineArchivalError> {
    1957            0 :         info!("setting timeline archival config");
    1958              :         // First part: figure out what is needed to do, and do validation
    1959            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    1960            0 :             let timelines = self.timelines.lock().unwrap();
    1961              : 
    1962            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    1963            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    1964            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    1965            0 :                     return Err(TimelineArchivalError::NotFound);
    1966              :                 };
    1967            0 :                 if new_state == TimelineArchivalState::Archived {
    1968              :                     // It's offloaded already, so nothing to do
    1969            0 :                     return Ok(());
    1970            0 :                 }
    1971            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    1972            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    1973            0 :                         ancestor_timeline_id,
    1974            0 :                         &timelines,
    1975            0 :                         &offloaded_timelines,
    1976            0 :                     )?;
    1977            0 :                 }
    1978            0 :                 break 'outer None;
    1979              :             };
    1980              : 
    1981              :             // Do some validation. We release the timelines lock below, so there is potential
    1982              :             // for race conditions: these checks are more present to prevent misunderstandings of
    1983              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    1984            0 :             match new_state {
    1985              :                 TimelineArchivalState::Unarchived => {
    1986            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    1987              :                 }
    1988              :                 TimelineArchivalState::Archived => {
    1989            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    1990              :                 }
    1991              :             }
    1992            0 :             Some(Arc::clone(timeline))
    1993              :         };
    1994              : 
    1995              :         // Second part: unoffload timeline (if needed)
    1996            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    1997            0 :             timeline
    1998              :         } else {
    1999              :             // Turn offloaded timeline into a non-offloaded one
    2000            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2001            0 :                 .await?
    2002              :         };
    2003              : 
    2004              :         // Third part: upload new timeline archival state and block until it is present in S3
    2005            0 :         let upload_needed = match timeline
    2006            0 :             .remote_client
    2007            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2008              :         {
    2009            0 :             Ok(upload_needed) => upload_needed,
    2010            0 :             Err(e) => {
    2011            0 :                 if timeline.cancel.is_cancelled() {
    2012            0 :                     return Err(TimelineArchivalError::Cancelled);
    2013              :                 } else {
    2014            0 :                     return Err(TimelineArchivalError::Other(e));
    2015              :                 }
    2016              :             }
    2017              :         };
    2018              : 
    2019            0 :         if upload_needed {
    2020            0 :             info!("Uploading new state");
    2021              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2022            0 :             let Ok(v) =
    2023            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2024              :             else {
    2025            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2026            0 :                 return Err(TimelineArchivalError::Timeout);
    2027              :             };
    2028            0 :             v.map_err(|e| match e {
    2029            0 :                 WaitCompletionError::NotInitialized(e) => {
    2030            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2031              :                 }
    2032              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2033            0 :                     TimelineArchivalError::Cancelled
    2034              :                 }
    2035            0 :             })?;
    2036            0 :         }
    2037            0 :         Ok(())
    2038            0 :     }
    2039              : 
    2040            0 :     pub fn get_offloaded_timeline(
    2041            0 :         &self,
    2042            0 :         timeline_id: TimelineId,
    2043            0 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2044            0 :         self.timelines_offloaded
    2045            0 :             .lock()
    2046            0 :             .unwrap()
    2047            0 :             .get(&timeline_id)
    2048            0 :             .map(Arc::clone)
    2049            0 :             .ok_or(GetTimelineError::NotFound {
    2050            0 :                 tenant_id: self.tenant_shard_id,
    2051            0 :                 timeline_id,
    2052            0 :             })
    2053            0 :     }
    2054              : 
    2055            4 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2056            4 :         self.tenant_shard_id
    2057            4 :     }
    2058              : 
    2059              :     /// Get Timeline handle for given Neon timeline ID.
    2060              :     /// This function is idempotent. It doesn't change internal state in any way.
    2061          222 :     pub fn get_timeline(
    2062          222 :         &self,
    2063          222 :         timeline_id: TimelineId,
    2064          222 :         active_only: bool,
    2065          222 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2066          222 :         let timelines_accessor = self.timelines.lock().unwrap();
    2067          222 :         let timeline = timelines_accessor
    2068          222 :             .get(&timeline_id)
    2069          222 :             .ok_or(GetTimelineError::NotFound {
    2070          222 :                 tenant_id: self.tenant_shard_id,
    2071          222 :                 timeline_id,
    2072          222 :             })?;
    2073              : 
    2074          220 :         if active_only && !timeline.is_active() {
    2075            0 :             Err(GetTimelineError::NotActive {
    2076            0 :                 tenant_id: self.tenant_shard_id,
    2077            0 :                 timeline_id,
    2078            0 :                 state: timeline.current_state(),
    2079            0 :             })
    2080              :         } else {
    2081          220 :             Ok(Arc::clone(timeline))
    2082              :         }
    2083          222 :     }
    2084              : 
    2085              :     /// Lists timelines the tenant contains.
    2086              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2087            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2088            0 :         self.timelines
    2089            0 :             .lock()
    2090            0 :             .unwrap()
    2091            0 :             .values()
    2092            0 :             .map(Arc::clone)
    2093            0 :             .collect()
    2094            0 :     }
    2095              : 
    2096              :     /// Lists timelines the tenant manages, including offloaded ones.
    2097              :     ///
    2098              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2099            0 :     pub fn list_timelines_and_offloaded(
    2100            0 :         &self,
    2101            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2102            0 :         let timelines = self
    2103            0 :             .timelines
    2104            0 :             .lock()
    2105            0 :             .unwrap()
    2106            0 :             .values()
    2107            0 :             .map(Arc::clone)
    2108            0 :             .collect();
    2109            0 :         let offloaded = self
    2110            0 :             .timelines_offloaded
    2111            0 :             .lock()
    2112            0 :             .unwrap()
    2113            0 :             .values()
    2114            0 :             .map(Arc::clone)
    2115            0 :             .collect();
    2116            0 :         (timelines, offloaded)
    2117            0 :     }
    2118              : 
    2119            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2120            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2121            0 :     }
    2122              : 
    2123              :     /// This is used by tests & import-from-basebackup.
    2124              :     ///
    2125              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2126              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2127              :     ///
    2128              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2129              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2130              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2131              :     /// to the [`Tenant::timelines`].
    2132              :     ///
    2133              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2134          182 :     pub(crate) async fn create_empty_timeline(
    2135          182 :         &self,
    2136          182 :         new_timeline_id: TimelineId,
    2137          182 :         initdb_lsn: Lsn,
    2138          182 :         pg_version: u32,
    2139          182 :         _ctx: &RequestContext,
    2140          182 :     ) -> anyhow::Result<UninitializedTimeline> {
    2141          182 :         anyhow::ensure!(
    2142          182 :             self.is_active(),
    2143            0 :             "Cannot create empty timelines on inactive tenant"
    2144              :         );
    2145              : 
    2146              :         // Protect against concurrent attempts to use this TimelineId
    2147          182 :         let create_guard = match self
    2148          182 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2149          177 :             .await?
    2150              :         {
    2151          180 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2152              :             StartCreatingTimelineResult::Idempotent(_) => {
    2153            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2154              :             }
    2155              :         };
    2156              : 
    2157          180 :         let new_metadata = TimelineMetadata::new(
    2158          180 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2159          180 :             // make it valid, before calling finish_creation()
    2160          180 :             Lsn(0),
    2161          180 :             None,
    2162          180 :             None,
    2163          180 :             Lsn(0),
    2164          180 :             initdb_lsn,
    2165          180 :             initdb_lsn,
    2166          180 :             pg_version,
    2167          180 :         );
    2168          180 :         self.prepare_new_timeline(
    2169          180 :             new_timeline_id,
    2170          180 :             &new_metadata,
    2171          180 :             create_guard,
    2172          180 :             initdb_lsn,
    2173          180 :             None,
    2174          180 :         )
    2175            0 :         .await
    2176          182 :     }
    2177              : 
    2178              :     /// Helper for unit tests to create an empty timeline.
    2179              :     ///
    2180              :     /// The timeline is has state value `Active` but its background loops are not running.
    2181              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2182              :     // Our current tests don't need the background loops.
    2183              :     #[cfg(test)]
    2184          172 :     pub async fn create_test_timeline(
    2185          172 :         &self,
    2186          172 :         new_timeline_id: TimelineId,
    2187          172 :         initdb_lsn: Lsn,
    2188          172 :         pg_version: u32,
    2189          172 :         ctx: &RequestContext,
    2190          172 :     ) -> anyhow::Result<Arc<Timeline>> {
    2191          172 :         let uninit_tl = self
    2192          172 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2193          169 :             .await?;
    2194          172 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2195          172 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2196              : 
    2197              :         // Setup minimum keys required for the timeline to be usable.
    2198          172 :         let mut modification = tline.begin_modification(initdb_lsn);
    2199          172 :         modification
    2200          172 :             .init_empty_test_timeline()
    2201          172 :             .context("init_empty_test_timeline")?;
    2202          172 :         modification
    2203          172 :             .commit(ctx)
    2204          166 :             .await
    2205          172 :             .context("commit init_empty_test_timeline modification")?;
    2206              : 
    2207              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2208          172 :         tline.maybe_spawn_flush_loop();
    2209          172 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2210              : 
    2211              :         // Make sure the freeze_and_flush reaches remote storage.
    2212          172 :         tline.remote_client.wait_completion().await.unwrap();
    2213              : 
    2214          172 :         let tl = uninit_tl.finish_creation()?;
    2215              :         // The non-test code would call tl.activate() here.
    2216          172 :         tl.set_state(TimelineState::Active);
    2217          172 :         Ok(tl)
    2218          172 :     }
    2219              : 
    2220              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2221              :     #[cfg(test)]
    2222              :     #[allow(clippy::too_many_arguments)]
    2223           32 :     pub async fn create_test_timeline_with_layers(
    2224           32 :         &self,
    2225           32 :         new_timeline_id: TimelineId,
    2226           32 :         initdb_lsn: Lsn,
    2227           32 :         pg_version: u32,
    2228           32 :         ctx: &RequestContext,
    2229           32 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2230           32 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2231           32 :         end_lsn: Lsn,
    2232           32 :     ) -> anyhow::Result<Arc<Timeline>> {
    2233              :         use checks::check_valid_layermap;
    2234              :         use itertools::Itertools;
    2235              : 
    2236           32 :         let tline = self
    2237           32 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2238           96 :             .await?;
    2239           32 :         tline.force_advance_lsn(end_lsn);
    2240          100 :         for deltas in delta_layer_desc {
    2241           68 :             tline
    2242           68 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2243          204 :                 .await?;
    2244              :         }
    2245           80 :         for (lsn, images) in image_layer_desc {
    2246           48 :             tline
    2247           48 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2248          294 :                 .await?;
    2249              :         }
    2250           32 :         let layer_names = tline
    2251           32 :             .layers
    2252           32 :             .read()
    2253            0 :             .await
    2254           32 :             .layer_map()
    2255           32 :             .unwrap()
    2256           32 :             .iter_historic_layers()
    2257          148 :             .map(|layer| layer.layer_name())
    2258           32 :             .collect_vec();
    2259           32 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2260            0 :             bail!("invalid layermap: {err}");
    2261           32 :         }
    2262           32 :         Ok(tline)
    2263           32 :     }
    2264              : 
    2265              :     /// Create a new timeline.
    2266              :     ///
    2267              :     /// Returns the new timeline ID and reference to its Timeline object.
    2268              :     ///
    2269              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2270              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2271              :     #[allow(clippy::too_many_arguments)]
    2272            0 :     pub(crate) async fn create_timeline(
    2273            0 :         self: &Arc<Tenant>,
    2274            0 :         params: CreateTimelineParams,
    2275            0 :         broker_client: storage_broker::BrokerClientChannel,
    2276            0 :         ctx: &RequestContext,
    2277            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2278            0 :         if !self.is_active() {
    2279            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2280            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2281              :             } else {
    2282            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2283            0 :                     "Cannot create timelines on inactive tenant"
    2284            0 :                 )));
    2285              :             }
    2286            0 :         }
    2287              : 
    2288            0 :         let _gate = self
    2289            0 :             .gate
    2290            0 :             .enter()
    2291            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2292              : 
    2293            0 :         let result: CreateTimelineResult = match params {
    2294              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2295            0 :                 new_timeline_id,
    2296            0 :                 existing_initdb_timeline_id,
    2297            0 :                 pg_version,
    2298            0 :             }) => {
    2299            0 :                 self.bootstrap_timeline(
    2300            0 :                     new_timeline_id,
    2301            0 :                     pg_version,
    2302            0 :                     existing_initdb_timeline_id,
    2303            0 :                     ctx,
    2304            0 :                 )
    2305            0 :                 .await?
    2306              :             }
    2307              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2308            0 :                 new_timeline_id,
    2309            0 :                 ancestor_timeline_id,
    2310            0 :                 mut ancestor_start_lsn,
    2311              :             }) => {
    2312            0 :                 let ancestor_timeline = self
    2313            0 :                     .get_timeline(ancestor_timeline_id, false)
    2314            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2315              : 
    2316              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2317              :                 // ready for other purposes either.
    2318            0 :                 if !ancestor_timeline.is_active() {
    2319            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2320            0 :                 }
    2321            0 : 
    2322            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2323            0 :                     info!("tried to branch archived timeline");
    2324            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2325            0 :                 }
    2326              : 
    2327            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2328            0 :                     *lsn = lsn.align();
    2329            0 : 
    2330            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2331            0 :                     if ancestor_ancestor_lsn > *lsn {
    2332              :                         // can we safely just branch from the ancestor instead?
    2333            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2334            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2335            0 :                             lsn,
    2336            0 :                             ancestor_timeline_id,
    2337            0 :                             ancestor_ancestor_lsn,
    2338            0 :                         )));
    2339            0 :                     }
    2340            0 : 
    2341            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2342            0 :                     // to the requested branch point. The repository code itself doesn't
    2343            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2344            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2345            0 :                     // sizes etc. and that would get confused if the previous page versions
    2346            0 :                     // are not in the repository yet.
    2347            0 :                     ancestor_timeline
    2348            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    2349            0 :                         .await
    2350            0 :                         .map_err(|e| match e {
    2351            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2352            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2353              :                             }
    2354            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2355            0 :                         })?;
    2356            0 :                 }
    2357              : 
    2358            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2359            0 :                     .await?
    2360              :             }
    2361              :         };
    2362              : 
    2363              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2364              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2365              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2366              :         //
    2367              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2368              :         // assume that, because they can see the timeline via API, that the creation is done and
    2369              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2370              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2371              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2372              :         //
    2373              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2374              :         // creation API until it returns success. Only then is durability guaranteed.
    2375            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2376            0 :         result
    2377            0 :             .timeline()
    2378            0 :             .remote_client
    2379            0 :             .wait_completion()
    2380            0 :             .await
    2381            0 :             .context("wait for timeline initial uploads to complete")?;
    2382              : 
    2383              :         // The creating task is responsible for activating the timeline.
    2384              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2385              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2386            0 :         let activated_timeline = match result {
    2387            0 :             CreateTimelineResult::Created(timeline) => {
    2388            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2389            0 :                 timeline
    2390              :             }
    2391            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2392            0 :                 info!(
    2393            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2394              :                 );
    2395            0 :                 timeline
    2396              :             }
    2397              :         };
    2398              : 
    2399            0 :         Ok(activated_timeline)
    2400            0 :     }
    2401              : 
    2402            0 :     pub(crate) async fn delete_timeline(
    2403            0 :         self: Arc<Self>,
    2404            0 :         timeline_id: TimelineId,
    2405            0 :     ) -> Result<(), DeleteTimelineError> {
    2406            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2407              : 
    2408            0 :         Ok(())
    2409            0 :     }
    2410              : 
    2411              :     /// perform one garbage collection iteration, removing old data files from disk.
    2412              :     /// this function is periodically called by gc task.
    2413              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2414              :     ///
    2415              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2416              :     ///
    2417              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2418              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2419              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2420              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2421              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2422              :     /// requires more history to be retained.
    2423              :     //
    2424          754 :     pub(crate) async fn gc_iteration(
    2425          754 :         &self,
    2426          754 :         target_timeline_id: Option<TimelineId>,
    2427          754 :         horizon: u64,
    2428          754 :         pitr: Duration,
    2429          754 :         cancel: &CancellationToken,
    2430          754 :         ctx: &RequestContext,
    2431          754 :     ) -> Result<GcResult, GcError> {
    2432          754 :         // Don't start doing work during shutdown
    2433          754 :         if let TenantState::Stopping { .. } = self.current_state() {
    2434            0 :             return Ok(GcResult::default());
    2435          754 :         }
    2436          754 : 
    2437          754 :         // there is a global allowed_error for this
    2438          754 :         if !self.is_active() {
    2439            0 :             return Err(GcError::NotActive);
    2440          754 :         }
    2441          754 : 
    2442          754 :         {
    2443          754 :             let conf = self.tenant_conf.load();
    2444          754 : 
    2445          754 :             if !conf.location.may_delete_layers_hint() {
    2446            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2447            0 :                 return Ok(GcResult::default());
    2448          754 :             }
    2449          754 : 
    2450          754 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2451          750 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2452          750 :                 return Ok(GcResult::default());
    2453            4 :             }
    2454              :         }
    2455              : 
    2456            4 :         let _guard = match self.gc_block.start().await {
    2457            4 :             Ok(guard) => guard,
    2458            0 :             Err(reasons) => {
    2459            0 :                 info!("Skipping GC: {reasons}");
    2460            0 :                 return Ok(GcResult::default());
    2461              :             }
    2462              :         };
    2463              : 
    2464            4 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2465            4 :             .await
    2466          754 :     }
    2467              : 
    2468              :     /// Perform one compaction iteration.
    2469              :     /// This function is periodically called by compactor task.
    2470              :     /// Also it can be explicitly requested per timeline through page server
    2471              :     /// api's 'compact' command.
    2472              :     ///
    2473              :     /// Returns whether we have pending compaction task.
    2474            0 :     async fn compaction_iteration(
    2475            0 :         self: &Arc<Self>,
    2476            0 :         cancel: &CancellationToken,
    2477            0 :         ctx: &RequestContext,
    2478            0 :     ) -> Result<bool, timeline::CompactionError> {
    2479            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2480            0 :         if !self.is_active() {
    2481            0 :             return Ok(false);
    2482            0 :         }
    2483            0 : 
    2484            0 :         {
    2485            0 :             let conf = self.tenant_conf.load();
    2486            0 :             if !conf.location.may_delete_layers_hint() || !conf.location.may_upload_layers_hint() {
    2487            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2488            0 :                 return Ok(false);
    2489            0 :             }
    2490            0 :         }
    2491            0 : 
    2492            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2493            0 :         // while holding the lock. Then drop the lock and actually perform the
    2494            0 :         // compactions.  We don't want to block everything else while the
    2495            0 :         // compaction runs.
    2496            0 :         let timelines_to_compact_or_offload;
    2497            0 :         {
    2498            0 :             let timelines = self.timelines.lock().unwrap();
    2499            0 :             timelines_to_compact_or_offload = timelines
    2500            0 :                 .iter()
    2501            0 :                 .filter_map(|(timeline_id, timeline)| {
    2502            0 :                     let (is_active, (can_offload, _)) =
    2503            0 :                         (timeline.is_active(), timeline.can_offload());
    2504            0 :                     let has_no_unoffloaded_children = {
    2505            0 :                         !timelines
    2506            0 :                             .iter()
    2507            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2508              :                     };
    2509            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2510            0 :                         || self
    2511            0 :                             .tenant_conf
    2512            0 :                             .load()
    2513            0 :                             .tenant_conf
    2514            0 :                             .timeline_offloading
    2515            0 :                             .unwrap_or_default();
    2516            0 :                     let can_offload =
    2517            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2518            0 :                     if (is_active, can_offload) == (false, false) {
    2519            0 :                         None
    2520              :                     } else {
    2521            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2522              :                     }
    2523            0 :                 })
    2524            0 :                 .collect::<Vec<_>>();
    2525            0 :             drop(timelines);
    2526            0 :         }
    2527            0 : 
    2528            0 :         // Before doing any I/O work, check our circuit breaker
    2529            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2530            0 :             info!("Skipping compaction due to previous failures");
    2531            0 :             return Ok(false);
    2532            0 :         }
    2533            0 : 
    2534            0 :         let mut has_pending_task = false;
    2535              : 
    2536            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2537              :         {
    2538            0 :             let pending_task_left = if *can_compact {
    2539              :                 Some(
    2540            0 :                     timeline
    2541            0 :                         .compact(cancel, EnumSet::empty(), ctx)
    2542            0 :                         .instrument(info_span!("compact_timeline", %timeline_id))
    2543            0 :                         .await
    2544            0 :                         .inspect_err(|e| match e {
    2545            0 :                             timeline::CompactionError::ShuttingDown => (),
    2546            0 :                             timeline::CompactionError::Offload(_) => {
    2547            0 :                                 // Failures to offload timelines do not trip the circuit breaker, because
    2548            0 :                                 // they do not do lots of writes the way compaction itself does: it is cheap
    2549            0 :                                 // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2550            0 :                             }
    2551            0 :                             timeline::CompactionError::Other(e) => {
    2552            0 :                                 self.compaction_circuit_breaker
    2553            0 :                                     .lock()
    2554            0 :                                     .unwrap()
    2555            0 :                                     .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2556            0 :                             }
    2557            0 :                         })?,
    2558              :                 )
    2559              :             } else {
    2560            0 :                 None
    2561              :             };
    2562            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    2563            0 :             if pending_task_left == Some(false) && *can_offload {
    2564            0 :                 offload_timeline(self, timeline)
    2565            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    2566            0 :                     .await?;
    2567            0 :             }
    2568              :         }
    2569              : 
    2570            0 :         self.compaction_circuit_breaker
    2571            0 :             .lock()
    2572            0 :             .unwrap()
    2573            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    2574            0 : 
    2575            0 :         Ok(has_pending_task)
    2576            0 :     }
    2577              : 
    2578              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    2579              :     // this happens during ingest: this background housekeeping is for freezing layers
    2580              :     // that are open but haven't been written to for some time.
    2581            0 :     async fn ingest_housekeeping(&self) {
    2582            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2583            0 :         // while holding the lock. Then drop the lock and actually perform the
    2584            0 :         // compactions.  We don't want to block everything else while the
    2585            0 :         // compaction runs.
    2586            0 :         let timelines = {
    2587            0 :             self.timelines
    2588            0 :                 .lock()
    2589            0 :                 .unwrap()
    2590            0 :                 .values()
    2591            0 :                 .filter_map(|timeline| {
    2592            0 :                     if timeline.is_active() {
    2593            0 :                         Some(timeline.clone())
    2594              :                     } else {
    2595            0 :                         None
    2596              :                     }
    2597            0 :                 })
    2598            0 :                 .collect::<Vec<_>>()
    2599              :         };
    2600              : 
    2601            0 :         for timeline in &timelines {
    2602            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    2603              :         }
    2604            0 :     }
    2605              : 
    2606            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    2607            0 :         let timelines = self.timelines.lock().unwrap();
    2608            0 :         !timelines
    2609            0 :             .iter()
    2610            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    2611            0 :     }
    2612              : 
    2613         1700 :     pub fn current_state(&self) -> TenantState {
    2614         1700 :         self.state.borrow().clone()
    2615         1700 :     }
    2616              : 
    2617          940 :     pub fn is_active(&self) -> bool {
    2618          940 :         self.current_state() == TenantState::Active
    2619          940 :     }
    2620              : 
    2621            0 :     pub fn generation(&self) -> Generation {
    2622            0 :         self.generation
    2623            0 :     }
    2624              : 
    2625            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    2626            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    2627            0 :     }
    2628              : 
    2629              :     /// Changes tenant status to active, unless shutdown was already requested.
    2630              :     ///
    2631              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    2632              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    2633            0 :     fn activate(
    2634            0 :         self: &Arc<Self>,
    2635            0 :         broker_client: BrokerClientChannel,
    2636            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    2637            0 :         ctx: &RequestContext,
    2638            0 :     ) {
    2639            0 :         span::debug_assert_current_span_has_tenant_id();
    2640            0 : 
    2641            0 :         let mut activating = false;
    2642            0 :         self.state.send_modify(|current_state| {
    2643              :             use pageserver_api::models::ActivatingFrom;
    2644            0 :             match &*current_state {
    2645              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    2646            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    2647              :                 }
    2648            0 :                 TenantState::Attaching => {
    2649            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    2650            0 :                 }
    2651            0 :             }
    2652            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    2653            0 :             activating = true;
    2654            0 :             // Continue outside the closure. We need to grab timelines.lock()
    2655            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    2656            0 :         });
    2657            0 : 
    2658            0 :         if activating {
    2659            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    2660            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    2661            0 :             let timelines_to_activate = timelines_accessor
    2662            0 :                 .values()
    2663            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    2664            0 : 
    2665            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    2666            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor);
    2667            0 : 
    2668            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    2669            0 :             // down when they notice that the tenant is inactive.
    2670            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    2671            0 : 
    2672            0 :             let mut activated_timelines = 0;
    2673              : 
    2674            0 :             for timeline in timelines_to_activate {
    2675            0 :                 timeline.activate(
    2676            0 :                     self.clone(),
    2677            0 :                     broker_client.clone(),
    2678            0 :                     background_jobs_can_start,
    2679            0 :                     ctx,
    2680            0 :                 );
    2681            0 :                 activated_timelines += 1;
    2682            0 :             }
    2683              : 
    2684            0 :             self.state.send_modify(move |current_state| {
    2685            0 :                 assert!(
    2686            0 :                     matches!(current_state, TenantState::Activating(_)),
    2687            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    2688              :                 );
    2689            0 :                 *current_state = TenantState::Active;
    2690            0 : 
    2691            0 :                 let elapsed = self.constructed_at.elapsed();
    2692            0 :                 let total_timelines = timelines_accessor.len();
    2693            0 : 
    2694            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    2695            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    2696            0 :                 info!(
    2697            0 :                     since_creation_millis = elapsed.as_millis(),
    2698            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    2699            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    2700            0 :                     activated_timelines,
    2701            0 :                     total_timelines,
    2702            0 :                     post_state = <&'static str>::from(&*current_state),
    2703            0 :                     "activation attempt finished"
    2704              :                 );
    2705              : 
    2706            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    2707            0 :             });
    2708            0 :         }
    2709            0 :     }
    2710              : 
    2711              :     /// Shutdown the tenant and join all of the spawned tasks.
    2712              :     ///
    2713              :     /// The method caters for all use-cases:
    2714              :     /// - pageserver shutdown (freeze_and_flush == true)
    2715              :     /// - detach + ignore (freeze_and_flush == false)
    2716              :     ///
    2717              :     /// This will attempt to shutdown even if tenant is broken.
    2718              :     ///
    2719              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    2720              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    2721              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    2722              :     /// the ongoing shutdown.
    2723            6 :     async fn shutdown(
    2724            6 :         &self,
    2725            6 :         shutdown_progress: completion::Barrier,
    2726            6 :         shutdown_mode: timeline::ShutdownMode,
    2727            6 :     ) -> Result<(), completion::Barrier> {
    2728            6 :         span::debug_assert_current_span_has_tenant_id();
    2729              : 
    2730              :         // Set tenant (and its timlines) to Stoppping state.
    2731              :         //
    2732              :         // Since we can only transition into Stopping state after activation is complete,
    2733              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    2734              :         //
    2735              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    2736              :         // 1. Lock out any new requests to the tenants.
    2737              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    2738              :         // 3. Signal cancellation for other tenant background loops.
    2739              :         // 4. ???
    2740              :         //
    2741              :         // The waiting for the cancellation is not done uniformly.
    2742              :         // We certainly wait for WAL receivers to shut down.
    2743              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    2744              :         // But the tenant background loops are joined-on in our caller.
    2745              :         // It's mesed up.
    2746              :         // we just ignore the failure to stop
    2747              : 
    2748              :         // If we're still attaching, fire the cancellation token early to drop out: this
    2749              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    2750              :         // is very slow.
    2751            6 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    2752            0 :             self.cancel.cancel();
    2753            0 : 
    2754            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    2755            0 :             // are children of ours, so their flush loops will have shut down already
    2756            0 :             timeline::ShutdownMode::Hard
    2757              :         } else {
    2758            6 :             shutdown_mode
    2759              :         };
    2760              : 
    2761            6 :         match self.set_stopping(shutdown_progress, false, false).await {
    2762            6 :             Ok(()) => {}
    2763            0 :             Err(SetStoppingError::Broken) => {
    2764            0 :                 // assume that this is acceptable
    2765            0 :             }
    2766            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    2767            0 :                 // give caller the option to wait for this this shutdown
    2768            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    2769            0 :                 return Err(other);
    2770              :             }
    2771              :         };
    2772              : 
    2773            6 :         let mut js = tokio::task::JoinSet::new();
    2774            6 :         {
    2775            6 :             let timelines = self.timelines.lock().unwrap();
    2776            6 :             timelines.values().for_each(|timeline| {
    2777            6 :                 let timeline = Arc::clone(timeline);
    2778            6 :                 let timeline_id = timeline.timeline_id;
    2779            6 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    2780           13 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    2781            6 :             })
    2782            6 :         };
    2783            6 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    2784            6 :         tracing::info!("Waiting for timelines...");
    2785           12 :         while let Some(res) = js.join_next().await {
    2786            0 :             match res {
    2787            6 :                 Ok(()) => {}
    2788            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    2789            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    2790            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    2791              :             }
    2792              :         }
    2793              : 
    2794              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    2795              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    2796            6 :         tracing::debug!("Cancelling CancellationToken");
    2797            6 :         self.cancel.cancel();
    2798            6 : 
    2799            6 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    2800            6 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    2801            6 :         //
    2802            6 :         // this will additionally shutdown and await all timeline tasks.
    2803            6 :         tracing::debug!("Waiting for tasks...");
    2804            6 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    2805              : 
    2806            6 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    2807            6 :             walredo_mgr.shutdown().await;
    2808            0 :         }
    2809              : 
    2810              :         // Wait for any in-flight operations to complete
    2811            6 :         self.gate.close().await;
    2812              : 
    2813            6 :         remove_tenant_metrics(&self.tenant_shard_id);
    2814            6 : 
    2815            6 :         Ok(())
    2816            6 :     }
    2817              : 
    2818              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    2819              :     ///
    2820              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    2821              :     ///
    2822              :     /// This function is not cancel-safe!
    2823              :     ///
    2824              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    2825              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    2826            6 :     async fn set_stopping(
    2827            6 :         &self,
    2828            6 :         progress: completion::Barrier,
    2829            6 :         _allow_transition_from_loading: bool,
    2830            6 :         allow_transition_from_attaching: bool,
    2831            6 :     ) -> Result<(), SetStoppingError> {
    2832            6 :         let mut rx = self.state.subscribe();
    2833            6 : 
    2834            6 :         // cannot stop before we're done activating, so wait out until we're done activating
    2835            6 :         rx.wait_for(|state| match state {
    2836            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    2837              :             TenantState::Activating(_) | TenantState::Attaching => {
    2838            0 :                 info!(
    2839            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    2840            0 :                     <&'static str>::from(state)
    2841              :                 );
    2842            0 :                 false
    2843              :             }
    2844            6 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    2845            6 :         })
    2846            0 :         .await
    2847            6 :         .expect("cannot drop self.state while on a &self method");
    2848            6 : 
    2849            6 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    2850            6 :         let mut err = None;
    2851            6 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    2852              :             TenantState::Activating(_) => {
    2853            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    2854              :             }
    2855              :             TenantState::Attaching => {
    2856            0 :                 if !allow_transition_from_attaching {
    2857            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    2858            0 :                 };
    2859            0 :                 *current_state = TenantState::Stopping { progress };
    2860            0 :                 true
    2861              :             }
    2862              :             TenantState::Active => {
    2863              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    2864              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    2865              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    2866            6 :                 *current_state = TenantState::Stopping { progress };
    2867            6 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    2868            6 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    2869            6 :                 true
    2870              :             }
    2871            0 :             TenantState::Broken { reason, .. } => {
    2872            0 :                 info!(
    2873            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    2874              :                 );
    2875            0 :                 err = Some(SetStoppingError::Broken);
    2876            0 :                 false
    2877              :             }
    2878            0 :             TenantState::Stopping { progress } => {
    2879            0 :                 info!("Tenant is already in Stopping state");
    2880            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    2881            0 :                 false
    2882              :             }
    2883            6 :         });
    2884            6 :         match (stopping, err) {
    2885            6 :             (true, None) => {} // continue
    2886            0 :             (false, Some(err)) => return Err(err),
    2887            0 :             (true, Some(_)) => unreachable!(
    2888            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    2889            0 :             ),
    2890            0 :             (false, None) => unreachable!(
    2891            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    2892            0 :             ),
    2893              :         }
    2894              : 
    2895            6 :         let timelines_accessor = self.timelines.lock().unwrap();
    2896            6 :         let not_broken_timelines = timelines_accessor
    2897            6 :             .values()
    2898            6 :             .filter(|timeline| !timeline.is_broken());
    2899           12 :         for timeline in not_broken_timelines {
    2900            6 :             timeline.set_state(TimelineState::Stopping);
    2901            6 :         }
    2902            6 :         Ok(())
    2903            6 :     }
    2904              : 
    2905              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    2906              :     /// `remove_tenant_from_memory`
    2907              :     ///
    2908              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    2909              :     ///
    2910              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    2911            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    2912            0 :         let mut rx = self.state.subscribe();
    2913            0 : 
    2914            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    2915            0 :         // So, wait until it's done.
    2916            0 :         rx.wait_for(|state| match state {
    2917              :             TenantState::Activating(_) | TenantState::Attaching => {
    2918            0 :                 info!(
    2919            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    2920            0 :                     <&'static str>::from(state)
    2921              :                 );
    2922            0 :                 false
    2923              :             }
    2924            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    2925            0 :         })
    2926            0 :         .await
    2927            0 :         .expect("cannot drop self.state while on a &self method");
    2928            0 : 
    2929            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    2930            0 :         self.set_broken_no_wait(reason)
    2931            0 :     }
    2932              : 
    2933            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    2934            0 :         let reason = reason.to_string();
    2935            0 :         self.state.send_modify(|current_state| {
    2936            0 :             match *current_state {
    2937              :                 TenantState::Activating(_) | TenantState::Attaching => {
    2938            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    2939              :                 }
    2940              :                 TenantState::Active => {
    2941            0 :                     if cfg!(feature = "testing") {
    2942            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    2943            0 :                         *current_state = TenantState::broken_from_reason(reason);
    2944              :                     } else {
    2945            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    2946              :                     }
    2947              :                 }
    2948              :                 TenantState::Broken { .. } => {
    2949            0 :                     warn!("Tenant is already in Broken state");
    2950              :                 }
    2951              :                 // This is the only "expected" path, any other path is a bug.
    2952              :                 TenantState::Stopping { .. } => {
    2953            0 :                     warn!(
    2954            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    2955              :                         reason
    2956              :                     );
    2957            0 :                     *current_state = TenantState::broken_from_reason(reason);
    2958              :                 }
    2959              :            }
    2960            0 :         });
    2961            0 :     }
    2962              : 
    2963            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    2964            0 :         self.state.subscribe()
    2965            0 :     }
    2966              : 
    2967              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    2968              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    2969            0 :     pub(crate) fn activate_now(&self) {
    2970            0 :         self.activate_now_sem.add_permits(1);
    2971            0 :     }
    2972              : 
    2973            0 :     pub(crate) async fn wait_to_become_active(
    2974            0 :         &self,
    2975            0 :         timeout: Duration,
    2976            0 :     ) -> Result<(), GetActiveTenantError> {
    2977            0 :         let mut receiver = self.state.subscribe();
    2978              :         loop {
    2979            0 :             let current_state = receiver.borrow_and_update().clone();
    2980            0 :             match current_state {
    2981              :                 TenantState::Attaching | TenantState::Activating(_) => {
    2982              :                     // in these states, there's a chance that we can reach ::Active
    2983            0 :                     self.activate_now();
    2984            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    2985            0 :                         Ok(r) => {
    2986            0 :                             r.map_err(
    2987            0 :                             |_e: tokio::sync::watch::error::RecvError|
    2988              :                                 // Tenant existed but was dropped: report it as non-existent
    2989            0 :                                 GetActiveTenantError::NotFound(GetTenantError::NotFound(self.tenant_shard_id.tenant_id))
    2990            0 :                         )?
    2991              :                         }
    2992              :                         Err(TimeoutCancellableError::Cancelled) => {
    2993            0 :                             return Err(GetActiveTenantError::Cancelled);
    2994              :                         }
    2995              :                         Err(TimeoutCancellableError::Timeout) => {
    2996            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    2997            0 :                                 latest_state: Some(self.current_state()),
    2998            0 :                                 wait_time: timeout,
    2999            0 :                             });
    3000              :                         }
    3001              :                     }
    3002              :                 }
    3003              :                 TenantState::Active { .. } => {
    3004            0 :                     return Ok(());
    3005              :                 }
    3006            0 :                 TenantState::Broken { reason, .. } => {
    3007            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3008            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3009            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3010              :                 }
    3011              :                 TenantState::Stopping { .. } => {
    3012              :                     // There's no chance the tenant can transition back into ::Active
    3013            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3014              :                 }
    3015              :             }
    3016              :         }
    3017            0 :     }
    3018              : 
    3019            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3020            0 :         self.tenant_conf.load().location.attach_mode
    3021            0 :     }
    3022              : 
    3023              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3024              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3025              :     /// rare external API calls, like a reconciliation at startup.
    3026            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3027            0 :         let conf = self.tenant_conf.load();
    3028              : 
    3029            0 :         let location_config_mode = match conf.location.attach_mode {
    3030            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3031            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3032            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3033              :         };
    3034              : 
    3035              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3036            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3037            0 : 
    3038            0 :         models::LocationConfig {
    3039            0 :             mode: location_config_mode,
    3040            0 :             generation: self.generation.into(),
    3041            0 :             secondary_conf: None,
    3042            0 :             shard_number: self.shard_identity.number.0,
    3043            0 :             shard_count: self.shard_identity.count.literal(),
    3044            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3045            0 :             tenant_conf: tenant_config,
    3046            0 :         }
    3047            0 :     }
    3048              : 
    3049            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3050            0 :         &self.tenant_shard_id
    3051            0 :     }
    3052              : 
    3053            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3054            0 :         self.shard_identity.stripe_size
    3055            0 :     }
    3056              : 
    3057            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3058            0 :         self.generation
    3059            0 :     }
    3060              : 
    3061              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3062              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3063              :     /// resetting this tenant to a valid state if we fail.
    3064            0 :     pub(crate) async fn split_prepare(
    3065            0 :         &self,
    3066            0 :         child_shards: &Vec<TenantShardId>,
    3067            0 :     ) -> anyhow::Result<()> {
    3068            0 :         let (timelines, offloaded) = {
    3069            0 :             let timelines = self.timelines.lock().unwrap();
    3070            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3071            0 :             (timelines.clone(), offloaded.clone())
    3072            0 :         };
    3073            0 :         let timelines_iter = timelines
    3074            0 :             .values()
    3075            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3076            0 :             .chain(
    3077            0 :                 offloaded
    3078            0 :                     .values()
    3079            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3080            0 :             );
    3081            0 :         for timeline in timelines_iter {
    3082              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3083              :             // to ensure that they do not start a split if currently in the process of doing these.
    3084              : 
    3085            0 :             let timeline_id = timeline.timeline_id();
    3086              : 
    3087            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3088              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3089              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3090              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3091            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3092            0 :                 timeline
    3093            0 :                     .remote_client
    3094            0 :                     .schedule_index_upload_for_file_changes()?;
    3095            0 :                 timeline.remote_client.wait_completion().await?;
    3096            0 :             }
    3097              : 
    3098            0 :             let remote_client = match timeline {
    3099            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3100            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3101            0 :                     let remote_client = self
    3102            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3103            0 :                     Arc::new(remote_client)
    3104              :                 }
    3105              :             };
    3106              : 
    3107              :             // Shut down the timeline's remote client: this means that the indices we write
    3108              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3109            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3110            0 :             remote_client.shutdown().await;
    3111              : 
    3112              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3113              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3114              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3115              :             // we use here really is the remotely persistent one).
    3116            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3117            0 :             let result = remote_client
    3118            0 :                 .download_index_file(&self.cancel)
    3119            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))
    3120            0 :                 .await?;
    3121            0 :             let index_part = match result {
    3122              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3123            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3124              :                 }
    3125            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3126              :             };
    3127              : 
    3128            0 :             for child_shard in child_shards {
    3129            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3130            0 :                 upload_index_part(
    3131            0 :                     &self.remote_storage,
    3132            0 :                     child_shard,
    3133            0 :                     &timeline_id,
    3134            0 :                     self.generation,
    3135            0 :                     &index_part,
    3136            0 :                     &self.cancel,
    3137            0 :                 )
    3138            0 :                 .await?;
    3139              :             }
    3140              :         }
    3141              : 
    3142            0 :         let tenant_manifest = self.build_tenant_manifest();
    3143            0 :         for child_shard in child_shards {
    3144            0 :             tracing::info!(
    3145            0 :                 "Uploading tenant manifest for child {}",
    3146            0 :                 child_shard.to_index()
    3147              :             );
    3148            0 :             upload_tenant_manifest(
    3149            0 :                 &self.remote_storage,
    3150            0 :                 child_shard,
    3151            0 :                 self.generation,
    3152            0 :                 &tenant_manifest,
    3153            0 :                 &self.cancel,
    3154            0 :             )
    3155            0 :             .await?;
    3156              :         }
    3157              : 
    3158            0 :         Ok(())
    3159            0 :     }
    3160              : 
    3161            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3162            0 :         let mut result = TopTenantShardItem {
    3163            0 :             id: self.tenant_shard_id,
    3164            0 :             resident_size: 0,
    3165            0 :             physical_size: 0,
    3166            0 :             max_logical_size: 0,
    3167            0 :         };
    3168              : 
    3169            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3170            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3171            0 : 
    3172            0 :             result.physical_size += timeline
    3173            0 :                 .remote_client
    3174            0 :                 .metrics
    3175            0 :                 .remote_physical_size_gauge
    3176            0 :                 .get();
    3177            0 :             result.max_logical_size = std::cmp::max(
    3178            0 :                 result.max_logical_size,
    3179            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3180            0 :             );
    3181            0 :         }
    3182              : 
    3183            0 :         result
    3184            0 :     }
    3185              : }
    3186              : 
    3187              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3188              : /// perform a topological sort, so that the parent of each timeline comes
    3189              : /// before the children.
    3190              : /// E extracts the ancestor from T
    3191              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3192          190 : fn tree_sort_timelines<T, E>(
    3193          190 :     timelines: HashMap<TimelineId, T>,
    3194          190 :     extractor: E,
    3195          190 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3196          190 : where
    3197          190 :     E: Fn(&T) -> Option<TimelineId>,
    3198          190 : {
    3199          190 :     let mut result = Vec::with_capacity(timelines.len());
    3200          190 : 
    3201          190 :     let mut now = Vec::with_capacity(timelines.len());
    3202          190 :     // (ancestor, children)
    3203          190 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3204          190 :         HashMap::with_capacity(timelines.len());
    3205              : 
    3206          196 :     for (timeline_id, value) in timelines {
    3207            6 :         if let Some(ancestor_id) = extractor(&value) {
    3208            2 :             let children = later.entry(ancestor_id).or_default();
    3209            2 :             children.push((timeline_id, value));
    3210            4 :         } else {
    3211            4 :             now.push((timeline_id, value));
    3212            4 :         }
    3213              :     }
    3214              : 
    3215          196 :     while let Some((timeline_id, metadata)) = now.pop() {
    3216            6 :         result.push((timeline_id, metadata));
    3217              :         // All children of this can be loaded now
    3218            6 :         if let Some(mut children) = later.remove(&timeline_id) {
    3219            2 :             now.append(&mut children);
    3220            4 :         }
    3221              :     }
    3222              : 
    3223              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3224          190 :     if !later.is_empty() {
    3225            0 :         for (missing_id, orphan_ids) in later {
    3226            0 :             for (orphan_id, _) in orphan_ids {
    3227            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3228              :             }
    3229              :         }
    3230            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3231          190 :     }
    3232          190 : 
    3233          190 :     Ok(result)
    3234          190 : }
    3235              : 
    3236              : impl Tenant {
    3237            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3238            0 :         self.tenant_conf.load().tenant_conf.clone()
    3239            0 :     }
    3240              : 
    3241            0 :     pub fn effective_config(&self) -> TenantConf {
    3242            0 :         self.tenant_specific_overrides()
    3243            0 :             .merge(self.conf.default_tenant_conf.clone())
    3244            0 :     }
    3245              : 
    3246            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3247            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3248            0 :         tenant_conf
    3249            0 :             .checkpoint_distance
    3250            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3251            0 :     }
    3252              : 
    3253            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3254            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3255            0 :         tenant_conf
    3256            0 :             .checkpoint_timeout
    3257            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3258            0 :     }
    3259              : 
    3260            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3261            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3262            0 :         tenant_conf
    3263            0 :             .compaction_target_size
    3264            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3265            0 :     }
    3266              : 
    3267            0 :     pub fn get_compaction_period(&self) -> Duration {
    3268            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3269            0 :         tenant_conf
    3270            0 :             .compaction_period
    3271            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3272            0 :     }
    3273              : 
    3274            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3275            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3276            0 :         tenant_conf
    3277            0 :             .compaction_threshold
    3278            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3279            0 :     }
    3280              : 
    3281            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3282            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3283            0 :         tenant_conf
    3284            0 :             .gc_horizon
    3285            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3286            0 :     }
    3287              : 
    3288            0 :     pub fn get_gc_period(&self) -> Duration {
    3289            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3290            0 :         tenant_conf
    3291            0 :             .gc_period
    3292            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3293            0 :     }
    3294              : 
    3295            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3296            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3297            0 :         tenant_conf
    3298            0 :             .image_creation_threshold
    3299            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3300            0 :     }
    3301              : 
    3302            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3303            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3304            0 :         tenant_conf
    3305            0 :             .pitr_interval
    3306            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3307            0 :     }
    3308              : 
    3309            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3310            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3311            0 :         tenant_conf
    3312            0 :             .min_resident_size_override
    3313            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3314            0 :     }
    3315              : 
    3316            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3317            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3318            0 :         let heatmap_period = tenant_conf
    3319            0 :             .heatmap_period
    3320            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3321            0 :         if heatmap_period.is_zero() {
    3322            0 :             None
    3323              :         } else {
    3324            0 :             Some(heatmap_period)
    3325              :         }
    3326            0 :     }
    3327              : 
    3328            4 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3329            4 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3330            4 :         tenant_conf
    3331            4 :             .lsn_lease_length
    3332            4 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3333            4 :     }
    3334              : 
    3335              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3336            0 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3337            0 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3338            0 : 
    3339            0 :         let mut timeline_manifests = timelines_offloaded
    3340            0 :             .iter()
    3341            0 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3342            0 :             .collect::<Vec<_>>();
    3343            0 :         // Sort the manifests so that our output is deterministic
    3344            0 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3345            0 : 
    3346            0 :         TenantManifest {
    3347            0 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3348            0 :             offloaded_timelines: timeline_manifests,
    3349            0 :         }
    3350            0 :     }
    3351              : 
    3352            0 :     pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
    3353            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3354            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3355            0 :         // this race is not possible if both request types come from the storage
    3356            0 :         // controller (as they should!) because an exclusive op lock is required
    3357            0 :         // on the storage controller side.
    3358            0 :         self.tenant_conf.rcu(|inner| {
    3359            0 :             Arc::new(AttachedTenantConf {
    3360            0 :                 tenant_conf: new_tenant_conf.clone(),
    3361            0 :                 location: inner.location,
    3362            0 :                 // Attached location is not changed, no need to update lsn lease deadline.
    3363            0 :                 lsn_lease_deadline: inner.lsn_lease_deadline,
    3364            0 :             })
    3365            0 :         });
    3366            0 : 
    3367            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3368            0 :         // Don't hold self.timelines.lock() during the notifies.
    3369            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3370            0 :         // mutexes in struct Timeline in the future.
    3371            0 :         let timelines = self.list_timelines();
    3372            0 :         for timeline in timelines {
    3373            0 :             timeline.tenant_conf_updated(&new_tenant_conf);
    3374            0 :         }
    3375            0 :     }
    3376              : 
    3377            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3378            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3379            0 : 
    3380            0 :         self.tenant_conf.store(Arc::new(new_conf));
    3381            0 : 
    3382            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3383            0 :         // Don't hold self.timelines.lock() during the notifies.
    3384            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3385            0 :         // mutexes in struct Timeline in the future.
    3386            0 :         let timelines = self.list_timelines();
    3387            0 :         for timeline in timelines {
    3388            0 :             timeline.tenant_conf_updated(&new_tenant_conf);
    3389            0 :         }
    3390            0 :     }
    3391              : 
    3392          190 :     fn get_timeline_get_throttle_config(
    3393          190 :         psconf: &'static PageServerConf,
    3394          190 :         overrides: &TenantConfOpt,
    3395          190 :     ) -> throttle::Config {
    3396          190 :         overrides
    3397          190 :             .timeline_get_throttle
    3398          190 :             .clone()
    3399          190 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3400          190 :     }
    3401              : 
    3402            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3403            0 :         let conf = Self::get_timeline_get_throttle_config(self.conf, new_conf);
    3404            0 :         self.timeline_get_throttle.reconfigure(conf)
    3405            0 :     }
    3406              : 
    3407              :     /// Helper function to create a new Timeline struct.
    3408              :     ///
    3409              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3410              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3411              :     /// map.
    3412              :     ///
    3413              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3414              :     /// and we might not have the ancestor present anymore which is fine for to be
    3415              :     /// deleted timelines.
    3416          414 :     fn create_timeline_struct(
    3417          414 :         &self,
    3418          414 :         new_timeline_id: TimelineId,
    3419          414 :         new_metadata: &TimelineMetadata,
    3420          414 :         ancestor: Option<Arc<Timeline>>,
    3421          414 :         resources: TimelineResources,
    3422          414 :         cause: CreateTimelineCause,
    3423          414 :         create_idempotency: CreateTimelineIdempotency,
    3424          414 :     ) -> anyhow::Result<Arc<Timeline>> {
    3425          414 :         let state = match cause {
    3426              :             CreateTimelineCause::Load => {
    3427          414 :                 let ancestor_id = new_metadata.ancestor_timeline();
    3428          414 :                 anyhow::ensure!(
    3429          414 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    3430            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    3431              :                 );
    3432          414 :                 TimelineState::Loading
    3433              :             }
    3434            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    3435              :         };
    3436              : 
    3437          414 :         let pg_version = new_metadata.pg_version();
    3438          414 : 
    3439          414 :         let timeline = Timeline::new(
    3440          414 :             self.conf,
    3441          414 :             Arc::clone(&self.tenant_conf),
    3442          414 :             new_metadata,
    3443          414 :             ancestor,
    3444          414 :             new_timeline_id,
    3445          414 :             self.tenant_shard_id,
    3446          414 :             self.generation,
    3447          414 :             self.shard_identity,
    3448          414 :             self.walredo_mgr.clone(),
    3449          414 :             resources,
    3450          414 :             pg_version,
    3451          414 :             state,
    3452          414 :             self.attach_wal_lag_cooldown.clone(),
    3453          414 :             create_idempotency,
    3454          414 :             self.cancel.child_token(),
    3455          414 :         );
    3456          414 : 
    3457          414 :         Ok(timeline)
    3458          414 :     }
    3459              : 
    3460              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    3461              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    3462              :     #[allow(clippy::too_many_arguments)]
    3463          190 :     fn new(
    3464          190 :         state: TenantState,
    3465          190 :         conf: &'static PageServerConf,
    3466          190 :         attached_conf: AttachedTenantConf,
    3467          190 :         shard_identity: ShardIdentity,
    3468          190 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    3469          190 :         tenant_shard_id: TenantShardId,
    3470          190 :         remote_storage: GenericRemoteStorage,
    3471          190 :         deletion_queue_client: DeletionQueueClient,
    3472          190 :         l0_flush_global_state: L0FlushGlobalState,
    3473          190 :     ) -> Tenant {
    3474          190 :         debug_assert!(
    3475          190 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    3476              :         );
    3477              : 
    3478          190 :         let (state, mut rx) = watch::channel(state);
    3479          190 : 
    3480          190 :         tokio::spawn(async move {
    3481          190 :             // reflect tenant state in metrics:
    3482          190 :             // - global per tenant state: TENANT_STATE_METRIC
    3483          190 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    3484          190 :             //
    3485          190 :             // set of broken tenants should not have zero counts so that it remains accessible for
    3486          190 :             // alerting.
    3487          190 : 
    3488          190 :             let tid = tenant_shard_id.to_string();
    3489          190 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    3490          190 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    3491              : 
    3492          380 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    3493          380 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    3494          380 :             }
    3495              : 
    3496          190 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    3497          190 : 
    3498          190 :             let is_broken = tuple.1;
    3499          190 :             let mut counted_broken = if is_broken {
    3500              :                 // add the id to the set right away, there should not be any updates on the channel
    3501              :                 // after before tenant is removed, if ever
    3502            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    3503            0 :                 true
    3504              :             } else {
    3505          190 :                 false
    3506              :             };
    3507              : 
    3508              :             loop {
    3509          380 :                 let labels = &tuple.0;
    3510          380 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    3511          380 :                 current.inc();
    3512          380 : 
    3513          380 :                 if rx.changed().await.is_err() {
    3514              :                     // tenant has been dropped
    3515           16 :                     current.dec();
    3516           16 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    3517           16 :                     break;
    3518          190 :                 }
    3519          190 : 
    3520          190 :                 current.dec();
    3521          190 :                 tuple = inspect_state(&rx.borrow_and_update());
    3522          190 : 
    3523          190 :                 let is_broken = tuple.1;
    3524          190 :                 if is_broken && !counted_broken {
    3525            0 :                     counted_broken = true;
    3526            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    3527            0 :                     // access
    3528            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    3529          190 :                 }
    3530              :             }
    3531          190 :         });
    3532          190 : 
    3533          190 :         Tenant {
    3534          190 :             tenant_shard_id,
    3535          190 :             shard_identity,
    3536          190 :             generation: attached_conf.location.generation,
    3537          190 :             conf,
    3538          190 :             // using now here is good enough approximation to catch tenants with really long
    3539          190 :             // activation times.
    3540          190 :             constructed_at: Instant::now(),
    3541          190 :             timelines: Mutex::new(HashMap::new()),
    3542          190 :             timelines_creating: Mutex::new(HashSet::new()),
    3543          190 :             timelines_offloaded: Mutex::new(HashMap::new()),
    3544          190 :             tenant_manifest_upload: Default::default(),
    3545          190 :             gc_cs: tokio::sync::Mutex::new(()),
    3546          190 :             walredo_mgr,
    3547          190 :             remote_storage,
    3548          190 :             deletion_queue_client,
    3549          190 :             state,
    3550          190 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    3551          190 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    3552          190 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    3553          190 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    3554          190 :                 format!("compaction-{tenant_shard_id}"),
    3555          190 :                 5,
    3556          190 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    3557          190 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    3558          190 :                 // use an extremely long backoff.
    3559          190 :                 Some(Duration::from_secs(3600 * 24)),
    3560          190 :             )),
    3561          190 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    3562          190 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    3563          190 :             cancel: CancellationToken::default(),
    3564          190 :             gate: Gate::default(),
    3565          190 :             timeline_get_throttle: Arc::new(throttle::Throttle::new(
    3566          190 :                 Tenant::get_timeline_get_throttle_config(conf, &attached_conf.tenant_conf),
    3567          190 :                 crate::metrics::tenant_throttling::TimelineGet::new(&tenant_shard_id),
    3568          190 :             )),
    3569          190 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    3570          190 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    3571          190 :             gc_block: Default::default(),
    3572          190 :             l0_flush_global_state,
    3573          190 :         }
    3574          190 :     }
    3575              : 
    3576              :     /// Locate and load config
    3577            0 :     pub(super) fn load_tenant_config(
    3578            0 :         conf: &'static PageServerConf,
    3579            0 :         tenant_shard_id: &TenantShardId,
    3580            0 :     ) -> Result<LocationConf, LoadConfigError> {
    3581            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    3582            0 : 
    3583            0 :         info!("loading tenant configuration from {config_path}");
    3584              : 
    3585              :         // load and parse file
    3586            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    3587            0 :             match e.kind() {
    3588              :                 std::io::ErrorKind::NotFound => {
    3589              :                     // The config should almost always exist for a tenant directory:
    3590              :                     //  - When attaching a tenant, the config is the first thing we write
    3591              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    3592              :                     //    before deleting contents.
    3593              :                     //
    3594              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    3595              :                     // between creating directory and writing config.  Callers should handle that as if the
    3596              :                     // directory didn't exist.
    3597              : 
    3598            0 :                     LoadConfigError::NotFound(config_path)
    3599              :                 }
    3600              :                 _ => {
    3601              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    3602              :                     // that we cannot cleanly recover
    3603            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    3604              :                 }
    3605              :             }
    3606            0 :         })?;
    3607              : 
    3608            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    3609            0 :     }
    3610              : 
    3611            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    3612              :     pub(super) async fn persist_tenant_config(
    3613              :         conf: &'static PageServerConf,
    3614              :         tenant_shard_id: &TenantShardId,
    3615              :         location_conf: &LocationConf,
    3616              :     ) -> std::io::Result<()> {
    3617              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    3618              : 
    3619              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    3620              :     }
    3621              : 
    3622            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    3623              :     pub(super) async fn persist_tenant_config_at(
    3624              :         tenant_shard_id: &TenantShardId,
    3625              :         config_path: &Utf8Path,
    3626              :         location_conf: &LocationConf,
    3627              :     ) -> std::io::Result<()> {
    3628              :         debug!("persisting tenantconf to {config_path}");
    3629              : 
    3630              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    3631              : #  It is read in case of pageserver restart.
    3632              : "#
    3633              :         .to_string();
    3634              : 
    3635            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    3636            0 :             Err(std::io::Error::new(
    3637            0 :                 std::io::ErrorKind::Other,
    3638            0 :                 "tenant-config-before-write",
    3639            0 :             ))
    3640            0 :         });
    3641              : 
    3642              :         // Convert the config to a toml file.
    3643              :         conf_content +=
    3644              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    3645              : 
    3646              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    3647              : 
    3648              :         let conf_content = conf_content.into_bytes();
    3649              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    3650              :     }
    3651              : 
    3652              :     //
    3653              :     // How garbage collection works:
    3654              :     //
    3655              :     //                    +--bar------------->
    3656              :     //                   /
    3657              :     //             +----+-----foo---------------->
    3658              :     //            /
    3659              :     // ----main--+-------------------------->
    3660              :     //                \
    3661              :     //                 +-----baz-------->
    3662              :     //
    3663              :     //
    3664              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    3665              :     //    `gc_infos` are being refreshed
    3666              :     // 2. Scan collected timelines, and on each timeline, make note of the
    3667              :     //    all the points where other timelines have been branched off.
    3668              :     //    We will refrain from removing page versions at those LSNs.
    3669              :     // 3. For each timeline, scan all layer files on the timeline.
    3670              :     //    Remove all files for which a newer file exists and which
    3671              :     //    don't cover any branch point LSNs.
    3672              :     //
    3673              :     // TODO:
    3674              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    3675              :     //   don't need to keep that in the parent anymore. But currently
    3676              :     //   we do.
    3677            4 :     async fn gc_iteration_internal(
    3678            4 :         &self,
    3679            4 :         target_timeline_id: Option<TimelineId>,
    3680            4 :         horizon: u64,
    3681            4 :         pitr: Duration,
    3682            4 :         cancel: &CancellationToken,
    3683            4 :         ctx: &RequestContext,
    3684            4 :     ) -> Result<GcResult, GcError> {
    3685            4 :         let mut totals: GcResult = Default::default();
    3686            4 :         let now = Instant::now();
    3687              : 
    3688            4 :         let gc_timelines = self
    3689            4 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3690            4 :             .await?;
    3691              : 
    3692            4 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    3693              : 
    3694              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    3695            4 :         if !gc_timelines.is_empty() {
    3696            4 :             info!("{} timelines need GC", gc_timelines.len());
    3697              :         } else {
    3698            0 :             debug!("{} timelines need GC", gc_timelines.len());
    3699              :         }
    3700              : 
    3701              :         // Perform GC for each timeline.
    3702              :         //
    3703              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    3704              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    3705              :         // with branch creation.
    3706              :         //
    3707              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    3708              :         // creation task can run concurrently with timeline's GC iteration.
    3709            8 :         for timeline in gc_timelines {
    3710            4 :             if cancel.is_cancelled() {
    3711              :                 // We were requested to shut down. Stop and return with the progress we
    3712              :                 // made.
    3713            0 :                 break;
    3714            4 :             }
    3715            4 :             let result = match timeline.gc().await {
    3716              :                 Err(GcError::TimelineCancelled) => {
    3717            0 :                     if target_timeline_id.is_some() {
    3718              :                         // If we were targetting this specific timeline, surface cancellation to caller
    3719            0 :                         return Err(GcError::TimelineCancelled);
    3720              :                     } else {
    3721              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    3722              :                         // skip past this and proceed to try GC on other timelines.
    3723            0 :                         continue;
    3724              :                     }
    3725              :                 }
    3726            4 :                 r => r?,
    3727              :             };
    3728            4 :             totals += result;
    3729              :         }
    3730              : 
    3731            4 :         totals.elapsed = now.elapsed();
    3732            4 :         Ok(totals)
    3733            4 :     }
    3734              : 
    3735              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    3736              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    3737              :     /// [`Tenant::get_gc_horizon`].
    3738              :     ///
    3739              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    3740            0 :     pub(crate) async fn refresh_gc_info(
    3741            0 :         &self,
    3742            0 :         cancel: &CancellationToken,
    3743            0 :         ctx: &RequestContext,
    3744            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    3745            0 :         // since this method can now be called at different rates than the configured gc loop, it
    3746            0 :         // might be that these configuration values get applied faster than what it was previously,
    3747            0 :         // since these were only read from the gc task.
    3748            0 :         let horizon = self.get_gc_horizon();
    3749            0 :         let pitr = self.get_pitr_interval();
    3750            0 : 
    3751            0 :         // refresh all timelines
    3752            0 :         let target_timeline_id = None;
    3753            0 : 
    3754            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3755            0 :             .await
    3756            0 :     }
    3757              : 
    3758              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    3759              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    3760              :     ///
    3761              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    3762            0 :     fn initialize_gc_info(
    3763            0 :         &self,
    3764            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    3765            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    3766            0 :     ) {
    3767            0 :         // This function must be called before activation: after activation timeline create/delete operations
    3768            0 :         // might happen, and this function is not safe to run concurrently with those.
    3769            0 :         assert!(!self.is_active());
    3770              : 
    3771              :         // Scan all timelines. For each timeline, remember the timeline ID and
    3772              :         // the branch point where it was created.
    3773            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    3774            0 :             BTreeMap::new();
    3775            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    3776            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    3777            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    3778            0 :                 ancestor_children.push((
    3779            0 :                     timeline_entry.get_ancestor_lsn(),
    3780            0 :                     *timeline_id,
    3781            0 :                     MaybeOffloaded::No,
    3782            0 :                 ));
    3783            0 :             }
    3784            0 :         });
    3785            0 :         timelines_offloaded
    3786            0 :             .iter()
    3787            0 :             .for_each(|(timeline_id, timeline_entry)| {
    3788            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    3789            0 :                     return;
    3790              :                 };
    3791            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    3792            0 :                     return;
    3793              :                 };
    3794            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    3795            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    3796            0 :             });
    3797            0 : 
    3798            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    3799            0 :         let horizon = self.get_gc_horizon();
    3800              : 
    3801              :         // Populate each timeline's GcInfo with information about its child branches
    3802            0 :         for timeline in timelines.values() {
    3803            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    3804            0 :                 .remove(&timeline.timeline_id)
    3805            0 :                 .unwrap_or_default();
    3806            0 : 
    3807            0 :             branchpoints.sort_by_key(|b| b.0);
    3808            0 : 
    3809            0 :             let mut target = timeline.gc_info.write().unwrap();
    3810            0 : 
    3811            0 :             target.retain_lsns = branchpoints;
    3812            0 : 
    3813            0 :             let space_cutoff = timeline
    3814            0 :                 .get_last_record_lsn()
    3815            0 :                 .checked_sub(horizon)
    3816            0 :                 .unwrap_or(Lsn(0));
    3817            0 : 
    3818            0 :             target.cutoffs = GcCutoffs {
    3819            0 :                 space: space_cutoff,
    3820            0 :                 time: Lsn::INVALID,
    3821            0 :             };
    3822            0 :         }
    3823            0 :     }
    3824              : 
    3825            4 :     async fn refresh_gc_info_internal(
    3826            4 :         &self,
    3827            4 :         target_timeline_id: Option<TimelineId>,
    3828            4 :         horizon: u64,
    3829            4 :         pitr: Duration,
    3830            4 :         cancel: &CancellationToken,
    3831            4 :         ctx: &RequestContext,
    3832            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    3833            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    3834            4 :         // currently visible timelines.
    3835            4 :         let timelines = self
    3836            4 :             .timelines
    3837            4 :             .lock()
    3838            4 :             .unwrap()
    3839            4 :             .values()
    3840            4 :             .filter(|tl| match target_timeline_id.as_ref() {
    3841            4 :                 Some(target) => &tl.timeline_id == target,
    3842            0 :                 None => true,
    3843            4 :             })
    3844            4 :             .cloned()
    3845            4 :             .collect::<Vec<_>>();
    3846            4 : 
    3847            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    3848              :             // We were to act on a particular timeline and it wasn't found
    3849            0 :             return Err(GcError::TimelineNotFound);
    3850            4 :         }
    3851            4 : 
    3852            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    3853            4 :             HashMap::with_capacity(timelines.len());
    3854              : 
    3855            4 :         for timeline in timelines.iter() {
    3856            4 :             let cutoff = timeline
    3857            4 :                 .get_last_record_lsn()
    3858            4 :                 .checked_sub(horizon)
    3859            4 :                 .unwrap_or(Lsn(0));
    3860              : 
    3861            4 :             let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
    3862            4 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    3863            4 :             assert!(old.is_none());
    3864              :         }
    3865              : 
    3866            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    3867            0 :             return Err(GcError::TenantCancelled);
    3868            4 :         }
    3869              : 
    3870              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    3871              :         // because that will stall branch creation.
    3872            4 :         let gc_cs = self.gc_cs.lock().await;
    3873              : 
    3874              :         // Ok, we now know all the branch points.
    3875              :         // Update the GC information for each timeline.
    3876            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    3877            8 :         for timeline in timelines {
    3878              :             // We filtered the timeline list above
    3879            4 :             if let Some(target_timeline_id) = target_timeline_id {
    3880            4 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    3881            0 :             }
    3882              : 
    3883              :             {
    3884            4 :                 let mut target = timeline.gc_info.write().unwrap();
    3885            4 : 
    3886            4 :                 // Cull any expired leases
    3887            4 :                 let now = SystemTime::now();
    3888            6 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    3889            4 : 
    3890            4 :                 timeline
    3891            4 :                     .metrics
    3892            4 :                     .valid_lsn_lease_count_gauge
    3893            4 :                     .set(target.leases.len() as u64);
    3894              : 
    3895              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    3896            4 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    3897            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    3898            0 :                         target.within_ancestor_pitr =
    3899            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    3900            0 :                     }
    3901            4 :                 }
    3902              : 
    3903              :                 // Update metrics that depend on GC state
    3904            4 :                 timeline
    3905            4 :                     .metrics
    3906            4 :                     .archival_size
    3907            4 :                     .set(if target.within_ancestor_pitr {
    3908            0 :                         timeline.metrics.current_logical_size_gauge.get()
    3909              :                     } else {
    3910            4 :                         0
    3911              :                     });
    3912            4 :                 timeline.metrics.pitr_history_size.set(
    3913            4 :                     timeline
    3914            4 :                         .get_last_record_lsn()
    3915            4 :                         .checked_sub(target.cutoffs.time)
    3916            4 :                         .unwrap_or(Lsn(0))
    3917            4 :                         .0,
    3918            4 :                 );
    3919              : 
    3920              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    3921              :                 // - this timeline was created while we were finding cutoffs
    3922              :                 // - lsn for timestamp search fails for this timeline repeatedly
    3923            4 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    3924            4 :                     target.cutoffs = cutoffs.clone();
    3925            4 :                 }
    3926              :             }
    3927              : 
    3928            4 :             gc_timelines.push(timeline);
    3929              :         }
    3930            4 :         drop(gc_cs);
    3931            4 :         Ok(gc_timelines)
    3932            4 :     }
    3933              : 
    3934              :     /// A substitute for `branch_timeline` for use in unit tests.
    3935              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    3936              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    3937              :     /// timeline background tasks are launched, except the flush loop.
    3938              :     #[cfg(test)]
    3939          230 :     async fn branch_timeline_test(
    3940          230 :         self: &Arc<Self>,
    3941          230 :         src_timeline: &Arc<Timeline>,
    3942          230 :         dst_id: TimelineId,
    3943          230 :         ancestor_lsn: Option<Lsn>,
    3944          230 :         ctx: &RequestContext,
    3945          230 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    3946          230 :         let tl = self
    3947          230 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    3948          193 :             .await?
    3949          226 :             .into_timeline_for_test();
    3950          226 :         tl.set_state(TimelineState::Active);
    3951          226 :         Ok(tl)
    3952          230 :     }
    3953              : 
    3954              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    3955              :     #[cfg(test)]
    3956              :     #[allow(clippy::too_many_arguments)]
    3957            6 :     pub async fn branch_timeline_test_with_layers(
    3958            6 :         self: &Arc<Self>,
    3959            6 :         src_timeline: &Arc<Timeline>,
    3960            6 :         dst_id: TimelineId,
    3961            6 :         ancestor_lsn: Option<Lsn>,
    3962            6 :         ctx: &RequestContext,
    3963            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    3964            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    3965            6 :         end_lsn: Lsn,
    3966            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    3967              :         use checks::check_valid_layermap;
    3968              :         use itertools::Itertools;
    3969              : 
    3970            6 :         let tline = self
    3971            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    3972            6 :             .await?;
    3973            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    3974            6 :             ancestor_lsn
    3975              :         } else {
    3976            0 :             tline.get_last_record_lsn()
    3977              :         };
    3978            6 :         assert!(end_lsn >= ancestor_lsn);
    3979            6 :         tline.force_advance_lsn(end_lsn);
    3980           12 :         for deltas in delta_layer_desc {
    3981            6 :             tline
    3982            6 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    3983           18 :                 .await?;
    3984              :         }
    3985           10 :         for (lsn, images) in image_layer_desc {
    3986            4 :             tline
    3987            4 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    3988           14 :                 .await?;
    3989              :         }
    3990            6 :         let layer_names = tline
    3991            6 :             .layers
    3992            6 :             .read()
    3993            0 :             .await
    3994            6 :             .layer_map()
    3995            6 :             .unwrap()
    3996            6 :             .iter_historic_layers()
    3997           10 :             .map(|layer| layer.layer_name())
    3998            6 :             .collect_vec();
    3999            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4000            0 :             bail!("invalid layermap: {err}");
    4001            6 :         }
    4002            6 :         Ok(tline)
    4003            6 :     }
    4004              : 
    4005              :     /// Branch an existing timeline.
    4006            0 :     async fn branch_timeline(
    4007            0 :         self: &Arc<Self>,
    4008            0 :         src_timeline: &Arc<Timeline>,
    4009            0 :         dst_id: TimelineId,
    4010            0 :         start_lsn: Option<Lsn>,
    4011            0 :         ctx: &RequestContext,
    4012            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4013            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4014            0 :             .await
    4015            0 :     }
    4016              : 
    4017          230 :     async fn branch_timeline_impl(
    4018          230 :         self: &Arc<Self>,
    4019          230 :         src_timeline: &Arc<Timeline>,
    4020          230 :         dst_id: TimelineId,
    4021          230 :         start_lsn: Option<Lsn>,
    4022          230 :         _ctx: &RequestContext,
    4023          230 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4024          230 :         let src_id = src_timeline.timeline_id;
    4025              : 
    4026              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4027              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4028              :         // valid while we are creating the branch.
    4029          230 :         let _gc_cs = self.gc_cs.lock().await;
    4030              : 
    4031              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4032          230 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4033            2 :             let lsn = src_timeline.get_last_record_lsn();
    4034            2 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4035            2 :             lsn
    4036          230 :         });
    4037              : 
    4038              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4039          230 :         let timeline_create_guard = match self
    4040          230 :             .start_creating_timeline(
    4041          230 :                 dst_id,
    4042          230 :                 CreateTimelineIdempotency::Branch {
    4043          230 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4044          230 :                     ancestor_start_lsn: start_lsn,
    4045          230 :                 },
    4046          230 :             )
    4047          192 :             .await?
    4048              :         {
    4049          230 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4050            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4051            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4052              :             }
    4053              :         };
    4054              : 
    4055              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4056              :         // horizon on the source timeline
    4057              :         //
    4058              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4059              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4060              :         // planned GC cutoff in 'gc_info' is normally larger than
    4061              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4062              :         // changed the GC settings for the tenant to make the PITR window
    4063              :         // larger, but some of the data was already removed by an earlier GC
    4064              :         // iteration.
    4065              : 
    4066              :         // check against last actual 'latest_gc_cutoff' first
    4067          230 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4068          230 :         src_timeline
    4069          230 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4070          230 :             .context(format!(
    4071          230 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4072          230 :                 *latest_gc_cutoff_lsn,
    4073          230 :             ))
    4074          230 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4075              : 
    4076              :         // and then the planned GC cutoff
    4077              :         {
    4078          226 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4079          226 :             let cutoff = gc_info.min_cutoff();
    4080          226 :             if start_lsn < cutoff {
    4081            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4082            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4083            0 :                 )));
    4084          226 :             }
    4085          226 :         }
    4086          226 : 
    4087          226 :         //
    4088          226 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4089          226 :         // so that GC cannot advance the GC cutoff until we are finished.
    4090          226 :         // Proceed with the branch creation.
    4091          226 :         //
    4092          226 : 
    4093          226 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4094          226 :         // the timeline was branched at the current end of the source timeline.
    4095          226 :         let RecordLsn {
    4096          226 :             last: src_last,
    4097          226 :             prev: src_prev,
    4098          226 :         } = src_timeline.get_last_record_rlsn();
    4099          226 :         let dst_prev = if src_last == start_lsn {
    4100          216 :             Some(src_prev)
    4101              :         } else {
    4102           10 :             None
    4103              :         };
    4104              : 
    4105              :         // Create the metadata file, noting the ancestor of the new timeline.
    4106              :         // There is initially no data in it, but all the read-calls know to look
    4107              :         // into the ancestor.
    4108          226 :         let metadata = TimelineMetadata::new(
    4109          226 :             start_lsn,
    4110          226 :             dst_prev,
    4111          226 :             Some(src_id),
    4112          226 :             start_lsn,
    4113          226 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4114          226 :             src_timeline.initdb_lsn,
    4115          226 :             src_timeline.pg_version,
    4116          226 :         );
    4117              : 
    4118          226 :         let uninitialized_timeline = self
    4119          226 :             .prepare_new_timeline(
    4120          226 :                 dst_id,
    4121          226 :                 &metadata,
    4122          226 :                 timeline_create_guard,
    4123          226 :                 start_lsn + 1,
    4124          226 :                 Some(Arc::clone(src_timeline)),
    4125          226 :             )
    4126            0 :             .await?;
    4127              : 
    4128          226 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4129              : 
    4130              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4131              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4132              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4133              :         // could get incorrect information and remove more layers, than needed.
    4134              :         // See also https://github.com/neondatabase/neon/issues/3865
    4135          226 :         new_timeline
    4136          226 :             .remote_client
    4137          226 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4138          226 :             .context("branch initial metadata upload")?;
    4139              : 
    4140              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4141              : 
    4142          226 :         Ok(CreateTimelineResult::Created(new_timeline))
    4143          230 :     }
    4144              : 
    4145              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4146              :     #[cfg(test)]
    4147            2 :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4148              :     pub(crate) async fn bootstrap_timeline_test(
    4149              :         self: &Arc<Self>,
    4150              :         timeline_id: TimelineId,
    4151              :         pg_version: u32,
    4152              :         load_existing_initdb: Option<TimelineId>,
    4153              :         ctx: &RequestContext,
    4154              :     ) -> anyhow::Result<Arc<Timeline>> {
    4155              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4156              :             .await
    4157              :             .map_err(anyhow::Error::new)
    4158            2 :             .map(|r| r.into_timeline_for_test())
    4159              :     }
    4160              : 
    4161              :     /// Get exclusive access to the timeline ID for creation.
    4162              :     ///
    4163              :     /// Timeline-creating code paths must use this function before making changes
    4164              :     /// to in-memory or persistent state.
    4165              :     ///
    4166              :     /// The `state` parameter is a description of the timeline creation operation
    4167              :     /// we intend to perform.
    4168              :     /// If the timeline was already created in the meantime, we check whether this
    4169              :     /// request conflicts or is idempotent , based on `state`.
    4170          414 :     async fn start_creating_timeline(
    4171          414 :         &self,
    4172          414 :         new_timeline_id: TimelineId,
    4173          414 :         idempotency: CreateTimelineIdempotency,
    4174          414 :     ) -> Result<StartCreatingTimelineResult<'_>, CreateTimelineError> {
    4175          414 :         let allow_offloaded = false;
    4176          414 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4177          412 :             Ok(create_guard) => {
    4178          412 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4179          412 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4180              :             }
    4181              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4182              :                 // Creation is in progress, we cannot create it again, and we cannot
    4183              :                 // check if this request matches the existing one, so caller must try
    4184              :                 // again later.
    4185            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4186              :             }
    4187            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4188              :             Err(TimelineExclusionError::AlreadyExists {
    4189            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4190            0 :                 ..
    4191            0 :             }) => {
    4192            0 :                 info!("timeline already exists but is offloaded");
    4193            0 :                 Err(CreateTimelineError::Conflict)
    4194              :             }
    4195              :             Err(TimelineExclusionError::AlreadyExists {
    4196            2 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4197            2 :                 arg,
    4198            2 :             }) => {
    4199            2 :                 {
    4200            2 :                     let existing = &existing.create_idempotency;
    4201            2 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4202            2 :                     debug!("timeline already exists");
    4203              : 
    4204            2 :                     match (existing, &arg) {
    4205              :                         // FailWithConflict => no idempotency check
    4206              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4207              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4208            2 :                             warn!("timeline already exists, failing request");
    4209            2 :                             return Err(CreateTimelineError::Conflict);
    4210              :                         }
    4211              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4212            0 :                         (x, y) if x == y => {
    4213            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4214              :                             // fallthrough
    4215              :                         }
    4216              :                         (_, _) => {
    4217            0 :                             warn!("idempotency conflict, failing request");
    4218            0 :                             return Err(CreateTimelineError::Conflict);
    4219              :                         }
    4220              :                     }
    4221              :                 }
    4222              : 
    4223            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4224              :             }
    4225              :         }
    4226          414 :     }
    4227              : 
    4228            0 :     async fn upload_initdb(
    4229            0 :         &self,
    4230            0 :         timelines_path: &Utf8PathBuf,
    4231            0 :         pgdata_path: &Utf8PathBuf,
    4232            0 :         timeline_id: &TimelineId,
    4233            0 :     ) -> anyhow::Result<()> {
    4234            0 :         let temp_path = timelines_path.join(format!(
    4235            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4236            0 :         ));
    4237            0 : 
    4238            0 :         scopeguard::defer! {
    4239            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4240            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4241            0 :             }
    4242            0 :         }
    4243              : 
    4244            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4245              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4246            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4247            0 :             warn!(
    4248            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4249              :             );
    4250            0 :         }
    4251              : 
    4252            0 :         pausable_failpoint!("before-initdb-upload");
    4253              : 
    4254            0 :         backoff::retry(
    4255            0 :             || async {
    4256            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4257            0 :                     &self.remote_storage,
    4258            0 :                     &self.tenant_shard_id.tenant_id,
    4259            0 :                     timeline_id,
    4260            0 :                     pgdata_zstd.try_clone().await?,
    4261            0 :                     tar_zst_size,
    4262            0 :                     &self.cancel,
    4263              :                 )
    4264            0 :                 .await
    4265            0 :             },
    4266            0 :             |_| false,
    4267            0 :             3,
    4268            0 :             u32::MAX,
    4269            0 :             "persist_initdb_tar_zst",
    4270            0 :             &self.cancel,
    4271            0 :         )
    4272            0 :         .await
    4273            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4274            0 :         .and_then(|x| x)
    4275            0 :     }
    4276              : 
    4277              :     /// - run initdb to init temporary instance and get bootstrap data
    4278              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4279            2 :     async fn bootstrap_timeline(
    4280            2 :         self: &Arc<Self>,
    4281            2 :         timeline_id: TimelineId,
    4282            2 :         pg_version: u32,
    4283            2 :         load_existing_initdb: Option<TimelineId>,
    4284            2 :         ctx: &RequestContext,
    4285            2 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4286            2 :         let timeline_create_guard = match self
    4287            2 :             .start_creating_timeline(
    4288            2 :                 timeline_id,
    4289            2 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4290            2 :             )
    4291            2 :             .await?
    4292              :         {
    4293            2 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4294            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4295            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4296              :             }
    4297              :         };
    4298              : 
    4299              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4300              :         // temporary directory for basebackup files for the given timeline.
    4301              : 
    4302            2 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4303            2 :         let pgdata_path = path_with_suffix_extension(
    4304            2 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4305            2 :             TEMP_FILE_SUFFIX,
    4306            2 :         );
    4307            2 : 
    4308            2 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4309            2 :         // we won't race with other creations or existent timelines with the same path.
    4310            2 :         if pgdata_path.exists() {
    4311            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4312            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4313            0 :             })?;
    4314            2 :         }
    4315              : 
    4316              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4317            2 :         scopeguard::defer! {
    4318            2 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4319            2 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4320            2 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4321            2 :             }
    4322            2 :         }
    4323            2 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4324            2 :             if existing_initdb_timeline_id != timeline_id {
    4325            0 :                 let source_path = &remote_initdb_archive_path(
    4326            0 :                     &self.tenant_shard_id.tenant_id,
    4327            0 :                     &existing_initdb_timeline_id,
    4328            0 :                 );
    4329            0 :                 let dest_path =
    4330            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4331            0 : 
    4332            0 :                 // if this fails, it will get retried by retried control plane requests
    4333            0 :                 self.remote_storage
    4334            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4335            0 :                     .await
    4336            0 :                     .context("copy initdb tar")?;
    4337            2 :             }
    4338            2 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4339            2 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4340            2 :                     self.conf,
    4341            2 :                     &self.remote_storage,
    4342            2 :                     &self.tenant_shard_id,
    4343            2 :                     &existing_initdb_timeline_id,
    4344            2 :                     &self.cancel,
    4345            2 :                 )
    4346          725 :                 .await
    4347            2 :                 .context("download initdb tar")?;
    4348              : 
    4349            2 :             scopeguard::defer! {
    4350            2 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4351            2 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4352            2 :                 }
    4353            2 :             }
    4354            2 : 
    4355            2 :             let buf_read =
    4356            2 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4357            2 :             extract_zst_tarball(&pgdata_path, buf_read)
    4358        10556 :                 .await
    4359            2 :                 .context("extract initdb tar")?;
    4360              :         } else {
    4361              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4362            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4363            0 :                 .await
    4364            0 :                 .context("run initdb")?;
    4365              : 
    4366              :             // Upload the created data dir to S3
    4367            0 :             if self.tenant_shard_id().is_shard_zero() {
    4368            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4369            0 :                     .await?;
    4370            0 :             }
    4371              :         }
    4372            2 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4373            2 : 
    4374            2 :         // Import the contents of the data directory at the initial checkpoint
    4375            2 :         // LSN, and any WAL after that.
    4376            2 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4377            2 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4378            2 :         let new_metadata = TimelineMetadata::new(
    4379            2 :             Lsn(0),
    4380            2 :             None,
    4381            2 :             None,
    4382            2 :             Lsn(0),
    4383            2 :             pgdata_lsn,
    4384            2 :             pgdata_lsn,
    4385            2 :             pg_version,
    4386            2 :         );
    4387            2 :         let raw_timeline = self
    4388            2 :             .prepare_new_timeline(
    4389            2 :                 timeline_id,
    4390            2 :                 &new_metadata,
    4391            2 :                 timeline_create_guard,
    4392            2 :                 pgdata_lsn,
    4393            2 :                 None,
    4394            2 :             )
    4395            0 :             .await?;
    4396              : 
    4397            2 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4398            2 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4399              : 
    4400              :         // Flush the new layer files to disk, before we make the timeline as available to
    4401              :         // the outside world.
    4402              :         //
    4403              :         // Flush loop needs to be spawned in order to be able to flush.
    4404            2 :         unfinished_timeline.maybe_spawn_flush_loop();
    4405            2 : 
    4406            2 :         import_datadir::import_timeline_from_postgres_datadir(
    4407            2 :             unfinished_timeline,
    4408            2 :             &pgdata_path,
    4409            2 :             pgdata_lsn,
    4410            2 :             ctx,
    4411            2 :         )
    4412         9522 :         .await
    4413            2 :         .with_context(|| {
    4414            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    4415            2 :         })?;
    4416              : 
    4417            2 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    4418            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    4419            0 :                 "failpoint before-checkpoint-new-timeline"
    4420            0 :             )))
    4421            2 :         });
    4422              : 
    4423            2 :         unfinished_timeline
    4424            2 :             .freeze_and_flush()
    4425            2 :             .await
    4426            2 :             .with_context(|| {
    4427            0 :                 format!(
    4428            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    4429            0 :                 )
    4430            2 :             })?;
    4431              : 
    4432              :         // All done!
    4433            2 :         let timeline = raw_timeline.finish_creation()?;
    4434              : 
    4435              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4436              : 
    4437            2 :         Ok(CreateTimelineResult::Created(timeline))
    4438            2 :     }
    4439              : 
    4440          408 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    4441          408 :         RemoteTimelineClient::new(
    4442          408 :             self.remote_storage.clone(),
    4443          408 :             self.deletion_queue_client.clone(),
    4444          408 :             self.conf,
    4445          408 :             self.tenant_shard_id,
    4446          408 :             timeline_id,
    4447          408 :             self.generation,
    4448          408 :         )
    4449          408 :     }
    4450              : 
    4451              :     /// Call this before constructing a timeline, to build its required structures
    4452          408 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    4453          408 :         TimelineResources {
    4454          408 :             remote_client: self.build_timeline_remote_client(timeline_id),
    4455          408 :             timeline_get_throttle: self.timeline_get_throttle.clone(),
    4456          408 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    4457          408 :         }
    4458          408 :     }
    4459              : 
    4460              :     /// Creates intermediate timeline structure and its files.
    4461              :     ///
    4462              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    4463              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    4464              :     /// `finish_creation` to insert the Timeline into the timelines map.
    4465          408 :     async fn prepare_new_timeline<'a>(
    4466          408 :         &'a self,
    4467          408 :         new_timeline_id: TimelineId,
    4468          408 :         new_metadata: &TimelineMetadata,
    4469          408 :         create_guard: TimelineCreateGuard<'a>,
    4470          408 :         start_lsn: Lsn,
    4471          408 :         ancestor: Option<Arc<Timeline>>,
    4472          408 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    4473          408 :         let tenant_shard_id = self.tenant_shard_id;
    4474          408 : 
    4475          408 :         let resources = self.build_timeline_resources(new_timeline_id);
    4476          408 :         resources
    4477          408 :             .remote_client
    4478          408 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    4479              : 
    4480          408 :         let timeline_struct = self
    4481          408 :             .create_timeline_struct(
    4482          408 :                 new_timeline_id,
    4483          408 :                 new_metadata,
    4484          408 :                 ancestor,
    4485          408 :                 resources,
    4486          408 :                 CreateTimelineCause::Load,
    4487          408 :                 create_guard.idempotency.clone(),
    4488          408 :             )
    4489          408 :             .context("Failed to create timeline data structure")?;
    4490              : 
    4491          408 :         timeline_struct.init_empty_layer_map(start_lsn);
    4492              : 
    4493          408 :         if let Err(e) = self
    4494          408 :             .create_timeline_files(&create_guard.timeline_path)
    4495            0 :             .await
    4496              :         {
    4497            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    4498            0 :             cleanup_timeline_directory(create_guard);
    4499            0 :             return Err(e);
    4500          408 :         }
    4501          408 : 
    4502          408 :         debug!(
    4503            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    4504              :         );
    4505              : 
    4506          408 :         Ok(UninitializedTimeline::new(
    4507          408 :             self,
    4508          408 :             new_timeline_id,
    4509          408 :             Some((timeline_struct, create_guard)),
    4510          408 :         ))
    4511          408 :     }
    4512              : 
    4513          408 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    4514          408 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    4515              : 
    4516          408 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    4517            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    4518          408 :         });
    4519              : 
    4520          408 :         Ok(())
    4521          408 :     }
    4522              : 
    4523              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    4524              :     /// concurrent attempts to create the same timeline.
    4525              :     ///
    4526              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    4527              :     /// offloaded timelines or not.
    4528          414 :     fn create_timeline_create_guard(
    4529          414 :         &self,
    4530          414 :         timeline_id: TimelineId,
    4531          414 :         idempotency: CreateTimelineIdempotency,
    4532          414 :         allow_offloaded: bool,
    4533          414 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    4534          414 :         let tenant_shard_id = self.tenant_shard_id;
    4535          414 : 
    4536          414 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    4537              : 
    4538          414 :         let create_guard = TimelineCreateGuard::new(
    4539          414 :             self,
    4540          414 :             timeline_id,
    4541          414 :             timeline_path.clone(),
    4542          414 :             idempotency,
    4543          414 :             allow_offloaded,
    4544          414 :         )?;
    4545              : 
    4546              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    4547              :         // for creation.
    4548              :         // A timeline directory should never exist on disk already:
    4549              :         // - a previous failed creation would have cleaned up after itself
    4550              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    4551              :         //
    4552              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    4553              :         // this error may indicate a bug in cleanup on failed creations.
    4554          412 :         if timeline_path.exists() {
    4555            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    4556            0 :                 "Timeline directory already exists! This is a bug."
    4557            0 :             )));
    4558          412 :         }
    4559          412 : 
    4560          412 :         Ok(create_guard)
    4561          414 :     }
    4562              : 
    4563              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    4564              :     ///
    4565              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    4566            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    4567              :     pub async fn gather_size_inputs(
    4568              :         &self,
    4569              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    4570              :         // (only if it is shorter than the real cutoff).
    4571              :         max_retention_period: Option<u64>,
    4572              :         cause: LogicalSizeCalculationCause,
    4573              :         cancel: &CancellationToken,
    4574              :         ctx: &RequestContext,
    4575              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    4576              :         let logical_sizes_at_once = self
    4577              :             .conf
    4578              :             .concurrent_tenant_size_logical_size_queries
    4579              :             .inner();
    4580              : 
    4581              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    4582              :         //
    4583              :         // But the only case where we need to run multiple of these at once is when we
    4584              :         // request a size for a tenant manually via API, while another background calculation
    4585              :         // is in progress (which is not a common case).
    4586              :         //
    4587              :         // See more for on the issue #2748 condenced out of the initial PR review.
    4588              :         let mut shared_cache = tokio::select! {
    4589              :             locked = self.cached_logical_sizes.lock() => locked,
    4590              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    4591              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    4592              :         };
    4593              : 
    4594              :         size::gather_inputs(
    4595              :             self,
    4596              :             logical_sizes_at_once,
    4597              :             max_retention_period,
    4598              :             &mut shared_cache,
    4599              :             cause,
    4600              :             cancel,
    4601              :             ctx,
    4602              :         )
    4603              :         .await
    4604              :     }
    4605              : 
    4606              :     /// Calculate synthetic tenant size and cache the result.
    4607              :     /// This is periodically called by background worker.
    4608              :     /// result is cached in tenant struct
    4609            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    4610              :     pub async fn calculate_synthetic_size(
    4611              :         &self,
    4612              :         cause: LogicalSizeCalculationCause,
    4613              :         cancel: &CancellationToken,
    4614              :         ctx: &RequestContext,
    4615              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    4616              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    4617              : 
    4618              :         let size = inputs.calculate();
    4619              : 
    4620              :         self.set_cached_synthetic_size(size);
    4621              : 
    4622              :         Ok(size)
    4623              :     }
    4624              : 
    4625              :     /// Cache given synthetic size and update the metric value
    4626            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    4627            0 :         self.cached_synthetic_tenant_size
    4628            0 :             .store(size, Ordering::Relaxed);
    4629            0 : 
    4630            0 :         // Only shard zero should be calculating synthetic sizes
    4631            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    4632              : 
    4633            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    4634            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    4635            0 :             .unwrap()
    4636            0 :             .set(size);
    4637            0 :     }
    4638              : 
    4639            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    4640            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    4641            0 :     }
    4642              : 
    4643              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    4644              :     ///
    4645              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    4646              :     /// from an external API handler.
    4647              :     ///
    4648              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    4649              :     /// still bounded by tenant/timeline shutdown.
    4650            0 :     #[tracing::instrument(skip_all)]
    4651              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    4652              :         let timelines = self.timelines.lock().unwrap().clone();
    4653              : 
    4654            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    4655            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    4656            0 :             timeline.freeze_and_flush().await?;
    4657            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    4658            0 :             timeline.remote_client.wait_completion().await?;
    4659              : 
    4660            0 :             Ok(())
    4661            0 :         }
    4662              : 
    4663              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    4664              :         // aborted when this function's future is cancelled: they should stay alive
    4665              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    4666              :         // before Timeline shutdown completes.
    4667              :         let mut results = FuturesUnordered::new();
    4668              : 
    4669              :         for (_timeline_id, timeline) in timelines {
    4670              :             // Run each timeline's flush in a task holding the timeline's gate: this
    4671              :             // means that if this function's future is cancelled, the Timeline shutdown
    4672              :             // will still wait for any I/O in here to complete.
    4673              :             let Ok(gate) = timeline.gate.enter() else {
    4674              :                 continue;
    4675              :             };
    4676            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    4677              :             results.push(jh);
    4678              :         }
    4679              : 
    4680              :         while let Some(r) = results.next().await {
    4681              :             if let Err(e) = r {
    4682              :                 if !e.is_cancelled() && !e.is_panic() {
    4683              :                     tracing::error!("unexpected join error: {e:?}");
    4684              :                 }
    4685              :             }
    4686              :         }
    4687              : 
    4688              :         // The flushes we did above were just writes, but the Tenant might have had
    4689              :         // pending deletions as well from recent compaction/gc: we want to flush those
    4690              :         // as well.  This requires flushing the global delete queue.  This is cheap
    4691              :         // because it's typically a no-op.
    4692              :         match self.deletion_queue_client.flush_execute().await {
    4693              :             Ok(_) => {}
    4694              :             Err(DeletionQueueError::ShuttingDown) => {}
    4695              :         }
    4696              : 
    4697              :         Ok(())
    4698              :     }
    4699              : 
    4700            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    4701            0 :         self.tenant_conf.load().tenant_conf.clone()
    4702            0 :     }
    4703              : 
    4704              :     /// How much local storage would this tenant like to have?  It can cope with
    4705              :     /// less than this (via eviction and on-demand downloads), but this function enables
    4706              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    4707              :     /// by keeping important things on local disk.
    4708              :     ///
    4709              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    4710              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    4711              :     /// actually use more than they report here.
    4712            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    4713            0 :         let timelines = self.timelines.lock().unwrap();
    4714            0 : 
    4715            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    4716            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    4717            0 :         // of them is used actively enough to occupy space on disk.
    4718            0 :         timelines
    4719            0 :             .values()
    4720            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    4721            0 :             .max()
    4722            0 :             .unwrap_or(0)
    4723            0 :     }
    4724              : 
    4725              :     /// Serialize and write the latest TenantManifest to remote storage.
    4726            0 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    4727              :         // Only one manifest write may be done at at time, and the contents of the manifest
    4728              :         // must be loaded while holding this lock. This makes it safe to call this function
    4729              :         // from anywhere without worrying about colliding updates.
    4730            0 :         let mut guard = tokio::select! {
    4731            0 :             g = self.tenant_manifest_upload.lock() => {
    4732            0 :                 g
    4733              :             },
    4734            0 :             _ = self.cancel.cancelled() => {
    4735            0 :                 return Err(TenantManifestError::Cancelled);
    4736              :             }
    4737              :         };
    4738              : 
    4739            0 :         let manifest = self.build_tenant_manifest();
    4740            0 :         if Some(&manifest) == (*guard).as_ref() {
    4741              :             // Optimisation: skip uploads that don't change anything.
    4742            0 :             return Ok(());
    4743            0 :         }
    4744            0 : 
    4745            0 :         upload_tenant_manifest(
    4746            0 :             &self.remote_storage,
    4747            0 :             &self.tenant_shard_id,
    4748            0 :             self.generation,
    4749            0 :             &manifest,
    4750            0 :             &self.cancel,
    4751            0 :         )
    4752            0 :         .await
    4753            0 :         .map_err(|e| {
    4754            0 :             if self.cancel.is_cancelled() {
    4755            0 :                 TenantManifestError::Cancelled
    4756              :             } else {
    4757            0 :                 TenantManifestError::RemoteStorage(e)
    4758              :             }
    4759            0 :         })?;
    4760              : 
    4761              :         // Store the successfully uploaded manifest, so that future callers can avoid
    4762              :         // re-uploading the same thing.
    4763            0 :         *guard = Some(manifest);
    4764            0 : 
    4765            0 :         Ok(())
    4766            0 :     }
    4767              : }
    4768              : 
    4769              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    4770              : /// to get bootstrap data for timeline initialization.
    4771            0 : async fn run_initdb(
    4772            0 :     conf: &'static PageServerConf,
    4773            0 :     initdb_target_dir: &Utf8Path,
    4774            0 :     pg_version: u32,
    4775            0 :     cancel: &CancellationToken,
    4776            0 : ) -> Result<(), InitdbError> {
    4777            0 :     let initdb_bin_path = conf
    4778            0 :         .pg_bin_dir(pg_version)
    4779            0 :         .map_err(InitdbError::Other)?
    4780            0 :         .join("initdb");
    4781            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    4782            0 :     info!(
    4783            0 :         "running {} in {}, libdir: {}",
    4784              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    4785              :     );
    4786              : 
    4787            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    4788              : 
    4789            0 :     let mut initdb_command = tokio::process::Command::new(&initdb_bin_path);
    4790            0 :     initdb_command
    4791            0 :         .args(["--pgdata", initdb_target_dir.as_ref()])
    4792            0 :         .args(["--username", &conf.superuser])
    4793            0 :         .args(["--encoding", "utf8"])
    4794            0 :         .args(["--locale", &conf.locale])
    4795            0 :         .arg("--no-instructions")
    4796            0 :         .arg("--no-sync")
    4797            0 :         .env_clear()
    4798            0 :         .env("LD_LIBRARY_PATH", &initdb_lib_dir)
    4799            0 :         .env("DYLD_LIBRARY_PATH", &initdb_lib_dir)
    4800            0 :         .stdin(std::process::Stdio::null())
    4801            0 :         // stdout invocation produces the same output every time, we don't need it
    4802            0 :         .stdout(std::process::Stdio::null())
    4803            0 :         // we would be interested in the stderr output, if there was any
    4804            0 :         .stderr(std::process::Stdio::piped());
    4805            0 : 
    4806            0 :     // Before version 14, only the libc provide was available.
    4807            0 :     if pg_version > 14 {
    4808              :         // Version 17 brought with it a builtin locale provider which only provides
    4809              :         // C and C.UTF-8. While being safer for collation purposes since it is
    4810              :         // guaranteed to be consistent throughout a major release, it is also more
    4811              :         // performant.
    4812            0 :         let locale_provider = if pg_version >= 17 { "builtin" } else { "libc" };
    4813              : 
    4814            0 :         initdb_command.args(["--locale-provider", locale_provider]);
    4815            0 :     }
    4816              : 
    4817            0 :     let initdb_proc = initdb_command.spawn()?;
    4818              : 
    4819              :     // Ideally we'd select here with the cancellation token, but the problem is that
    4820              :     // we can't safely terminate initdb: it launches processes of its own, and killing
    4821              :     // initdb doesn't kill them. After we return from this function, we want the target
    4822              :     // directory to be able to be cleaned up.
    4823              :     // See https://github.com/neondatabase/neon/issues/6385
    4824            0 :     let initdb_output = initdb_proc.wait_with_output().await?;
    4825            0 :     if !initdb_output.status.success() {
    4826            0 :         return Err(InitdbError::Failed(
    4827            0 :             initdb_output.status,
    4828            0 :             initdb_output.stderr,
    4829            0 :         ));
    4830            0 :     }
    4831            0 : 
    4832            0 :     // This isn't true cancellation support, see above. Still return an error to
    4833            0 :     // excercise the cancellation code path.
    4834            0 :     if cancel.is_cancelled() {
    4835            0 :         return Err(InitdbError::Cancelled);
    4836            0 :     }
    4837            0 : 
    4838            0 :     Ok(())
    4839            0 : }
    4840              : 
    4841              : /// Dump contents of a layer file to stdout.
    4842            0 : pub async fn dump_layerfile_from_path(
    4843            0 :     path: &Utf8Path,
    4844            0 :     verbose: bool,
    4845            0 :     ctx: &RequestContext,
    4846            0 : ) -> anyhow::Result<()> {
    4847              :     use std::os::unix::fs::FileExt;
    4848              : 
    4849              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    4850              :     // file.
    4851            0 :     let file = File::open(path)?;
    4852            0 :     let mut header_buf = [0u8; 2];
    4853            0 :     file.read_exact_at(&mut header_buf, 0)?;
    4854              : 
    4855            0 :     match u16::from_be_bytes(header_buf) {
    4856              :         crate::IMAGE_FILE_MAGIC => {
    4857            0 :             ImageLayer::new_for_path(path, file)?
    4858            0 :                 .dump(verbose, ctx)
    4859            0 :                 .await?
    4860              :         }
    4861              :         crate::DELTA_FILE_MAGIC => {
    4862            0 :             DeltaLayer::new_for_path(path, file)?
    4863            0 :                 .dump(verbose, ctx)
    4864            0 :                 .await?
    4865              :         }
    4866            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    4867              :     }
    4868              : 
    4869            0 :     Ok(())
    4870            0 : }
    4871              : 
    4872              : #[cfg(test)]
    4873              : pub(crate) mod harness {
    4874              :     use bytes::{Bytes, BytesMut};
    4875              :     use once_cell::sync::OnceCell;
    4876              :     use pageserver_api::models::ShardParameters;
    4877              :     use pageserver_api::shard::ShardIndex;
    4878              :     use utils::logging;
    4879              : 
    4880              :     use crate::deletion_queue::mock::MockDeletionQueue;
    4881              :     use crate::l0_flush::L0FlushConfig;
    4882              :     use crate::walredo::apply_neon;
    4883              :     use pageserver_api::key::Key;
    4884              :     use pageserver_api::record::NeonWalRecord;
    4885              : 
    4886              :     use super::*;
    4887              :     use hex_literal::hex;
    4888              :     use utils::id::TenantId;
    4889              : 
    4890              :     pub const TIMELINE_ID: TimelineId =
    4891              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    4892              :     pub const NEW_TIMELINE_ID: TimelineId =
    4893              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    4894              : 
    4895              :     /// Convenience function to create a page image with given string as the only content
    4896      5028729 :     pub fn test_img(s: &str) -> Bytes {
    4897      5028729 :         let mut buf = BytesMut::new();
    4898      5028729 :         buf.extend_from_slice(s.as_bytes());
    4899      5028729 :         buf.resize(64, 0);
    4900      5028729 : 
    4901      5028729 :         buf.freeze()
    4902      5028729 :     }
    4903              : 
    4904              :     impl From<TenantConf> for TenantConfOpt {
    4905          190 :         fn from(tenant_conf: TenantConf) -> Self {
    4906          190 :             Self {
    4907          190 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    4908          190 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    4909          190 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    4910          190 :                 compaction_period: Some(tenant_conf.compaction_period),
    4911          190 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    4912          190 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    4913          190 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    4914          190 :                 gc_period: Some(tenant_conf.gc_period),
    4915          190 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    4916          190 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    4917          190 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    4918          190 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    4919          190 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    4920          190 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    4921          190 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    4922          190 :                 evictions_low_residence_duration_metric_threshold: Some(
    4923          190 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    4924          190 :                 ),
    4925          190 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    4926          190 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    4927          190 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    4928          190 :                 image_layer_creation_check_threshold: Some(
    4929          190 :                     tenant_conf.image_layer_creation_check_threshold,
    4930          190 :                 ),
    4931          190 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    4932          190 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    4933          190 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    4934          190 :             }
    4935          190 :         }
    4936              :     }
    4937              : 
    4938              :     pub struct TenantHarness {
    4939              :         pub conf: &'static PageServerConf,
    4940              :         pub tenant_conf: TenantConf,
    4941              :         pub tenant_shard_id: TenantShardId,
    4942              :         pub generation: Generation,
    4943              :         pub shard: ShardIndex,
    4944              :         pub remote_storage: GenericRemoteStorage,
    4945              :         pub remote_fs_dir: Utf8PathBuf,
    4946              :         pub deletion_queue: MockDeletionQueue,
    4947              :     }
    4948              : 
    4949              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    4950              : 
    4951          206 :     pub(crate) fn setup_logging() {
    4952          206 :         LOG_HANDLE.get_or_init(|| {
    4953          194 :             logging::init(
    4954          194 :                 logging::LogFormat::Test,
    4955          194 :                 // enable it in case the tests exercise code paths that use
    4956          194 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    4957          194 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    4958          194 :                 logging::Output::Stdout,
    4959          194 :             )
    4960          194 :             .expect("Failed to init test logging")
    4961          206 :         });
    4962          206 :     }
    4963              : 
    4964              :     impl TenantHarness {
    4965          190 :         pub async fn create_custom(
    4966          190 :             test_name: &'static str,
    4967          190 :             tenant_conf: TenantConf,
    4968          190 :             tenant_id: TenantId,
    4969          190 :             shard_identity: ShardIdentity,
    4970          190 :             generation: Generation,
    4971          190 :         ) -> anyhow::Result<Self> {
    4972          190 :             setup_logging();
    4973          190 : 
    4974          190 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    4975          190 :             let _ = fs::remove_dir_all(&repo_dir);
    4976          190 :             fs::create_dir_all(&repo_dir)?;
    4977              : 
    4978          190 :             let conf = PageServerConf::dummy_conf(repo_dir);
    4979          190 :             // Make a static copy of the config. This can never be free'd, but that's
    4980          190 :             // OK in a test.
    4981          190 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    4982          190 : 
    4983          190 :             let shard = shard_identity.shard_index();
    4984          190 :             let tenant_shard_id = TenantShardId {
    4985          190 :                 tenant_id,
    4986          190 :                 shard_number: shard.shard_number,
    4987          190 :                 shard_count: shard.shard_count,
    4988          190 :             };
    4989          190 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    4990          190 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    4991              : 
    4992              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    4993          190 :             let remote_fs_dir = conf.workdir.join("localfs");
    4994          190 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    4995          190 :             let config = RemoteStorageConfig {
    4996          190 :                 storage: RemoteStorageKind::LocalFs {
    4997          190 :                     local_path: remote_fs_dir.clone(),
    4998          190 :                 },
    4999          190 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5000          190 :             };
    5001          190 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5002          190 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5003          190 : 
    5004          190 :             Ok(Self {
    5005          190 :                 conf,
    5006          190 :                 tenant_conf,
    5007          190 :                 tenant_shard_id,
    5008          190 :                 generation,
    5009          190 :                 shard,
    5010          190 :                 remote_storage,
    5011          190 :                 remote_fs_dir,
    5012          190 :                 deletion_queue,
    5013          190 :             })
    5014          190 :         }
    5015              : 
    5016          178 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5017          178 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5018          178 :             // The tests perform them manually if needed.
    5019          178 :             let tenant_conf = TenantConf {
    5020          178 :                 gc_period: Duration::ZERO,
    5021          178 :                 compaction_period: Duration::ZERO,
    5022          178 :                 ..TenantConf::default()
    5023          178 :             };
    5024          178 :             let tenant_id = TenantId::generate();
    5025          178 :             let shard = ShardIdentity::unsharded();
    5026          178 :             Self::create_custom(
    5027          178 :                 test_name,
    5028          178 :                 tenant_conf,
    5029          178 :                 tenant_id,
    5030          178 :                 shard,
    5031          178 :                 Generation::new(0xdeadbeef),
    5032          178 :             )
    5033            0 :             .await
    5034          178 :         }
    5035              : 
    5036           20 :         pub fn span(&self) -> tracing::Span {
    5037           20 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5038           20 :         }
    5039              : 
    5040          190 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5041          190 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5042          190 :             (
    5043          190 :                 self.do_try_load(&ctx)
    5044         1903 :                     .await
    5045          190 :                     .expect("failed to load test tenant"),
    5046          190 :                 ctx,
    5047          190 :             )
    5048          190 :         }
    5049              : 
    5050          190 :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5051              :         pub(crate) async fn do_try_load(
    5052              :             &self,
    5053              :             ctx: &RequestContext,
    5054              :         ) -> anyhow::Result<Arc<Tenant>> {
    5055              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5056              : 
    5057              :             let tenant = Arc::new(Tenant::new(
    5058              :                 TenantState::Attaching,
    5059              :                 self.conf,
    5060              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5061              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5062              :                     self.generation,
    5063              :                     &ShardParameters::default(),
    5064              :                 ))
    5065              :                 .unwrap(),
    5066              :                 // This is a legacy/test code path: sharding isn't supported here.
    5067              :                 ShardIdentity::unsharded(),
    5068              :                 Some(walredo_mgr),
    5069              :                 self.tenant_shard_id,
    5070              :                 self.remote_storage.clone(),
    5071              :                 self.deletion_queue.new_client(),
    5072              :                 // TODO: ideally we should run all unit tests with both configs
    5073              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5074              :             ));
    5075              : 
    5076              :             let preload = tenant
    5077              :                 .preload(&self.remote_storage, CancellationToken::new())
    5078              :                 .await?;
    5079              :             tenant.attach(Some(preload), ctx).await?;
    5080              : 
    5081              :             tenant.state.send_replace(TenantState::Active);
    5082              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5083              :                 timeline.set_state(TimelineState::Active);
    5084              :             }
    5085              :             Ok(tenant)
    5086              :         }
    5087              : 
    5088            2 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5089            2 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5090            2 :         }
    5091              :     }
    5092              : 
    5093              :     // Mock WAL redo manager that doesn't do much
    5094              :     pub(crate) struct TestRedoManager;
    5095              : 
    5096              :     impl TestRedoManager {
    5097              :         /// # Cancel-Safety
    5098              :         ///
    5099              :         /// This method is cancellation-safe.
    5100          410 :         pub async fn request_redo(
    5101          410 :             &self,
    5102          410 :             key: Key,
    5103          410 :             lsn: Lsn,
    5104          410 :             base_img: Option<(Lsn, Bytes)>,
    5105          410 :             records: Vec<(Lsn, NeonWalRecord)>,
    5106          410 :             _pg_version: u32,
    5107          410 :         ) -> Result<Bytes, walredo::Error> {
    5108          570 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5109          410 :             if records_neon {
    5110              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5111          410 :                 let mut page = match (base_img, records.first()) {
    5112          344 :                     (Some((_lsn, img)), _) => {
    5113          344 :                         let mut page = BytesMut::new();
    5114          344 :                         page.extend_from_slice(&img);
    5115          344 :                         page
    5116              :                     }
    5117           66 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5118              :                     _ => {
    5119            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5120              :                     }
    5121              :                 };
    5122              : 
    5123          980 :                 for (record_lsn, record) in records {
    5124          570 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5125              :                 }
    5126          410 :                 Ok(page.freeze())
    5127              :             } else {
    5128              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5129            0 :                 let s = format!(
    5130            0 :                     "redo for {} to get to {}, with {} and {} records",
    5131            0 :                     key,
    5132            0 :                     lsn,
    5133            0 :                     if base_img.is_some() {
    5134            0 :                         "base image"
    5135              :                     } else {
    5136            0 :                         "no base image"
    5137              :                     },
    5138            0 :                     records.len()
    5139            0 :                 );
    5140            0 :                 println!("{s}");
    5141            0 : 
    5142            0 :                 Ok(test_img(&s))
    5143              :             }
    5144          410 :         }
    5145              :     }
    5146              : }
    5147              : 
    5148              : #[cfg(test)]
    5149              : mod tests {
    5150              :     use std::collections::{BTreeMap, BTreeSet};
    5151              : 
    5152              :     use super::*;
    5153              :     use crate::keyspace::KeySpaceAccum;
    5154              :     use crate::tenant::harness::*;
    5155              :     use crate::tenant::timeline::CompactFlags;
    5156              :     use crate::DEFAULT_PG_VERSION;
    5157              :     use bytes::{Bytes, BytesMut};
    5158              :     use hex_literal::hex;
    5159              :     use itertools::Itertools;
    5160              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
    5161              :     use pageserver_api::keyspace::KeySpace;
    5162              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5163              :     use pageserver_api::value::Value;
    5164              :     use pageserver_compaction::helpers::overlaps_with;
    5165              :     use rand::{thread_rng, Rng};
    5166              :     use storage_layer::PersistentLayerKey;
    5167              :     use tests::storage_layer::ValuesReconstructState;
    5168              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5169              :     use timeline::DeltaLayerTestDesc;
    5170              :     use utils::id::TenantId;
    5171              : 
    5172              :     #[cfg(feature = "testing")]
    5173              :     use pageserver_api::record::NeonWalRecord;
    5174              :     #[cfg(feature = "testing")]
    5175              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5176              :     #[cfg(feature = "testing")]
    5177              :     use timeline::GcInfo;
    5178              : 
    5179              :     static TEST_KEY: Lazy<Key> =
    5180           18 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5181              : 
    5182              :     #[tokio::test]
    5183            2 :     async fn test_basic() -> anyhow::Result<()> {
    5184           20 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5185            2 :         let tline = tenant
    5186            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5187            6 :             .await?;
    5188            2 : 
    5189            2 :         let mut writer = tline.writer().await;
    5190            2 :         writer
    5191            2 :             .put(
    5192            2 :                 *TEST_KEY,
    5193            2 :                 Lsn(0x10),
    5194            2 :                 &Value::Image(test_img("foo at 0x10")),
    5195            2 :                 &ctx,
    5196            2 :             )
    5197            2 :             .await?;
    5198            2 :         writer.finish_write(Lsn(0x10));
    5199            2 :         drop(writer);
    5200            2 : 
    5201            2 :         let mut writer = tline.writer().await;
    5202            2 :         writer
    5203            2 :             .put(
    5204            2 :                 *TEST_KEY,
    5205            2 :                 Lsn(0x20),
    5206            2 :                 &Value::Image(test_img("foo at 0x20")),
    5207            2 :                 &ctx,
    5208            2 :             )
    5209            2 :             .await?;
    5210            2 :         writer.finish_write(Lsn(0x20));
    5211            2 :         drop(writer);
    5212            2 : 
    5213            2 :         assert_eq!(
    5214            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5215            2 :             test_img("foo at 0x10")
    5216            2 :         );
    5217            2 :         assert_eq!(
    5218            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5219            2 :             test_img("foo at 0x10")
    5220            2 :         );
    5221            2 :         assert_eq!(
    5222            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5223            2 :             test_img("foo at 0x20")
    5224            2 :         );
    5225            2 : 
    5226            2 :         Ok(())
    5227            2 :     }
    5228              : 
    5229              :     #[tokio::test]
    5230            2 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5231            2 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5232            2 :             .await?
    5233            2 :             .load()
    5234           20 :             .await;
    5235            2 :         let _ = tenant
    5236            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5237            5 :             .await?;
    5238            2 : 
    5239            2 :         match tenant
    5240            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5241            2 :             .await
    5242            2 :         {
    5243            2 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5244            2 :             Err(e) => assert_eq!(
    5245            2 :                 e.to_string(),
    5246            2 :                 "timeline already exists with different parameters".to_string()
    5247            2 :             ),
    5248            2 :         }
    5249            2 : 
    5250            2 :         Ok(())
    5251            2 :     }
    5252              : 
    5253              :     /// Convenience function to create a page image with given string as the only content
    5254           10 :     pub fn test_value(s: &str) -> Value {
    5255           10 :         let mut buf = BytesMut::new();
    5256           10 :         buf.extend_from_slice(s.as_bytes());
    5257           10 :         Value::Image(buf.freeze())
    5258           10 :     }
    5259              : 
    5260              :     ///
    5261              :     /// Test branch creation
    5262              :     ///
    5263              :     #[tokio::test]
    5264            2 :     async fn test_branch() -> anyhow::Result<()> {
    5265            2 :         use std::str::from_utf8;
    5266            2 : 
    5267           20 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5268            2 :         let tline = tenant
    5269            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5270            6 :             .await?;
    5271            2 :         let mut writer = tline.writer().await;
    5272            2 : 
    5273            2 :         #[allow(non_snake_case)]
    5274            2 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5275            2 :         #[allow(non_snake_case)]
    5276            2 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5277            2 : 
    5278            2 :         // Insert a value on the timeline
    5279            2 :         writer
    5280            2 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5281            2 :             .await?;
    5282            2 :         writer
    5283            2 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5284            2 :             .await?;
    5285            2 :         writer.finish_write(Lsn(0x20));
    5286            2 : 
    5287            2 :         writer
    5288            2 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5289            2 :             .await?;
    5290            2 :         writer.finish_write(Lsn(0x30));
    5291            2 :         writer
    5292            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5293            2 :             .await?;
    5294            2 :         writer.finish_write(Lsn(0x40));
    5295            2 : 
    5296            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5297            2 : 
    5298            2 :         // Branch the history, modify relation differently on the new timeline
    5299            2 :         tenant
    5300            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5301            2 :             .await?;
    5302            2 :         let newtline = tenant
    5303            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5304            2 :             .expect("Should have a local timeline");
    5305            2 :         let mut new_writer = newtline.writer().await;
    5306            2 :         new_writer
    5307            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5308            2 :             .await?;
    5309            2 :         new_writer.finish_write(Lsn(0x40));
    5310            2 : 
    5311            2 :         // Check page contents on both branches
    5312            2 :         assert_eq!(
    5313            2 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5314            2 :             "foo at 0x40"
    5315            2 :         );
    5316            2 :         assert_eq!(
    5317            2 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5318            2 :             "bar at 0x40"
    5319            2 :         );
    5320            2 :         assert_eq!(
    5321            2 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5322            2 :             "foobar at 0x20"
    5323            2 :         );
    5324            2 : 
    5325            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5326            2 : 
    5327            2 :         Ok(())
    5328            2 :     }
    5329              : 
    5330           20 :     async fn make_some_layers(
    5331           20 :         tline: &Timeline,
    5332           20 :         start_lsn: Lsn,
    5333           20 :         ctx: &RequestContext,
    5334           20 :     ) -> anyhow::Result<()> {
    5335           20 :         let mut lsn = start_lsn;
    5336              :         {
    5337           20 :             let mut writer = tline.writer().await;
    5338              :             // Create a relation on the timeline
    5339           20 :             writer
    5340           20 :                 .put(
    5341           20 :                     *TEST_KEY,
    5342           20 :                     lsn,
    5343           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5344           20 :                     ctx,
    5345           20 :                 )
    5346           10 :                 .await?;
    5347           20 :             writer.finish_write(lsn);
    5348           20 :             lsn += 0x10;
    5349           20 :             writer
    5350           20 :                 .put(
    5351           20 :                     *TEST_KEY,
    5352           20 :                     lsn,
    5353           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5354           20 :                     ctx,
    5355           20 :                 )
    5356            0 :                 .await?;
    5357           20 :             writer.finish_write(lsn);
    5358           20 :             lsn += 0x10;
    5359           20 :         }
    5360           20 :         tline.freeze_and_flush().await?;
    5361              :         {
    5362           20 :             let mut writer = tline.writer().await;
    5363           20 :             writer
    5364           20 :                 .put(
    5365           20 :                     *TEST_KEY,
    5366           20 :                     lsn,
    5367           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5368           20 :                     ctx,
    5369           20 :                 )
    5370           10 :                 .await?;
    5371           20 :             writer.finish_write(lsn);
    5372           20 :             lsn += 0x10;
    5373           20 :             writer
    5374           20 :                 .put(
    5375           20 :                     *TEST_KEY,
    5376           20 :                     lsn,
    5377           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5378           20 :                     ctx,
    5379           20 :                 )
    5380            0 :                 .await?;
    5381           20 :             writer.finish_write(lsn);
    5382           20 :         }
    5383           21 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5384           20 :     }
    5385              : 
    5386              :     #[tokio::test(start_paused = true)]
    5387            2 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5388            2 :         let (tenant, ctx) =
    5389            2 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5390            2 :                 .await?
    5391            2 :                 .load()
    5392           20 :                 .await;
    5393            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5394            2 :         // initial transition into AttachedSingle.
    5395            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5396            2 :         tokio::time::resume();
    5397            2 :         let tline = tenant
    5398            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5399            6 :             .await?;
    5400            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5401            2 : 
    5402            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5403            2 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5404            2 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5405            2 :         // below should fail.
    5406            2 :         tenant
    5407            2 :             .gc_iteration(
    5408            2 :                 Some(TIMELINE_ID),
    5409            2 :                 0x10,
    5410            2 :                 Duration::ZERO,
    5411            2 :                 &CancellationToken::new(),
    5412            2 :                 &ctx,
    5413            2 :             )
    5414            2 :             .await?;
    5415            2 : 
    5416            2 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5417            2 :         match tenant
    5418            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5419            2 :             .await
    5420            2 :         {
    5421            2 :             Ok(_) => panic!("branching should have failed"),
    5422            2 :             Err(err) => {
    5423            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5424            2 :                     panic!("wrong error type")
    5425            2 :                 };
    5426            2 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    5427            2 :                 assert!(err
    5428            2 :                     .source()
    5429            2 :                     .unwrap()
    5430            2 :                     .to_string()
    5431            2 :                     .contains("we might've already garbage collected needed data"))
    5432            2 :             }
    5433            2 :         }
    5434            2 : 
    5435            2 :         Ok(())
    5436            2 :     }
    5437              : 
    5438              :     #[tokio::test]
    5439            2 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    5440            2 :         let (tenant, ctx) =
    5441            2 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    5442            2 :                 .await?
    5443            2 :                 .load()
    5444           20 :                 .await;
    5445            2 : 
    5446            2 :         let tline = tenant
    5447            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    5448            6 :             .await?;
    5449            2 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    5450            2 :         match tenant
    5451            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5452            2 :             .await
    5453            2 :         {
    5454            2 :             Ok(_) => panic!("branching should have failed"),
    5455            2 :             Err(err) => {
    5456            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5457            2 :                     panic!("wrong error type");
    5458            2 :                 };
    5459            2 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    5460            2 :                 assert!(&err
    5461            2 :                     .source()
    5462            2 :                     .unwrap()
    5463            2 :                     .to_string()
    5464            2 :                     .contains("is earlier than latest GC cutoff"));
    5465            2 :             }
    5466            2 :         }
    5467            2 : 
    5468            2 :         Ok(())
    5469            2 :     }
    5470              : 
    5471              :     /*
    5472              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    5473              :     // remove the old value, we'd need to work a little harder
    5474              :     #[tokio::test]
    5475              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    5476              :         let repo =
    5477              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    5478              :             .load();
    5479              : 
    5480              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    5481              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5482              : 
    5483              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    5484              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    5485              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    5486              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    5487              :             Ok(_) => panic!("request for page should have failed"),
    5488              :             Err(err) => assert!(err.to_string().contains("not found at")),
    5489              :         }
    5490              :         Ok(())
    5491              :     }
    5492              :      */
    5493              : 
    5494              :     #[tokio::test]
    5495            2 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    5496            2 :         let (tenant, ctx) =
    5497            2 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    5498            2 :                 .await?
    5499            2 :                 .load()
    5500           20 :                 .await;
    5501            2 :         let tline = tenant
    5502            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5503            6 :             .await?;
    5504            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5505            2 : 
    5506            2 :         tenant
    5507            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5508            2 :             .await?;
    5509            2 :         let newtline = tenant
    5510            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5511            2 :             .expect("Should have a local timeline");
    5512            2 : 
    5513            6 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5514            2 : 
    5515            2 :         tline.set_broken("test".to_owned());
    5516            2 : 
    5517            2 :         tenant
    5518            2 :             .gc_iteration(
    5519            2 :                 Some(TIMELINE_ID),
    5520            2 :                 0x10,
    5521            2 :                 Duration::ZERO,
    5522            2 :                 &CancellationToken::new(),
    5523            2 :                 &ctx,
    5524            2 :             )
    5525            2 :             .await?;
    5526            2 : 
    5527            2 :         // The branchpoints should contain all timelines, even ones marked
    5528            2 :         // as Broken.
    5529            2 :         {
    5530            2 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    5531            2 :             assert_eq!(branchpoints.len(), 1);
    5532            2 :             assert_eq!(
    5533            2 :                 branchpoints[0],
    5534            2 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    5535            2 :             );
    5536            2 :         }
    5537            2 : 
    5538            2 :         // You can read the key from the child branch even though the parent is
    5539            2 :         // Broken, as long as you don't need to access data from the parent.
    5540            2 :         assert_eq!(
    5541            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    5542            2 :             test_img(&format!("foo at {}", Lsn(0x70)))
    5543            2 :         );
    5544            2 : 
    5545            2 :         // This needs to traverse to the parent, and fails.
    5546            2 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    5547            2 :         assert!(
    5548            2 :             err.to_string().starts_with(&format!(
    5549            2 :                 "bad state on timeline {}: Broken",
    5550            2 :                 tline.timeline_id
    5551            2 :             )),
    5552            2 :             "{err}"
    5553            2 :         );
    5554            2 : 
    5555            2 :         Ok(())
    5556            2 :     }
    5557              : 
    5558              :     #[tokio::test]
    5559            2 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    5560            2 :         let (tenant, ctx) =
    5561            2 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    5562            2 :                 .await?
    5563            2 :                 .load()
    5564           18 :                 .await;
    5565            2 :         let tline = tenant
    5566            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5567            5 :             .await?;
    5568            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5569            2 : 
    5570            2 :         tenant
    5571            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5572            2 :             .await?;
    5573            2 :         let newtline = tenant
    5574            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5575            2 :             .expect("Should have a local timeline");
    5576            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5577            2 :         tenant
    5578            2 :             .gc_iteration(
    5579            2 :                 Some(TIMELINE_ID),
    5580            2 :                 0x10,
    5581            2 :                 Duration::ZERO,
    5582            2 :                 &CancellationToken::new(),
    5583            2 :                 &ctx,
    5584            2 :             )
    5585            2 :             .await?;
    5586            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    5587            2 : 
    5588            2 :         Ok(())
    5589            2 :     }
    5590              :     #[tokio::test]
    5591            2 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    5592            2 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    5593            2 :             .await?
    5594            2 :             .load()
    5595           19 :             .await;
    5596            2 :         let tline = tenant
    5597            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5598            6 :             .await?;
    5599            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5600            2 : 
    5601            2 :         tenant
    5602            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5603            2 :             .await?;
    5604            2 :         let newtline = tenant
    5605            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5606            2 :             .expect("Should have a local timeline");
    5607            2 : 
    5608            6 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5609            2 : 
    5610            2 :         // run gc on parent
    5611            2 :         tenant
    5612            2 :             .gc_iteration(
    5613            2 :                 Some(TIMELINE_ID),
    5614            2 :                 0x10,
    5615            2 :                 Duration::ZERO,
    5616            2 :                 &CancellationToken::new(),
    5617            2 :                 &ctx,
    5618            2 :             )
    5619            2 :             .await?;
    5620            2 : 
    5621            2 :         // Check that the data is still accessible on the branch.
    5622            2 :         assert_eq!(
    5623            7 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    5624            2 :             test_img(&format!("foo at {}", Lsn(0x40)))
    5625            2 :         );
    5626            2 : 
    5627            2 :         Ok(())
    5628            2 :     }
    5629              : 
    5630              :     #[tokio::test]
    5631            2 :     async fn timeline_load() -> anyhow::Result<()> {
    5632            2 :         const TEST_NAME: &str = "timeline_load";
    5633            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    5634            2 :         {
    5635           20 :             let (tenant, ctx) = harness.load().await;
    5636            2 :             let tline = tenant
    5637            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    5638            6 :                 .await?;
    5639            7 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    5640            2 :             // so that all uploads finish & we can call harness.load() below again
    5641            2 :             tenant
    5642            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    5643            2 :                 .instrument(harness.span())
    5644            2 :                 .await
    5645            2 :                 .ok()
    5646            2 :                 .unwrap();
    5647            2 :         }
    5648            2 : 
    5649           12 :         let (tenant, _ctx) = harness.load().await;
    5650            2 :         tenant
    5651            2 :             .get_timeline(TIMELINE_ID, true)
    5652            2 :             .expect("cannot load timeline");
    5653            2 : 
    5654            2 :         Ok(())
    5655            2 :     }
    5656              : 
    5657              :     #[tokio::test]
    5658            2 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    5659            2 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    5660            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    5661            2 :         // create two timelines
    5662            2 :         {
    5663           20 :             let (tenant, ctx) = harness.load().await;
    5664            2 :             let tline = tenant
    5665            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5666            6 :                 .await?;
    5667            2 : 
    5668            6 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5669            2 : 
    5670            2 :             let child_tline = tenant
    5671            2 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5672            2 :                 .await?;
    5673            2 :             child_tline.set_state(TimelineState::Active);
    5674            2 : 
    5675            2 :             let newtline = tenant
    5676            2 :                 .get_timeline(NEW_TIMELINE_ID, true)
    5677            2 :                 .expect("Should have a local timeline");
    5678            2 : 
    5679            6 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5680            2 : 
    5681            2 :             // so that all uploads finish & we can call harness.load() below again
    5682            2 :             tenant
    5683            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    5684            2 :                 .instrument(harness.span())
    5685            2 :                 .await
    5686            2 :                 .ok()
    5687            2 :                 .unwrap();
    5688            2 :         }
    5689            2 : 
    5690            2 :         // check that both of them are initially unloaded
    5691           34 :         let (tenant, _ctx) = harness.load().await;
    5692            2 : 
    5693            2 :         // check that both, child and ancestor are loaded
    5694            2 :         let _child_tline = tenant
    5695            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5696            2 :             .expect("cannot get child timeline loaded");
    5697            2 : 
    5698            2 :         let _ancestor_tline = tenant
    5699            2 :             .get_timeline(TIMELINE_ID, true)
    5700            2 :             .expect("cannot get ancestor timeline loaded");
    5701            2 : 
    5702            2 :         Ok(())
    5703            2 :     }
    5704              : 
    5705              :     #[tokio::test]
    5706            2 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    5707            2 :         use storage_layer::AsLayerDesc;
    5708            2 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    5709            2 :             .await?
    5710            2 :             .load()
    5711           20 :             .await;
    5712            2 :         let tline = tenant
    5713            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5714            6 :             .await?;
    5715            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5716            2 : 
    5717            2 :         let layer_map = tline.layers.read().await;
    5718            2 :         let level0_deltas = layer_map
    5719            2 :             .layer_map()?
    5720            2 :             .level0_deltas()
    5721            2 :             .iter()
    5722            4 :             .map(|desc| layer_map.get_from_desc(desc))
    5723            2 :             .collect::<Vec<_>>();
    5724            2 : 
    5725            2 :         assert!(!level0_deltas.is_empty());
    5726            2 : 
    5727            6 :         for delta in level0_deltas {
    5728            2 :             // Ensure we are dumping a delta layer here
    5729            4 :             assert!(delta.layer_desc().is_delta);
    5730            8 :             delta.dump(true, &ctx).await.unwrap();
    5731            2 :         }
    5732            2 : 
    5733            2 :         Ok(())
    5734            2 :     }
    5735              : 
    5736              :     #[tokio::test]
    5737            2 :     async fn test_images() -> anyhow::Result<()> {
    5738           20 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    5739            2 :         let tline = tenant
    5740            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5741            6 :             .await?;
    5742            2 : 
    5743            2 :         let mut writer = tline.writer().await;
    5744            2 :         writer
    5745            2 :             .put(
    5746            2 :                 *TEST_KEY,
    5747            2 :                 Lsn(0x10),
    5748            2 :                 &Value::Image(test_img("foo at 0x10")),
    5749            2 :                 &ctx,
    5750            2 :             )
    5751            2 :             .await?;
    5752            2 :         writer.finish_write(Lsn(0x10));
    5753            2 :         drop(writer);
    5754            2 : 
    5755            2 :         tline.freeze_and_flush().await?;
    5756            2 :         tline
    5757            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5758            2 :             .await?;
    5759            2 : 
    5760            2 :         let mut writer = tline.writer().await;
    5761            2 :         writer
    5762            2 :             .put(
    5763            2 :                 *TEST_KEY,
    5764            2 :                 Lsn(0x20),
    5765            2 :                 &Value::Image(test_img("foo at 0x20")),
    5766            2 :                 &ctx,
    5767            2 :             )
    5768            2 :             .await?;
    5769            2 :         writer.finish_write(Lsn(0x20));
    5770            2 :         drop(writer);
    5771            2 : 
    5772            2 :         tline.freeze_and_flush().await?;
    5773            2 :         tline
    5774            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5775            2 :             .await?;
    5776            2 : 
    5777            2 :         let mut writer = tline.writer().await;
    5778            2 :         writer
    5779            2 :             .put(
    5780            2 :                 *TEST_KEY,
    5781            2 :                 Lsn(0x30),
    5782            2 :                 &Value::Image(test_img("foo at 0x30")),
    5783            2 :                 &ctx,
    5784            2 :             )
    5785            2 :             .await?;
    5786            2 :         writer.finish_write(Lsn(0x30));
    5787            2 :         drop(writer);
    5788            2 : 
    5789            2 :         tline.freeze_and_flush().await?;
    5790            2 :         tline
    5791            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5792            2 :             .await?;
    5793            2 : 
    5794            2 :         let mut writer = tline.writer().await;
    5795            2 :         writer
    5796            2 :             .put(
    5797            2 :                 *TEST_KEY,
    5798            2 :                 Lsn(0x40),
    5799            2 :                 &Value::Image(test_img("foo at 0x40")),
    5800            2 :                 &ctx,
    5801            2 :             )
    5802            2 :             .await?;
    5803            2 :         writer.finish_write(Lsn(0x40));
    5804            2 :         drop(writer);
    5805            2 : 
    5806            2 :         tline.freeze_and_flush().await?;
    5807            2 :         tline
    5808            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5809            2 :             .await?;
    5810            2 : 
    5811            2 :         assert_eq!(
    5812            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5813            2 :             test_img("foo at 0x10")
    5814            2 :         );
    5815            2 :         assert_eq!(
    5816            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5817            2 :             test_img("foo at 0x10")
    5818            2 :         );
    5819            2 :         assert_eq!(
    5820            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5821            2 :             test_img("foo at 0x20")
    5822            2 :         );
    5823            2 :         assert_eq!(
    5824            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    5825            2 :             test_img("foo at 0x30")
    5826            2 :         );
    5827            2 :         assert_eq!(
    5828            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    5829            2 :             test_img("foo at 0x40")
    5830            2 :         );
    5831            2 : 
    5832            2 :         Ok(())
    5833            2 :     }
    5834              : 
    5835            4 :     async fn bulk_insert_compact_gc(
    5836            4 :         tenant: &Tenant,
    5837            4 :         timeline: &Arc<Timeline>,
    5838            4 :         ctx: &RequestContext,
    5839            4 :         lsn: Lsn,
    5840            4 :         repeat: usize,
    5841            4 :         key_count: usize,
    5842            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    5843            4 :         let compact = true;
    5844        40718 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    5845            4 :     }
    5846              : 
    5847            8 :     async fn bulk_insert_maybe_compact_gc(
    5848            8 :         tenant: &Tenant,
    5849            8 :         timeline: &Arc<Timeline>,
    5850            8 :         ctx: &RequestContext,
    5851            8 :         mut lsn: Lsn,
    5852            8 :         repeat: usize,
    5853            8 :         key_count: usize,
    5854            8 :         compact: bool,
    5855            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    5856            8 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    5857            8 : 
    5858            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5859            8 :         let mut blknum = 0;
    5860            8 : 
    5861            8 :         // Enforce that key range is monotonously increasing
    5862            8 :         let mut keyspace = KeySpaceAccum::new();
    5863            8 : 
    5864            8 :         let cancel = CancellationToken::new();
    5865            8 : 
    5866            8 :         for _ in 0..repeat {
    5867          400 :             for _ in 0..key_count {
    5868      4000000 :                 test_key.field6 = blknum;
    5869      4000000 :                 let mut writer = timeline.writer().await;
    5870      4000000 :                 writer
    5871      4000000 :                     .put(
    5872      4000000 :                         test_key,
    5873      4000000 :                         lsn,
    5874      4000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5875      4000000 :                         ctx,
    5876      4000000 :                     )
    5877         3426 :                     .await?;
    5878      4000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    5879      4000000 :                 writer.finish_write(lsn);
    5880      4000000 :                 drop(writer);
    5881      4000000 : 
    5882      4000000 :                 keyspace.add_key(test_key);
    5883      4000000 : 
    5884      4000000 :                 lsn = Lsn(lsn.0 + 0x10);
    5885      4000000 :                 blknum += 1;
    5886              :             }
    5887              : 
    5888          400 :             timeline.freeze_and_flush().await?;
    5889          400 :             if compact {
    5890              :                 // this requires timeline to be &Arc<Timeline>
    5891         8618 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    5892          200 :             }
    5893              : 
    5894              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    5895              :             // originally was.
    5896          400 :             let res = tenant
    5897          400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    5898            0 :                 .await?;
    5899              : 
    5900          400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    5901              :         }
    5902              : 
    5903            8 :         Ok(inserted)
    5904            8 :     }
    5905              : 
    5906              :     //
    5907              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    5908              :     // Repeat 50 times.
    5909              :     //
    5910              :     #[tokio::test]
    5911            2 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    5912            2 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    5913           20 :         let (tenant, ctx) = harness.load().await;
    5914            2 :         let tline = tenant
    5915            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5916            5 :             .await?;
    5917            2 : 
    5918            2 :         let lsn = Lsn(0x10);
    5919        20359 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    5920            2 : 
    5921            2 :         Ok(())
    5922            2 :     }
    5923              : 
    5924              :     // Test the vectored get real implementation against a simple sequential implementation.
    5925              :     //
    5926              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    5927              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    5928              :     // grow to the right on the X axis.
    5929              :     //                       [Delta]
    5930              :     //                 [Delta]
    5931              :     //           [Delta]
    5932              :     //    [Delta]
    5933              :     // ------------ Image ---------------
    5934              :     //
    5935              :     // After layer generation we pick the ranges to query as follows:
    5936              :     // 1. The beginning of each delta layer
    5937              :     // 2. At the seam between two adjacent delta layers
    5938              :     //
    5939              :     // There's one major downside to this test: delta layers only contains images,
    5940              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    5941              :     #[tokio::test]
    5942            2 :     async fn test_get_vectored() -> anyhow::Result<()> {
    5943            2 :         let harness = TenantHarness::create("test_get_vectored").await?;
    5944           20 :         let (tenant, ctx) = harness.load().await;
    5945            2 :         let tline = tenant
    5946            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5947            6 :             .await?;
    5948            2 : 
    5949            2 :         let lsn = Lsn(0x10);
    5950        20359 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    5951            2 : 
    5952            2 :         let guard = tline.layers.read().await;
    5953            2 :         let lm = guard.layer_map()?;
    5954            2 : 
    5955            2 :         lm.dump(true, &ctx).await?;
    5956            2 : 
    5957            2 :         let mut reads = Vec::new();
    5958            2 :         let mut prev = None;
    5959           12 :         lm.iter_historic_layers().for_each(|desc| {
    5960           12 :             if !desc.is_delta() {
    5961            2 :                 prev = Some(desc.clone());
    5962            2 :                 return;
    5963           10 :             }
    5964           10 : 
    5965           10 :             let start = desc.key_range.start;
    5966           10 :             let end = desc
    5967           10 :                 .key_range
    5968           10 :                 .start
    5969           10 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    5970           10 :             reads.push(KeySpace {
    5971           10 :                 ranges: vec![start..end],
    5972           10 :             });
    5973            2 : 
    5974           10 :             if let Some(prev) = &prev {
    5975           10 :                 if !prev.is_delta() {
    5976           10 :                     return;
    5977            2 :                 }
    5978            0 : 
    5979            0 :                 let first_range = Key {
    5980            0 :                     field6: prev.key_range.end.field6 - 4,
    5981            0 :                     ..prev.key_range.end
    5982            0 :                 }..prev.key_range.end;
    5983            0 : 
    5984            0 :                 let second_range = desc.key_range.start..Key {
    5985            0 :                     field6: desc.key_range.start.field6 + 4,
    5986            0 :                     ..desc.key_range.start
    5987            0 :                 };
    5988            0 : 
    5989            0 :                 reads.push(KeySpace {
    5990            0 :                     ranges: vec![first_range, second_range],
    5991            0 :                 });
    5992            2 :             };
    5993            2 : 
    5994            2 :             prev = Some(desc.clone());
    5995           12 :         });
    5996            2 : 
    5997            2 :         drop(guard);
    5998            2 : 
    5999            2 :         // Pick a big LSN such that we query over all the changes.
    6000            2 :         let reads_lsn = Lsn(u64::MAX - 1);
    6001            2 : 
    6002           12 :         for read in reads {
    6003           10 :             info!("Doing vectored read on {:?}", read);
    6004            2 : 
    6005           10 :             let vectored_res = tline
    6006           10 :                 .get_vectored_impl(
    6007           10 :                     read.clone(),
    6008           10 :                     reads_lsn,
    6009           10 :                     &mut ValuesReconstructState::new(),
    6010           10 :                     &ctx,
    6011           10 :                 )
    6012           25 :                 .await;
    6013            2 : 
    6014           10 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6015           10 :             let mut expect_missing = false;
    6016           10 :             let mut key = read.start().unwrap();
    6017          330 :             while key != read.end().unwrap() {
    6018          320 :                 if let Some(lsns) = inserted.get(&key) {
    6019          320 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6020          320 :                     match expected_lsn {
    6021          320 :                         Some(lsn) => {
    6022          320 :                             expected_lsns.insert(key, *lsn);
    6023          320 :                         }
    6024            2 :                         None => {
    6025            2 :                             expect_missing = true;
    6026            0 :                             break;
    6027            2 :                         }
    6028            2 :                     }
    6029            2 :                 } else {
    6030            2 :                     expect_missing = true;
    6031            0 :                     break;
    6032            2 :                 }
    6033            2 : 
    6034          320 :                 key = key.next();
    6035            2 :             }
    6036            2 : 
    6037           10 :             if expect_missing {
    6038            2 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6039            2 :             } else {
    6040          320 :                 for (key, image) in vectored_res? {
    6041          320 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6042          320 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6043          320 :                     assert_eq!(image?, expected_image);
    6044            2 :                 }
    6045            2 :             }
    6046            2 :         }
    6047            2 : 
    6048            2 :         Ok(())
    6049            2 :     }
    6050              : 
    6051              :     #[tokio::test]
    6052            2 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6053            2 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6054            2 : 
    6055           20 :         let (tenant, ctx) = harness.load().await;
    6056            2 :         let tline = tenant
    6057            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6058            2 :             .await?;
    6059            2 :         let tline = tline.raw_timeline().unwrap();
    6060            2 : 
    6061            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6062            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6063            2 :         modification.set_lsn(Lsn(0x1008))?;
    6064            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6065            2 :         modification.commit(&ctx).await?;
    6066            2 : 
    6067            2 :         let child_timeline_id = TimelineId::generate();
    6068            2 :         tenant
    6069            2 :             .branch_timeline_test(
    6070            2 :                 tline,
    6071            2 :                 child_timeline_id,
    6072            2 :                 Some(tline.get_last_record_lsn()),
    6073            2 :                 &ctx,
    6074            2 :             )
    6075            2 :             .await?;
    6076            2 : 
    6077            2 :         let child_timeline = tenant
    6078            2 :             .get_timeline(child_timeline_id, true)
    6079            2 :             .expect("Should have the branched timeline");
    6080            2 : 
    6081            2 :         let aux_keyspace = KeySpace {
    6082            2 :             ranges: vec![NON_INHERITED_RANGE],
    6083            2 :         };
    6084            2 :         let read_lsn = child_timeline.get_last_record_lsn();
    6085            2 : 
    6086            2 :         let vectored_res = child_timeline
    6087            2 :             .get_vectored_impl(
    6088            2 :                 aux_keyspace.clone(),
    6089            2 :                 read_lsn,
    6090            2 :                 &mut ValuesReconstructState::new(),
    6091            2 :                 &ctx,
    6092            2 :             )
    6093            2 :             .await;
    6094            2 : 
    6095            2 :         let images = vectored_res?;
    6096            2 :         assert!(images.is_empty());
    6097            2 :         Ok(())
    6098            2 :     }
    6099              : 
    6100              :     // Test that vectored get handles layer gaps correctly
    6101              :     // by advancing into the next ancestor timeline if required.
    6102              :     //
    6103              :     // The test generates timelines that look like the diagram below.
    6104              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6105              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6106              :     //
    6107              :     // ```
    6108              :     //-------------------------------+
    6109              :     //                          ...  |
    6110              :     //               [   L1   ]      |
    6111              :     //     [ / L1   ]                | Child Timeline
    6112              :     // ...                           |
    6113              :     // ------------------------------+
    6114              :     //     [ X L1   ]                | Parent Timeline
    6115              :     // ------------------------------+
    6116              :     // ```
    6117              :     #[tokio::test]
    6118            2 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6119            2 :         let tenant_conf = TenantConf {
    6120            2 :             // Make compaction deterministic
    6121            2 :             gc_period: Duration::ZERO,
    6122            2 :             compaction_period: Duration::ZERO,
    6123            2 :             // Encourage creation of L1 layers
    6124            2 :             checkpoint_distance: 16 * 1024,
    6125            2 :             compaction_target_size: 8 * 1024,
    6126            2 :             ..TenantConf::default()
    6127            2 :         };
    6128            2 : 
    6129            2 :         let harness = TenantHarness::create_custom(
    6130            2 :             "test_get_vectored_key_gap",
    6131            2 :             tenant_conf,
    6132            2 :             TenantId::generate(),
    6133            2 :             ShardIdentity::unsharded(),
    6134            2 :             Generation::new(0xdeadbeef),
    6135            2 :         )
    6136            2 :         .await?;
    6137           20 :         let (tenant, ctx) = harness.load().await;
    6138            2 : 
    6139            2 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6140            2 :         let gap_at_key = current_key.add(100);
    6141            2 :         let mut current_lsn = Lsn(0x10);
    6142            2 : 
    6143            2 :         const KEY_COUNT: usize = 10_000;
    6144            2 : 
    6145            2 :         let timeline_id = TimelineId::generate();
    6146            2 :         let current_timeline = tenant
    6147            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6148            6 :             .await?;
    6149            2 : 
    6150            2 :         current_lsn += 0x100;
    6151            2 : 
    6152            2 :         let mut writer = current_timeline.writer().await;
    6153            2 :         writer
    6154            2 :             .put(
    6155            2 :                 gap_at_key,
    6156            2 :                 current_lsn,
    6157            2 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6158            2 :                 &ctx,
    6159            2 :             )
    6160            2 :             .await?;
    6161            2 :         writer.finish_write(current_lsn);
    6162            2 :         drop(writer);
    6163            2 : 
    6164            2 :         let mut latest_lsns = HashMap::new();
    6165            2 :         latest_lsns.insert(gap_at_key, current_lsn);
    6166            2 : 
    6167            2 :         current_timeline.freeze_and_flush().await?;
    6168            2 : 
    6169            2 :         let child_timeline_id = TimelineId::generate();
    6170            2 : 
    6171            2 :         tenant
    6172            2 :             .branch_timeline_test(
    6173            2 :                 &current_timeline,
    6174            2 :                 child_timeline_id,
    6175            2 :                 Some(current_lsn),
    6176            2 :                 &ctx,
    6177            2 :             )
    6178            2 :             .await?;
    6179            2 :         let child_timeline = tenant
    6180            2 :             .get_timeline(child_timeline_id, true)
    6181            2 :             .expect("Should have the branched timeline");
    6182            2 : 
    6183        20002 :         for i in 0..KEY_COUNT {
    6184        20000 :             if current_key == gap_at_key {
    6185            2 :                 current_key = current_key.next();
    6186            2 :                 continue;
    6187        19998 :             }
    6188        19998 : 
    6189        19998 :             current_lsn += 0x10;
    6190            2 : 
    6191        19998 :             let mut writer = child_timeline.writer().await;
    6192        19998 :             writer
    6193        19998 :                 .put(
    6194        19998 :                     current_key,
    6195        19998 :                     current_lsn,
    6196        19998 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6197        19998 :                     &ctx,
    6198        19998 :                 )
    6199           71 :                 .await?;
    6200        19998 :             writer.finish_write(current_lsn);
    6201        19998 :             drop(writer);
    6202        19998 : 
    6203        19998 :             latest_lsns.insert(current_key, current_lsn);
    6204        19998 :             current_key = current_key.next();
    6205        19998 : 
    6206        19998 :             // Flush every now and then to encourage layer file creation.
    6207        19998 :             if i % 500 == 0 {
    6208           43 :                 child_timeline.freeze_and_flush().await?;
    6209        19958 :             }
    6210            2 :         }
    6211            2 : 
    6212            2 :         child_timeline.freeze_and_flush().await?;
    6213            2 :         let mut flags = EnumSet::new();
    6214            2 :         flags.insert(CompactFlags::ForceRepartition);
    6215            2 :         child_timeline
    6216            2 :             .compact(&CancellationToken::new(), flags, &ctx)
    6217         1757 :             .await?;
    6218            2 : 
    6219            2 :         let key_near_end = {
    6220            2 :             let mut tmp = current_key;
    6221            2 :             tmp.field6 -= 10;
    6222            2 :             tmp
    6223            2 :         };
    6224            2 : 
    6225            2 :         let key_near_gap = {
    6226            2 :             let mut tmp = gap_at_key;
    6227            2 :             tmp.field6 -= 10;
    6228            2 :             tmp
    6229            2 :         };
    6230            2 : 
    6231            2 :         let read = KeySpace {
    6232            2 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6233            2 :         };
    6234            2 :         let results = child_timeline
    6235            2 :             .get_vectored_impl(
    6236            2 :                 read.clone(),
    6237            2 :                 current_lsn,
    6238            2 :                 &mut ValuesReconstructState::new(),
    6239            2 :                 &ctx,
    6240            2 :             )
    6241           16 :             .await?;
    6242            2 : 
    6243           44 :         for (key, img_res) in results {
    6244           42 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6245           42 :             assert_eq!(img_res?, expected);
    6246            2 :         }
    6247            2 : 
    6248            2 :         Ok(())
    6249            2 :     }
    6250              : 
    6251              :     // Test that vectored get descends into ancestor timelines correctly and
    6252              :     // does not return an image that's newer than requested.
    6253              :     //
    6254              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6255              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6256              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6257              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6258              :     // order to avoid returning an image that's too new. The test below constructs such
    6259              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6260              :     // ```
    6261              :     //    LSN
    6262              :     //     ^
    6263              :     //     |
    6264              :     //     |
    6265              :     // 500 | --------------------------------------> branch point
    6266              :     // 400 |        X
    6267              :     // 300 |        X
    6268              :     // 200 | --------------------------------------> requested lsn
    6269              :     // 100 |        X
    6270              :     //     |---------------------------------------> Key
    6271              :     //              |
    6272              :     //              ------> requested key
    6273              :     //
    6274              :     // Legend:
    6275              :     // * X - page images
    6276              :     // ```
    6277              :     #[tokio::test]
    6278            2 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6279            2 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6280           20 :         let (tenant, ctx) = harness.load().await;
    6281            2 : 
    6282            2 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6283            2 :         let end_key = start_key.add(1000);
    6284            2 :         let child_gap_at_key = start_key.add(500);
    6285            2 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6286            2 : 
    6287            2 :         let mut current_lsn = Lsn(0x10);
    6288            2 : 
    6289            2 :         let timeline_id = TimelineId::generate();
    6290            2 :         let parent_timeline = tenant
    6291            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6292            6 :             .await?;
    6293            2 : 
    6294            2 :         current_lsn += 0x100;
    6295            2 : 
    6296            8 :         for _ in 0..3 {
    6297            6 :             let mut key = start_key;
    6298         6006 :             while key < end_key {
    6299         6000 :                 current_lsn += 0x10;
    6300         6000 : 
    6301         6000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6302            2 : 
    6303         6000 :                 let mut writer = parent_timeline.writer().await;
    6304         6000 :                 writer
    6305         6000 :                     .put(
    6306         6000 :                         key,
    6307         6000 :                         current_lsn,
    6308         6000 :                         &Value::Image(test_img(&image_value)),
    6309         6000 :                         &ctx,
    6310         6000 :                     )
    6311            6 :                     .await?;
    6312         6000 :                 writer.finish_write(current_lsn);
    6313         6000 : 
    6314         6000 :                 if key == child_gap_at_key {
    6315            6 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6316         5994 :                 }
    6317            2 : 
    6318         6000 :                 key = key.next();
    6319            2 :             }
    6320            2 : 
    6321            7 :             parent_timeline.freeze_and_flush().await?;
    6322            2 :         }
    6323            2 : 
    6324            2 :         let child_timeline_id = TimelineId::generate();
    6325            2 : 
    6326            2 :         let child_timeline = tenant
    6327            2 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6328            2 :             .await?;
    6329            2 : 
    6330            2 :         let mut key = start_key;
    6331         2002 :         while key < end_key {
    6332         2000 :             if key == child_gap_at_key {
    6333            2 :                 key = key.next();
    6334            2 :                 continue;
    6335         1998 :             }
    6336         1998 : 
    6337         1998 :             current_lsn += 0x10;
    6338            2 : 
    6339         1998 :             let mut writer = child_timeline.writer().await;
    6340         1998 :             writer
    6341         1998 :                 .put(
    6342         1998 :                     key,
    6343         1998 :                     current_lsn,
    6344         1998 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6345         1998 :                     &ctx,
    6346         1998 :                 )
    6347           17 :                 .await?;
    6348         1998 :             writer.finish_write(current_lsn);
    6349         1998 : 
    6350         1998 :             key = key.next();
    6351            2 :         }
    6352            2 : 
    6353            2 :         child_timeline.freeze_and_flush().await?;
    6354            2 : 
    6355            2 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6356            2 :         let mut query_lsns = Vec::new();
    6357            6 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6358           36 :             for offset in lsn_offsets {
    6359           30 :                 query_lsns.push(Lsn(image_lsn
    6360           30 :                     .0
    6361           30 :                     .checked_add_signed(offset)
    6362           30 :                     .expect("Shouldn't overflow")));
    6363           30 :             }
    6364            2 :         }
    6365            2 : 
    6366           32 :         for query_lsn in query_lsns {
    6367           30 :             let results = child_timeline
    6368           30 :                 .get_vectored_impl(
    6369           30 :                     KeySpace {
    6370           30 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6371           30 :                     },
    6372           30 :                     query_lsn,
    6373           30 :                     &mut ValuesReconstructState::new(),
    6374           30 :                     &ctx,
    6375           30 :                 )
    6376           29 :                 .await;
    6377            2 : 
    6378           30 :             let expected_item = parent_gap_lsns
    6379           30 :                 .iter()
    6380           30 :                 .rev()
    6381           68 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6382           30 : 
    6383           30 :             info!(
    6384            2 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6385            2 :                 query_lsn, expected_item
    6386            2 :             );
    6387            2 : 
    6388           30 :             match expected_item {
    6389           26 :                 Some((_, img_value)) => {
    6390           26 :                     let key_results = results.expect("No vectored get error expected");
    6391           26 :                     let key_result = &key_results[&child_gap_at_key];
    6392           26 :                     let returned_img = key_result
    6393           26 :                         .as_ref()
    6394           26 :                         .expect("No page reconstruct error expected");
    6395           26 : 
    6396           26 :                     info!(
    6397            2 :                         "Vectored read at LSN {} returned image {}",
    6398            0 :                         query_lsn,
    6399            0 :                         std::str::from_utf8(returned_img)?
    6400            2 :                     );
    6401           26 :                     assert_eq!(*returned_img, test_img(img_value));
    6402            2 :                 }
    6403            2 :                 None => {
    6404            4 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6405            2 :                 }
    6406            2 :             }
    6407            2 :         }
    6408            2 : 
    6409            2 :         Ok(())
    6410            2 :     }
    6411              : 
    6412              :     #[tokio::test]
    6413            2 :     async fn test_random_updates() -> anyhow::Result<()> {
    6414            2 :         let names_algorithms = [
    6415            2 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    6416            2 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    6417            2 :         ];
    6418            6 :         for (name, algorithm) in names_algorithms {
    6419        96229 :             test_random_updates_algorithm(name, algorithm).await?;
    6420            2 :         }
    6421            2 :         Ok(())
    6422            2 :     }
    6423              : 
    6424            4 :     async fn test_random_updates_algorithm(
    6425            4 :         name: &'static str,
    6426            4 :         compaction_algorithm: CompactionAlgorithm,
    6427            4 :     ) -> anyhow::Result<()> {
    6428            4 :         let mut harness = TenantHarness::create(name).await?;
    6429            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6430            4 :             kind: compaction_algorithm,
    6431            4 :         };
    6432           40 :         let (tenant, ctx) = harness.load().await;
    6433            4 :         let tline = tenant
    6434            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6435           11 :             .await?;
    6436              : 
    6437              :         const NUM_KEYS: usize = 1000;
    6438            4 :         let cancel = CancellationToken::new();
    6439            4 : 
    6440            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6441            4 :         let mut test_key_end = test_key;
    6442            4 :         test_key_end.field6 = NUM_KEYS as u32;
    6443            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    6444            4 : 
    6445            4 :         let mut keyspace = KeySpaceAccum::new();
    6446            4 : 
    6447            4 :         // Track when each page was last modified. Used to assert that
    6448            4 :         // a read sees the latest page version.
    6449            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    6450            4 : 
    6451            4 :         let mut lsn = Lsn(0x10);
    6452              :         #[allow(clippy::needless_range_loop)]
    6453         4004 :         for blknum in 0..NUM_KEYS {
    6454         4000 :             lsn = Lsn(lsn.0 + 0x10);
    6455         4000 :             test_key.field6 = blknum as u32;
    6456         4000 :             let mut writer = tline.writer().await;
    6457         4000 :             writer
    6458         4000 :                 .put(
    6459         4000 :                     test_key,
    6460         4000 :                     lsn,
    6461         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6462         4000 :                     &ctx,
    6463         4000 :                 )
    6464            4 :                 .await?;
    6465         4000 :             writer.finish_write(lsn);
    6466         4000 :             updated[blknum] = lsn;
    6467         4000 :             drop(writer);
    6468         4000 : 
    6469         4000 :             keyspace.add_key(test_key);
    6470              :         }
    6471              : 
    6472          204 :         for _ in 0..50 {
    6473       200200 :             for _ in 0..NUM_KEYS {
    6474       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    6475       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6476       200000 :                 test_key.field6 = blknum as u32;
    6477       200000 :                 let mut writer = tline.writer().await;
    6478       200000 :                 writer
    6479       200000 :                     .put(
    6480       200000 :                         test_key,
    6481       200000 :                         lsn,
    6482       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6483       200000 :                         &ctx,
    6484       200000 :                     )
    6485          198 :                     .await?;
    6486       200000 :                 writer.finish_write(lsn);
    6487       200000 :                 drop(writer);
    6488       200000 :                 updated[blknum] = lsn;
    6489              :             }
    6490              : 
    6491              :             // Read all the blocks
    6492       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6493       200000 :                 test_key.field6 = blknum as u32;
    6494       200000 :                 assert_eq!(
    6495       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    6496       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6497              :                 );
    6498              :             }
    6499              : 
    6500              :             // Perform a cycle of flush, and GC
    6501          202 :             tline.freeze_and_flush().await?;
    6502          200 :             tenant
    6503          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    6504            0 :                 .await?;
    6505              :         }
    6506              : 
    6507            4 :         Ok(())
    6508            4 :     }
    6509              : 
    6510              :     #[tokio::test]
    6511            2 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    6512            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    6513            2 :             .await?
    6514            2 :             .load()
    6515           20 :             .await;
    6516            2 :         let mut tline = tenant
    6517            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6518            6 :             .await?;
    6519            2 : 
    6520            2 :         const NUM_KEYS: usize = 1000;
    6521            2 : 
    6522            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6523            2 : 
    6524            2 :         let mut keyspace = KeySpaceAccum::new();
    6525            2 : 
    6526            2 :         let cancel = CancellationToken::new();
    6527            2 : 
    6528            2 :         // Track when each page was last modified. Used to assert that
    6529            2 :         // a read sees the latest page version.
    6530            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    6531            2 : 
    6532            2 :         let mut lsn = Lsn(0x10);
    6533            2 :         #[allow(clippy::needless_range_loop)]
    6534         2002 :         for blknum in 0..NUM_KEYS {
    6535         2000 :             lsn = Lsn(lsn.0 + 0x10);
    6536         2000 :             test_key.field6 = blknum as u32;
    6537         2000 :             let mut writer = tline.writer().await;
    6538         2000 :             writer
    6539         2000 :                 .put(
    6540         2000 :                     test_key,
    6541         2000 :                     lsn,
    6542         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6543         2000 :                     &ctx,
    6544         2000 :                 )
    6545            2 :                 .await?;
    6546         2000 :             writer.finish_write(lsn);
    6547         2000 :             updated[blknum] = lsn;
    6548         2000 :             drop(writer);
    6549         2000 : 
    6550         2000 :             keyspace.add_key(test_key);
    6551            2 :         }
    6552            2 : 
    6553          102 :         for _ in 0..50 {
    6554          100 :             let new_tline_id = TimelineId::generate();
    6555          100 :             tenant
    6556          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    6557           98 :                 .await?;
    6558          100 :             tline = tenant
    6559          100 :                 .get_timeline(new_tline_id, true)
    6560          100 :                 .expect("Should have the branched timeline");
    6561            2 : 
    6562       100100 :             for _ in 0..NUM_KEYS {
    6563       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    6564       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6565       100000 :                 test_key.field6 = blknum as u32;
    6566       100000 :                 let mut writer = tline.writer().await;
    6567       100000 :                 writer
    6568       100000 :                     .put(
    6569       100000 :                         test_key,
    6570       100000 :                         lsn,
    6571       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6572       100000 :                         &ctx,
    6573       100000 :                     )
    6574          835 :                     .await?;
    6575       100000 :                 println!("updating {} at {}", blknum, lsn);
    6576       100000 :                 writer.finish_write(lsn);
    6577       100000 :                 drop(writer);
    6578       100000 :                 updated[blknum] = lsn;
    6579            2 :             }
    6580            2 : 
    6581            2 :             // Read all the blocks
    6582       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6583       100000 :                 test_key.field6 = blknum as u32;
    6584       100000 :                 assert_eq!(
    6585       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    6586       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6587            2 :                 );
    6588            2 :             }
    6589            2 : 
    6590            2 :             // Perform a cycle of flush, compact, and GC
    6591          100 :             tline.freeze_and_flush().await?;
    6592        14992 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    6593          100 :             tenant
    6594          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    6595            2 :                 .await?;
    6596            2 :         }
    6597            2 : 
    6598            2 :         Ok(())
    6599            2 :     }
    6600              : 
    6601              :     #[tokio::test]
    6602            2 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    6603            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    6604            2 :             .await?
    6605            2 :             .load()
    6606           20 :             .await;
    6607            2 :         let mut tline = tenant
    6608            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6609            6 :             .await?;
    6610            2 : 
    6611            2 :         const NUM_KEYS: usize = 100;
    6612            2 :         const NUM_TLINES: usize = 50;
    6613            2 : 
    6614            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6615            2 :         // Track page mutation lsns across different timelines.
    6616            2 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    6617            2 : 
    6618            2 :         let mut lsn = Lsn(0x10);
    6619            2 : 
    6620            2 :         #[allow(clippy::needless_range_loop)]
    6621          102 :         for idx in 0..NUM_TLINES {
    6622          100 :             let new_tline_id = TimelineId::generate();
    6623          100 :             tenant
    6624          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    6625           67 :                 .await?;
    6626          100 :             tline = tenant
    6627          100 :                 .get_timeline(new_tline_id, true)
    6628          100 :                 .expect("Should have the branched timeline");
    6629            2 : 
    6630        10100 :             for _ in 0..NUM_KEYS {
    6631        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    6632        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6633        10000 :                 test_key.field6 = blknum as u32;
    6634        10000 :                 let mut writer = tline.writer().await;
    6635        10000 :                 writer
    6636        10000 :                     .put(
    6637        10000 :                         test_key,
    6638        10000 :                         lsn,
    6639        10000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    6640        10000 :                         &ctx,
    6641        10000 :                     )
    6642          108 :                     .await?;
    6643        10000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    6644        10000 :                 writer.finish_write(lsn);
    6645        10000 :                 drop(writer);
    6646        10000 :                 updated[idx][blknum] = lsn;
    6647            2 :             }
    6648            2 :         }
    6649            2 : 
    6650            2 :         // Read pages from leaf timeline across all ancestors.
    6651          100 :         for (idx, lsns) in updated.iter().enumerate() {
    6652        10000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    6653            2 :                 // Skip empty mutations.
    6654        10000 :                 if lsn.0 == 0 {
    6655         3665 :                     continue;
    6656         6335 :                 }
    6657         6335 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    6658         6335 :                 test_key.field6 = blknum as u32;
    6659         6335 :                 assert_eq!(
    6660         6335 :                     tline.get(test_key, *lsn, &ctx).await?,
    6661         6335 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    6662            2 :                 );
    6663            2 :             }
    6664            2 :         }
    6665            2 :         Ok(())
    6666            2 :     }
    6667              : 
    6668              :     #[tokio::test]
    6669            2 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    6670            2 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    6671            2 :             .await?
    6672            2 :             .load()
    6673           20 :             .await;
    6674            2 : 
    6675            2 :         let initdb_lsn = Lsn(0x20);
    6676            2 :         let utline = tenant
    6677            2 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    6678            2 :             .await?;
    6679            2 :         let tline = utline.raw_timeline().unwrap();
    6680            2 : 
    6681            2 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    6682            2 :         tline.maybe_spawn_flush_loop();
    6683            2 : 
    6684            2 :         // Make sure the timeline has the minimum set of required keys for operation.
    6685            2 :         // The only operation you can always do on an empty timeline is to `put` new data.
    6686            2 :         // Except if you `put` at `initdb_lsn`.
    6687            2 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    6688            2 :         // It uses `repartition()`, which assumes some keys to be present.
    6689            2 :         // Let's make sure the test timeline can handle that case.
    6690            2 :         {
    6691            2 :             let mut state = tline.flush_loop_state.lock().unwrap();
    6692            2 :             assert_eq!(
    6693            2 :                 timeline::FlushLoopState::Running {
    6694            2 :                     expect_initdb_optimization: false,
    6695            2 :                     initdb_optimization_count: 0,
    6696            2 :                 },
    6697            2 :                 *state
    6698            2 :             );
    6699            2 :             *state = timeline::FlushLoopState::Running {
    6700            2 :                 expect_initdb_optimization: true,
    6701            2 :                 initdb_optimization_count: 0,
    6702            2 :             };
    6703            2 :         }
    6704            2 : 
    6705            2 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    6706            2 :         // As explained above, the optimization requires some keys to be present.
    6707            2 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    6708            2 :         // This is what `create_test_timeline` does, by the way.
    6709            2 :         let mut modification = tline.begin_modification(initdb_lsn);
    6710            2 :         modification
    6711            2 :             .init_empty_test_timeline()
    6712            2 :             .context("init_empty_test_timeline")?;
    6713            2 :         modification
    6714            2 :             .commit(&ctx)
    6715            2 :             .await
    6716            2 :             .context("commit init_empty_test_timeline modification")?;
    6717            2 : 
    6718            2 :         // Do the flush. The flush code will check the expectations that we set above.
    6719            2 :         tline.freeze_and_flush().await?;
    6720            2 : 
    6721            2 :         // assert freeze_and_flush exercised the initdb optimization
    6722            2 :         {
    6723            2 :             let state = tline.flush_loop_state.lock().unwrap();
    6724            2 :             let timeline::FlushLoopState::Running {
    6725            2 :                 expect_initdb_optimization,
    6726            2 :                 initdb_optimization_count,
    6727            2 :             } = *state
    6728            2 :             else {
    6729            2 :                 panic!("unexpected state: {:?}", *state);
    6730            2 :             };
    6731            2 :             assert!(expect_initdb_optimization);
    6732            2 :             assert!(initdb_optimization_count > 0);
    6733            2 :         }
    6734            2 :         Ok(())
    6735            2 :     }
    6736              : 
    6737              :     #[tokio::test]
    6738            2 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    6739            2 :         let name = "test_create_guard_crash";
    6740            2 :         let harness = TenantHarness::create(name).await?;
    6741            2 :         {
    6742           20 :             let (tenant, ctx) = harness.load().await;
    6743            2 :             let tline = tenant
    6744            2 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6745            2 :                 .await?;
    6746            2 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    6747            2 :             let raw_tline = tline.raw_timeline().unwrap();
    6748            2 :             raw_tline
    6749            2 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    6750            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))
    6751            2 :                 .await;
    6752            2 :             std::mem::forget(tline);
    6753            2 :         }
    6754            2 : 
    6755           20 :         let (tenant, _) = harness.load().await;
    6756            2 :         match tenant.get_timeline(TIMELINE_ID, false) {
    6757            2 :             Ok(_) => panic!("timeline should've been removed during load"),
    6758            2 :             Err(e) => {
    6759            2 :                 assert_eq!(
    6760            2 :                     e,
    6761            2 :                     GetTimelineError::NotFound {
    6762            2 :                         tenant_id: tenant.tenant_shard_id,
    6763            2 :                         timeline_id: TIMELINE_ID,
    6764            2 :                     }
    6765            2 :                 )
    6766            2 :             }
    6767            2 :         }
    6768            2 : 
    6769            2 :         assert!(!harness
    6770            2 :             .conf
    6771            2 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    6772            2 :             .exists());
    6773            2 : 
    6774            2 :         Ok(())
    6775            2 :     }
    6776              : 
    6777              :     #[tokio::test]
    6778            2 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    6779            2 :         let names_algorithms = [
    6780            2 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    6781            2 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    6782            2 :         ];
    6783            6 :         for (name, algorithm) in names_algorithms {
    6784        32561 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    6785            2 :         }
    6786            2 :         Ok(())
    6787            2 :     }
    6788              : 
    6789            4 :     async fn test_read_at_max_lsn_algorithm(
    6790            4 :         name: &'static str,
    6791            4 :         compaction_algorithm: CompactionAlgorithm,
    6792            4 :     ) -> anyhow::Result<()> {
    6793            4 :         let mut harness = TenantHarness::create(name).await?;
    6794            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6795            4 :             kind: compaction_algorithm,
    6796            4 :         };
    6797           40 :         let (tenant, ctx) = harness.load().await;
    6798            4 :         let tline = tenant
    6799            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6800           11 :             .await?;
    6801              : 
    6802            4 :         let lsn = Lsn(0x10);
    6803            4 :         let compact = false;
    6804        32100 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    6805              : 
    6806            4 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6807            4 :         let read_lsn = Lsn(u64::MAX - 1);
    6808              : 
    6809          410 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    6810            4 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    6811              : 
    6812            4 :         Ok(())
    6813            4 :     }
    6814              : 
    6815              :     #[tokio::test]
    6816            2 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    6817            2 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    6818           20 :         let (tenant, ctx) = harness.load().await;
    6819            2 :         let tline = tenant
    6820            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6821            6 :             .await?;
    6822            2 : 
    6823            2 :         const NUM_KEYS: usize = 1000;
    6824            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    6825            2 : 
    6826            2 :         let cancel = CancellationToken::new();
    6827            2 : 
    6828            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    6829            2 :         base_key.field1 = AUX_KEY_PREFIX;
    6830            2 :         let mut test_key = base_key;
    6831            2 : 
    6832            2 :         // Track when each page was last modified. Used to assert that
    6833            2 :         // a read sees the latest page version.
    6834            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    6835            2 : 
    6836            2 :         let mut lsn = Lsn(0x10);
    6837            2 :         #[allow(clippy::needless_range_loop)]
    6838         2002 :         for blknum in 0..NUM_KEYS {
    6839         2000 :             lsn = Lsn(lsn.0 + 0x10);
    6840         2000 :             test_key.field6 = (blknum * STEP) as u32;
    6841         2000 :             let mut writer = tline.writer().await;
    6842         2000 :             writer
    6843         2000 :                 .put(
    6844         2000 :                     test_key,
    6845         2000 :                     lsn,
    6846         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6847         2000 :                     &ctx,
    6848         2000 :                 )
    6849            2 :                 .await?;
    6850         2000 :             writer.finish_write(lsn);
    6851         2000 :             updated[blknum] = lsn;
    6852         2000 :             drop(writer);
    6853            2 :         }
    6854            2 : 
    6855            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    6856            2 : 
    6857           24 :         for iter in 0..=10 {
    6858            2 :             // Read all the blocks
    6859        22000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6860        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    6861        22000 :                 assert_eq!(
    6862        22000 :                     tline.get(test_key, lsn, &ctx).await?,
    6863        22000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6864            2 :                 );
    6865            2 :             }
    6866            2 : 
    6867           22 :             let mut cnt = 0;
    6868        22000 :             for (key, value) in tline
    6869           22 :                 .get_vectored_impl(
    6870           22 :                     keyspace.clone(),
    6871           22 :                     lsn,
    6872           22 :                     &mut ValuesReconstructState::default(),
    6873           22 :                     &ctx,
    6874           22 :                 )
    6875          741 :                 .await?
    6876            2 :             {
    6877        22000 :                 let blknum = key.field6 as usize;
    6878        22000 :                 let value = value?;
    6879        22000 :                 assert!(blknum % STEP == 0);
    6880        22000 :                 let blknum = blknum / STEP;
    6881        22000 :                 assert_eq!(
    6882        22000 :                     value,
    6883        22000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    6884        22000 :                 );
    6885        22000 :                 cnt += 1;
    6886            2 :             }
    6887            2 : 
    6888           22 :             assert_eq!(cnt, NUM_KEYS);
    6889            2 : 
    6890        22022 :             for _ in 0..NUM_KEYS {
    6891        22000 :                 lsn = Lsn(lsn.0 + 0x10);
    6892        22000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6893        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    6894        22000 :                 let mut writer = tline.writer().await;
    6895        22000 :                 writer
    6896        22000 :                     .put(
    6897        22000 :                         test_key,
    6898        22000 :                         lsn,
    6899        22000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6900        22000 :                         &ctx,
    6901        22000 :                     )
    6902          111 :                     .await?;
    6903        22000 :                 writer.finish_write(lsn);
    6904        22000 :                 drop(writer);
    6905        22000 :                 updated[blknum] = lsn;
    6906            2 :             }
    6907            2 : 
    6908            2 :             // Perform two cycles of flush, compact, and GC
    6909           66 :             for round in 0..2 {
    6910           44 :                 tline.freeze_and_flush().await?;
    6911           44 :                 tline
    6912           44 :                     .compact(
    6913           44 :                         &cancel,
    6914           44 :                         if iter % 5 == 0 && round == 0 {
    6915            6 :                             let mut flags = EnumSet::new();
    6916            6 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    6917            6 :                             flags.insert(CompactFlags::ForceRepartition);
    6918            6 :                             flags
    6919            2 :                         } else {
    6920           38 :                             EnumSet::empty()
    6921            2 :                         },
    6922           44 :                         &ctx,
    6923            2 :                     )
    6924         6702 :                     .await?;
    6925           44 :                 tenant
    6926           44 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    6927            2 :                     .await?;
    6928            2 :             }
    6929            2 :         }
    6930            2 : 
    6931            2 :         Ok(())
    6932            2 :     }
    6933              : 
    6934              :     #[tokio::test]
    6935            2 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    6936            2 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    6937           20 :         let (tenant, ctx) = harness.load().await;
    6938            2 :         let tline = tenant
    6939            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6940            6 :             .await?;
    6941            2 : 
    6942            2 :         let cancel = CancellationToken::new();
    6943            2 : 
    6944            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    6945            2 :         base_key.field1 = AUX_KEY_PREFIX;
    6946            2 :         let test_key = base_key;
    6947            2 :         let mut lsn = Lsn(0x10);
    6948            2 : 
    6949           42 :         for _ in 0..20 {
    6950           40 :             lsn = Lsn(lsn.0 + 0x10);
    6951           40 :             let mut writer = tline.writer().await;
    6952           40 :             writer
    6953           40 :                 .put(
    6954           40 :                     test_key,
    6955           40 :                     lsn,
    6956           40 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    6957           40 :                     &ctx,
    6958           40 :                 )
    6959           20 :                 .await?;
    6960           40 :             writer.finish_write(lsn);
    6961           40 :             drop(writer);
    6962           40 :             tline.freeze_and_flush().await?; // force create a delta layer
    6963            2 :         }
    6964            2 : 
    6965            2 :         let before_num_l0_delta_files =
    6966            2 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    6967            2 : 
    6968          110 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    6969            2 : 
    6970            2 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    6971            2 : 
    6972            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}");
    6973            2 : 
    6974            2 :         assert_eq!(
    6975            4 :             tline.get(test_key, lsn, &ctx).await?,
    6976            2 :             test_img(&format!("{} at {}", 0, lsn))
    6977            2 :         );
    6978            2 : 
    6979            2 :         Ok(())
    6980            2 :     }
    6981              : 
    6982              :     #[tokio::test]
    6983            2 :     async fn test_aux_file_e2e() {
    6984            2 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    6985            2 : 
    6986           20 :         let (tenant, ctx) = harness.load().await;
    6987            2 : 
    6988            2 :         let mut lsn = Lsn(0x08);
    6989            2 : 
    6990            2 :         let tline: Arc<Timeline> = tenant
    6991            2 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    6992            6 :             .await
    6993            2 :             .unwrap();
    6994            2 : 
    6995            2 :         {
    6996            2 :             lsn += 8;
    6997            2 :             let mut modification = tline.begin_modification(lsn);
    6998            2 :             modification
    6999            2 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7000            2 :                 .await
    7001            2 :                 .unwrap();
    7002            2 :             modification.commit(&ctx).await.unwrap();
    7003            2 :         }
    7004            2 : 
    7005            2 :         // we can read everything from the storage
    7006            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7007            2 :         assert_eq!(
    7008            2 :             files.get("pg_logical/mappings/test1"),
    7009            2 :             Some(&bytes::Bytes::from_static(b"first"))
    7010            2 :         );
    7011            2 : 
    7012            2 :         {
    7013            2 :             lsn += 8;
    7014            2 :             let mut modification = tline.begin_modification(lsn);
    7015            2 :             modification
    7016            2 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7017            2 :                 .await
    7018            2 :                 .unwrap();
    7019            2 :             modification.commit(&ctx).await.unwrap();
    7020            2 :         }
    7021            2 : 
    7022            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7023            2 :         assert_eq!(
    7024            2 :             files.get("pg_logical/mappings/test2"),
    7025            2 :             Some(&bytes::Bytes::from_static(b"second"))
    7026            2 :         );
    7027            2 : 
    7028            2 :         let child = tenant
    7029            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7030            2 :             .await
    7031            2 :             .unwrap();
    7032            2 : 
    7033            2 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    7034            2 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7035            2 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7036            2 :     }
    7037              : 
    7038              :     #[tokio::test]
    7039            2 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7040            2 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7041           20 :         let (tenant, ctx) = harness.load().await;
    7042            2 :         let tline = tenant
    7043            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7044            6 :             .await?;
    7045            2 : 
    7046            2 :         const NUM_KEYS: usize = 1000;
    7047            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7048            2 : 
    7049            2 :         let cancel = CancellationToken::new();
    7050            2 : 
    7051            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7052            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7053            2 :         let mut test_key = base_key;
    7054            2 :         let mut lsn = Lsn(0x10);
    7055            2 : 
    7056            8 :         async fn scan_with_statistics(
    7057            8 :             tline: &Timeline,
    7058            8 :             keyspace: &KeySpace,
    7059            8 :             lsn: Lsn,
    7060            8 :             ctx: &RequestContext,
    7061            8 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7062            8 :             let mut reconstruct_state = ValuesReconstructState::default();
    7063            8 :             let res = tline
    7064            8 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7065          241 :                 .await?;
    7066            8 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7067            8 :         }
    7068            2 : 
    7069            2 :         #[allow(clippy::needless_range_loop)]
    7070         2002 :         for blknum in 0..NUM_KEYS {
    7071         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7072         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7073         2000 :             let mut writer = tline.writer().await;
    7074         2000 :             writer
    7075         2000 :                 .put(
    7076         2000 :                     test_key,
    7077         2000 :                     lsn,
    7078         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7079         2000 :                     &ctx,
    7080         2000 :                 )
    7081            2 :                 .await?;
    7082         2000 :             writer.finish_write(lsn);
    7083         2000 :             drop(writer);
    7084            2 :         }
    7085            2 : 
    7086            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7087            2 : 
    7088           22 :         for iter in 1..=10 {
    7089        20020 :             for _ in 0..NUM_KEYS {
    7090        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7091        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7092        20000 :                 test_key.field6 = (blknum * STEP) as u32;
    7093        20000 :                 let mut writer = tline.writer().await;
    7094        20000 :                 writer
    7095        20000 :                     .put(
    7096        20000 :                         test_key,
    7097        20000 :                         lsn,
    7098        20000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7099        20000 :                         &ctx,
    7100        20000 :                     )
    7101           35 :                     .await?;
    7102        20000 :                 writer.finish_write(lsn);
    7103        20000 :                 drop(writer);
    7104            2 :             }
    7105            2 : 
    7106           20 :             tline.freeze_and_flush().await?;
    7107            2 : 
    7108           20 :             if iter % 5 == 0 {
    7109            4 :                 let (_, before_delta_file_accessed) =
    7110          233 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7111            4 :                 tline
    7112            4 :                     .compact(
    7113            4 :                         &cancel,
    7114            4 :                         {
    7115            4 :                             let mut flags = EnumSet::new();
    7116            4 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7117            4 :                             flags.insert(CompactFlags::ForceRepartition);
    7118            4 :                             flags
    7119            4 :                         },
    7120            4 :                         &ctx,
    7121            4 :                     )
    7122         4829 :                     .await?;
    7123            4 :                 let (_, after_delta_file_accessed) =
    7124            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7125            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}");
    7126            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.
    7127            4 :                 assert!(
    7128            4 :                     after_delta_file_accessed <= 2,
    7129            2 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7130            2 :                 );
    7131           16 :             }
    7132            2 :         }
    7133            2 : 
    7134            2 :         Ok(())
    7135            2 :     }
    7136              : 
    7137              :     #[tokio::test]
    7138            2 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7139            2 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7140           20 :         let (tenant, ctx) = harness.load().await;
    7141            2 : 
    7142            2 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7143            2 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7144            2 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7145            2 : 
    7146            2 :         let tline = tenant
    7147            2 :             .create_test_timeline_with_layers(
    7148            2 :                 TIMELINE_ID,
    7149            2 :                 Lsn(0x10),
    7150            2 :                 DEFAULT_PG_VERSION,
    7151            2 :                 &ctx,
    7152            2 :                 Vec::new(), // delta layers
    7153            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7154            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
    7155            2 :             )
    7156           13 :             .await?;
    7157            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7158            2 : 
    7159            2 :         let child = tenant
    7160            2 :             .branch_timeline_test_with_layers(
    7161            2 :                 &tline,
    7162            2 :                 NEW_TIMELINE_ID,
    7163            2 :                 Some(Lsn(0x20)),
    7164            2 :                 &ctx,
    7165            2 :                 Vec::new(), // delta layers
    7166            2 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7167            2 :                 Lsn(0x30),
    7168            2 :             )
    7169            9 :             .await
    7170            2 :             .unwrap();
    7171            2 : 
    7172            2 :         let lsn = Lsn(0x30);
    7173            2 : 
    7174            2 :         // test vectored get on parent timeline
    7175            2 :         assert_eq!(
    7176            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7177            2 :             Some(test_img("data key 1"))
    7178            2 :         );
    7179            2 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7180            3 :             .await
    7181            2 :             .unwrap_err()
    7182            2 :             .is_missing_key_error());
    7183            2 :         assert!(
    7184            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7185            2 :                 .await
    7186            2 :                 .unwrap_err()
    7187            2 :                 .is_missing_key_error()
    7188            2 :         );
    7189            2 : 
    7190            2 :         // test vectored get on child timeline
    7191            2 :         assert_eq!(
    7192            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7193            2 :             Some(test_img("data key 1"))
    7194            2 :         );
    7195            2 :         assert_eq!(
    7196            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7197            2 :             Some(test_img("data key 2"))
    7198            2 :         );
    7199            2 :         assert!(
    7200            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7201            2 :                 .await
    7202            2 :                 .unwrap_err()
    7203            2 :                 .is_missing_key_error()
    7204            2 :         );
    7205            2 : 
    7206            2 :         Ok(())
    7207            2 :     }
    7208              : 
    7209              :     #[tokio::test]
    7210            2 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7211            2 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7212           20 :         let (tenant, ctx) = harness.load().await;
    7213            2 : 
    7214            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7215            2 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7216            2 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7217            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7218            2 : 
    7219            2 :         let tline = tenant
    7220            2 :             .create_test_timeline_with_layers(
    7221            2 :                 TIMELINE_ID,
    7222            2 :                 Lsn(0x10),
    7223            2 :                 DEFAULT_PG_VERSION,
    7224            2 :                 &ctx,
    7225            2 :                 Vec::new(), // delta layers
    7226            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
    7227            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
    7228            2 :             )
    7229           13 :             .await?;
    7230            2 : 
    7231            2 :         let child = tenant
    7232            2 :             .branch_timeline_test_with_layers(
    7233            2 :                 &tline,
    7234            2 :                 NEW_TIMELINE_ID,
    7235            2 :                 Some(Lsn(0x20)),
    7236            2 :                 &ctx,
    7237            2 :                 Vec::new(), // delta layers
    7238            2 :                 vec![(
    7239            2 :                     Lsn(0x30),
    7240            2 :                     vec![(base_key_child, test_img("metadata key 2"))],
    7241            2 :                 )], // image layers
    7242            2 :                 Lsn(0x30),
    7243            2 :             )
    7244            9 :             .await
    7245            2 :             .unwrap();
    7246            2 : 
    7247            2 :         let lsn = Lsn(0x30);
    7248            2 : 
    7249            2 :         // test vectored get on parent timeline
    7250            2 :         assert_eq!(
    7251            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7252            2 :             Some(test_img("metadata key 1"))
    7253            2 :         );
    7254            2 :         assert_eq!(
    7255            2 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7256            2 :             None
    7257            2 :         );
    7258            2 :         assert_eq!(
    7259            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7260            2 :             None
    7261            2 :         );
    7262            2 : 
    7263            2 :         // test vectored get on child timeline
    7264            2 :         assert_eq!(
    7265            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7266            2 :             None
    7267            2 :         );
    7268            2 :         assert_eq!(
    7269            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7270            2 :             Some(test_img("metadata key 2"))
    7271            2 :         );
    7272            2 :         assert_eq!(
    7273            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7274            2 :             None
    7275            2 :         );
    7276            2 : 
    7277            2 :         Ok(())
    7278            2 :     }
    7279              : 
    7280           36 :     async fn get_vectored_impl_wrapper(
    7281           36 :         tline: &Arc<Timeline>,
    7282           36 :         key: Key,
    7283           36 :         lsn: Lsn,
    7284           36 :         ctx: &RequestContext,
    7285           36 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7286           36 :         let mut reconstruct_state = ValuesReconstructState::new();
    7287           36 :         let mut res = tline
    7288           36 :             .get_vectored_impl(
    7289           36 :                 KeySpace::single(key..key.next()),
    7290           36 :                 lsn,
    7291           36 :                 &mut reconstruct_state,
    7292           36 :                 ctx,
    7293           36 :             )
    7294           40 :             .await?;
    7295           30 :         Ok(res.pop_last().map(|(k, v)| {
    7296           18 :             assert_eq!(k, key);
    7297           18 :             v.unwrap()
    7298           30 :         }))
    7299           36 :     }
    7300              : 
    7301              :     #[tokio::test]
    7302            2 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    7303            2 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    7304           20 :         let (tenant, ctx) = harness.load().await;
    7305            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7306            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7307            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7308            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7309            2 : 
    7310            2 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    7311            2 :         // Lsn 0x30 key0, key3, no key1+key2
    7312            2 :         // Lsn 0x20 key1+key2 tomestones
    7313            2 :         // Lsn 0x10 key1 in image, key2 in delta
    7314            2 :         let tline = tenant
    7315            2 :             .create_test_timeline_with_layers(
    7316            2 :                 TIMELINE_ID,
    7317            2 :                 Lsn(0x10),
    7318            2 :                 DEFAULT_PG_VERSION,
    7319            2 :                 &ctx,
    7320            2 :                 // delta layers
    7321            2 :                 vec![
    7322            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7323            2 :                         Lsn(0x10)..Lsn(0x20),
    7324            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7325            2 :                     ),
    7326            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7327            2 :                         Lsn(0x20)..Lsn(0x30),
    7328            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7329            2 :                     ),
    7330            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7331            2 :                         Lsn(0x20)..Lsn(0x30),
    7332            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7333            2 :                     ),
    7334            2 :                 ],
    7335            2 :                 // image layers
    7336            2 :                 vec![
    7337            2 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    7338            2 :                     (
    7339            2 :                         Lsn(0x30),
    7340            2 :                         vec![
    7341            2 :                             (key0, test_img("metadata key 0")),
    7342            2 :                             (key3, test_img("metadata key 3")),
    7343            2 :                         ],
    7344            2 :                     ),
    7345            2 :                 ],
    7346            2 :                 Lsn(0x30),
    7347            2 :             )
    7348           40 :             .await?;
    7349            2 : 
    7350            2 :         let lsn = Lsn(0x30);
    7351            2 :         let old_lsn = Lsn(0x20);
    7352            2 : 
    7353            2 :         assert_eq!(
    7354            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    7355            2 :             Some(test_img("metadata key 0"))
    7356            2 :         );
    7357            2 :         assert_eq!(
    7358            2 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    7359            2 :             None,
    7360            2 :         );
    7361            2 :         assert_eq!(
    7362            2 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    7363            2 :             None,
    7364            2 :         );
    7365            2 :         assert_eq!(
    7366            8 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    7367            2 :             Some(Bytes::new()),
    7368            2 :         );
    7369            2 :         assert_eq!(
    7370            7 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    7371            2 :             Some(Bytes::new()),
    7372            2 :         );
    7373            2 :         assert_eq!(
    7374            2 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    7375            2 :             Some(test_img("metadata key 3"))
    7376            2 :         );
    7377            2 : 
    7378            2 :         Ok(())
    7379            2 :     }
    7380              : 
    7381              :     #[tokio::test]
    7382            2 :     async fn test_metadata_tombstone_image_creation() {
    7383            2 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    7384            2 :             .await
    7385            2 :             .unwrap();
    7386           20 :         let (tenant, ctx) = harness.load().await;
    7387            2 : 
    7388            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7389            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7390            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7391            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7392            2 : 
    7393            2 :         let tline = tenant
    7394            2 :             .create_test_timeline_with_layers(
    7395            2 :                 TIMELINE_ID,
    7396            2 :                 Lsn(0x10),
    7397            2 :                 DEFAULT_PG_VERSION,
    7398            2 :                 &ctx,
    7399            2 :                 // delta layers
    7400            2 :                 vec![
    7401            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7402            2 :                         Lsn(0x10)..Lsn(0x20),
    7403            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7404            2 :                     ),
    7405            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7406            2 :                         Lsn(0x20)..Lsn(0x30),
    7407            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7408            2 :                     ),
    7409            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7410            2 :                         Lsn(0x20)..Lsn(0x30),
    7411            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7412            2 :                     ),
    7413            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7414            2 :                         Lsn(0x30)..Lsn(0x40),
    7415            2 :                         vec![
    7416            2 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    7417            2 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    7418            2 :                         ],
    7419            2 :                     ),
    7420            2 :                 ],
    7421            2 :                 // image layers
    7422            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7423            2 :                 Lsn(0x40),
    7424            2 :             )
    7425           37 :             .await
    7426            2 :             .unwrap();
    7427            2 : 
    7428            2 :         let cancel = CancellationToken::new();
    7429            2 : 
    7430            2 :         tline
    7431            2 :             .compact(
    7432            2 :                 &cancel,
    7433            2 :                 {
    7434            2 :                     let mut flags = EnumSet::new();
    7435            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7436            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7437            2 :                     flags
    7438            2 :                 },
    7439            2 :                 &ctx,
    7440            2 :             )
    7441           62 :             .await
    7442            2 :             .unwrap();
    7443            2 : 
    7444            2 :         // Image layers are created at last_record_lsn
    7445            2 :         let images = tline
    7446            2 :             .inspect_image_layers(Lsn(0x40), &ctx)
    7447            8 :             .await
    7448            2 :             .unwrap()
    7449            2 :             .into_iter()
    7450           18 :             .filter(|(k, _)| k.is_metadata_key())
    7451            2 :             .collect::<Vec<_>>();
    7452            2 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    7453            2 :     }
    7454              : 
    7455              :     #[tokio::test]
    7456            2 :     async fn test_metadata_tombstone_empty_image_creation() {
    7457            2 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    7458            2 :             .await
    7459            2 :             .unwrap();
    7460           20 :         let (tenant, ctx) = harness.load().await;
    7461            2 : 
    7462            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7463            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7464            2 : 
    7465            2 :         let tline = tenant
    7466            2 :             .create_test_timeline_with_layers(
    7467            2 :                 TIMELINE_ID,
    7468            2 :                 Lsn(0x10),
    7469            2 :                 DEFAULT_PG_VERSION,
    7470            2 :                 &ctx,
    7471            2 :                 // delta layers
    7472            2 :                 vec![
    7473            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7474            2 :                         Lsn(0x10)..Lsn(0x20),
    7475            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7476            2 :                     ),
    7477            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7478            2 :                         Lsn(0x20)..Lsn(0x30),
    7479            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7480            2 :                     ),
    7481            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7482            2 :                         Lsn(0x20)..Lsn(0x30),
    7483            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7484            2 :                     ),
    7485            2 :                 ],
    7486            2 :                 // image layers
    7487            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7488            2 :                 Lsn(0x30),
    7489            2 :             )
    7490           31 :             .await
    7491            2 :             .unwrap();
    7492            2 : 
    7493            2 :         let cancel = CancellationToken::new();
    7494            2 : 
    7495            2 :         tline
    7496            2 :             .compact(
    7497            2 :                 &cancel,
    7498            2 :                 {
    7499            2 :                     let mut flags = EnumSet::new();
    7500            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7501            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7502            2 :                     flags
    7503            2 :                 },
    7504            2 :                 &ctx,
    7505            2 :             )
    7506           50 :             .await
    7507            2 :             .unwrap();
    7508            2 : 
    7509            2 :         // Image layers are created at last_record_lsn
    7510            2 :         let images = tline
    7511            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    7512            4 :             .await
    7513            2 :             .unwrap()
    7514            2 :             .into_iter()
    7515           14 :             .filter(|(k, _)| k.is_metadata_key())
    7516            2 :             .collect::<Vec<_>>();
    7517            2 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    7518            2 :     }
    7519              : 
    7520              :     #[tokio::test]
    7521            2 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    7522            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    7523           20 :         let (tenant, ctx) = harness.load().await;
    7524            2 : 
    7525          102 :         fn get_key(id: u32) -> Key {
    7526          102 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7527          102 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7528          102 :             key.field6 = id;
    7529          102 :             key
    7530          102 :         }
    7531            2 : 
    7532            2 :         // We create
    7533            2 :         // - one bottom-most image layer,
    7534            2 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    7535            2 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    7536            2 :         // - a delta layer D3 above the horizon.
    7537            2 :         //
    7538            2 :         //                             | D3 |
    7539            2 :         //  | D1 |
    7540            2 :         // -|    |-- gc horizon -----------------
    7541            2 :         //  |    |                | D2 |
    7542            2 :         // --------- img layer ------------------
    7543            2 :         //
    7544            2 :         // What we should expact from this compaction is:
    7545            2 :         //                             | D3 |
    7546            2 :         //  | Part of D1 |
    7547            2 :         // --------- img layer with D1+D2 at GC horizon------------------
    7548            2 : 
    7549            2 :         // img layer at 0x10
    7550            2 :         let img_layer = (0..10)
    7551           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    7552            2 :             .collect_vec();
    7553            2 : 
    7554            2 :         let delta1 = vec![
    7555            2 :             (
    7556            2 :                 get_key(1),
    7557            2 :                 Lsn(0x20),
    7558            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    7559            2 :             ),
    7560            2 :             (
    7561            2 :                 get_key(2),
    7562            2 :                 Lsn(0x30),
    7563            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    7564            2 :             ),
    7565            2 :             (
    7566            2 :                 get_key(3),
    7567            2 :                 Lsn(0x40),
    7568            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    7569            2 :             ),
    7570            2 :         ];
    7571            2 :         let delta2 = vec![
    7572            2 :             (
    7573            2 :                 get_key(5),
    7574            2 :                 Lsn(0x20),
    7575            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    7576            2 :             ),
    7577            2 :             (
    7578            2 :                 get_key(6),
    7579            2 :                 Lsn(0x20),
    7580            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    7581            2 :             ),
    7582            2 :         ];
    7583            2 :         let delta3 = vec![
    7584            2 :             (
    7585            2 :                 get_key(8),
    7586            2 :                 Lsn(0x48),
    7587            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    7588            2 :             ),
    7589            2 :             (
    7590            2 :                 get_key(9),
    7591            2 :                 Lsn(0x48),
    7592            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    7593            2 :             ),
    7594            2 :         ];
    7595            2 : 
    7596            2 :         let tline = tenant
    7597            2 :             .create_test_timeline_with_layers(
    7598            2 :                 TIMELINE_ID,
    7599            2 :                 Lsn(0x10),
    7600            2 :                 DEFAULT_PG_VERSION,
    7601            2 :                 &ctx,
    7602            2 :                 vec![
    7603            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    7604            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    7605            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    7606            2 :                 ], // delta layers
    7607            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    7608            2 :                 Lsn(0x50),
    7609            2 :             )
    7610           49 :             .await?;
    7611            2 :         {
    7612            2 :             // Update GC info
    7613            2 :             let mut guard = tline.gc_info.write().unwrap();
    7614            2 :             guard.cutoffs.time = Lsn(0x30);
    7615            2 :             guard.cutoffs.space = Lsn(0x30);
    7616            2 :         }
    7617            2 : 
    7618            2 :         let expected_result = [
    7619            2 :             Bytes::from_static(b"value 0@0x10"),
    7620            2 :             Bytes::from_static(b"value 1@0x20"),
    7621            2 :             Bytes::from_static(b"value 2@0x30"),
    7622            2 :             Bytes::from_static(b"value 3@0x40"),
    7623            2 :             Bytes::from_static(b"value 4@0x10"),
    7624            2 :             Bytes::from_static(b"value 5@0x20"),
    7625            2 :             Bytes::from_static(b"value 6@0x20"),
    7626            2 :             Bytes::from_static(b"value 7@0x10"),
    7627            2 :             Bytes::from_static(b"value 8@0x48"),
    7628            2 :             Bytes::from_static(b"value 9@0x48"),
    7629            2 :         ];
    7630            2 : 
    7631           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    7632           20 :             assert_eq!(
    7633           20 :                 tline
    7634           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7635           30 :                     .await
    7636           20 :                     .unwrap(),
    7637            2 :                 expected
    7638            2 :             );
    7639            2 :         }
    7640            2 : 
    7641            2 :         let cancel = CancellationToken::new();
    7642            2 :         tline
    7643            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7644           56 :             .await
    7645            2 :             .unwrap();
    7646            2 : 
    7647           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    7648           20 :             assert_eq!(
    7649           20 :                 tline
    7650           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7651           20 :                     .await
    7652           20 :                     .unwrap(),
    7653            2 :                 expected
    7654            2 :             );
    7655            2 :         }
    7656            2 : 
    7657            2 :         // Check if the image layer at the GC horizon contains exactly what we want
    7658            2 :         let image_at_gc_horizon = tline
    7659            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    7660            2 :             .await
    7661            2 :             .unwrap()
    7662            2 :             .into_iter()
    7663           34 :             .filter(|(k, _)| k.is_metadata_key())
    7664            2 :             .collect::<Vec<_>>();
    7665            2 : 
    7666            2 :         assert_eq!(image_at_gc_horizon.len(), 10);
    7667            2 :         let expected_result = [
    7668            2 :             Bytes::from_static(b"value 0@0x10"),
    7669            2 :             Bytes::from_static(b"value 1@0x20"),
    7670            2 :             Bytes::from_static(b"value 2@0x30"),
    7671            2 :             Bytes::from_static(b"value 3@0x10"),
    7672            2 :             Bytes::from_static(b"value 4@0x10"),
    7673            2 :             Bytes::from_static(b"value 5@0x20"),
    7674            2 :             Bytes::from_static(b"value 6@0x20"),
    7675            2 :             Bytes::from_static(b"value 7@0x10"),
    7676            2 :             Bytes::from_static(b"value 8@0x10"),
    7677            2 :             Bytes::from_static(b"value 9@0x10"),
    7678            2 :         ];
    7679           22 :         for idx in 0..10 {
    7680           20 :             assert_eq!(
    7681           20 :                 image_at_gc_horizon[idx],
    7682           20 :                 (get_key(idx as u32), expected_result[idx].clone())
    7683           20 :             );
    7684            2 :         }
    7685            2 : 
    7686            2 :         // Check if old layers are removed / new layers have the expected LSN
    7687            2 :         let all_layers = inspect_and_sort(&tline, None).await;
    7688            2 :         assert_eq!(
    7689            2 :             all_layers,
    7690            2 :             vec![
    7691            2 :                 // Image layer at GC horizon
    7692            2 :                 PersistentLayerKey {
    7693            2 :                     key_range: Key::MIN..Key::MAX,
    7694            2 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    7695            2 :                     is_delta: false
    7696            2 :                 },
    7697            2 :                 // The delta layer below the horizon
    7698            2 :                 PersistentLayerKey {
    7699            2 :                     key_range: get_key(3)..get_key(4),
    7700            2 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    7701            2 :                     is_delta: true
    7702            2 :                 },
    7703            2 :                 // The delta3 layer that should not be picked for the compaction
    7704            2 :                 PersistentLayerKey {
    7705            2 :                     key_range: get_key(8)..get_key(10),
    7706            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    7707            2 :                     is_delta: true
    7708            2 :                 }
    7709            2 :             ]
    7710            2 :         );
    7711            2 : 
    7712            2 :         // increase GC horizon and compact again
    7713            2 :         {
    7714            2 :             // Update GC info
    7715            2 :             let mut guard = tline.gc_info.write().unwrap();
    7716            2 :             guard.cutoffs.time = Lsn(0x40);
    7717            2 :             guard.cutoffs.space = Lsn(0x40);
    7718            2 :         }
    7719            2 :         tline
    7720            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7721           45 :             .await
    7722            2 :             .unwrap();
    7723            2 : 
    7724            2 :         Ok(())
    7725            2 :     }
    7726              : 
    7727              :     #[cfg(feature = "testing")]
    7728              :     #[tokio::test]
    7729            2 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    7730            2 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    7731           20 :         let (tenant, ctx) = harness.load().await;
    7732            2 : 
    7733           24 :         fn get_key(id: u32) -> Key {
    7734           24 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7735           24 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7736           24 :             key.field6 = id;
    7737           24 :             key
    7738           24 :         }
    7739            2 : 
    7740            2 :         let delta1 = vec![
    7741            2 :             (
    7742            2 :                 get_key(1),
    7743            2 :                 Lsn(0x20),
    7744            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    7745            2 :             ),
    7746            2 :             (
    7747            2 :                 get_key(1),
    7748            2 :                 Lsn(0x30),
    7749            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    7750            2 :             ),
    7751            2 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    7752            2 :             (
    7753            2 :                 get_key(2),
    7754            2 :                 Lsn(0x20),
    7755            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    7756            2 :             ),
    7757            2 :             (
    7758            2 :                 get_key(2),
    7759            2 :                 Lsn(0x30),
    7760            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    7761            2 :             ),
    7762            2 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    7763            2 :             (
    7764            2 :                 get_key(3),
    7765            2 :                 Lsn(0x20),
    7766            2 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    7767            2 :             ),
    7768            2 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    7769            2 :             (
    7770            2 :                 get_key(4),
    7771            2 :                 Lsn(0x20),
    7772            2 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    7773            2 :             ),
    7774            2 :         ];
    7775            2 :         let image1 = vec![(get_key(1), "0x10".into())];
    7776            2 : 
    7777            2 :         let tline = tenant
    7778            2 :             .create_test_timeline_with_layers(
    7779            2 :                 TIMELINE_ID,
    7780            2 :                 Lsn(0x10),
    7781            2 :                 DEFAULT_PG_VERSION,
    7782            2 :                 &ctx,
    7783            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    7784            2 :                     Lsn(0x10)..Lsn(0x40),
    7785            2 :                     delta1,
    7786            2 :                 )], // delta layers
    7787            2 :                 vec![(Lsn(0x10), image1)], // image layers
    7788            2 :                 Lsn(0x50),
    7789            2 :             )
    7790           19 :             .await?;
    7791            2 : 
    7792            2 :         assert_eq!(
    7793            8 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    7794            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    7795            2 :         );
    7796            2 :         assert_eq!(
    7797            2 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    7798            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    7799            2 :         );
    7800            2 : 
    7801            2 :         // Need to remove the limit of "Neon WAL redo requires base image".
    7802            2 : 
    7803            2 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    7804            2 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    7805            2 : 
    7806            2 :         Ok(())
    7807            2 :     }
    7808              : 
    7809              :     #[tokio::test(start_paused = true)]
    7810            2 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    7811            2 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    7812            2 :             .await
    7813            2 :             .unwrap()
    7814            2 :             .load()
    7815           20 :             .await;
    7816            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    7817            2 :         // initial transition into AttachedSingle.
    7818            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    7819            2 :         tokio::time::resume();
    7820            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7821            2 : 
    7822            2 :         let end_lsn = Lsn(0x100);
    7823            2 :         let image_layers = (0x20..=0x90)
    7824            2 :             .step_by(0x10)
    7825           16 :             .map(|n| {
    7826           16 :                 (
    7827           16 :                     Lsn(n),
    7828           16 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    7829           16 :                 )
    7830           16 :             })
    7831            2 :             .collect();
    7832            2 : 
    7833            2 :         let timeline = tenant
    7834            2 :             .create_test_timeline_with_layers(
    7835            2 :                 TIMELINE_ID,
    7836            2 :                 Lsn(0x10),
    7837            2 :                 DEFAULT_PG_VERSION,
    7838            2 :                 &ctx,
    7839            2 :                 Vec::new(),
    7840            2 :                 image_layers,
    7841            2 :                 end_lsn,
    7842            2 :             )
    7843           62 :             .await?;
    7844            2 : 
    7845            2 :         let leased_lsns = [0x30, 0x50, 0x70];
    7846            2 :         let mut leases = Vec::new();
    7847            6 :         leased_lsns.iter().for_each(|n| {
    7848            6 :             leases.push(
    7849            6 :                 timeline
    7850            6 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    7851            6 :                     .expect("lease request should succeed"),
    7852            6 :             );
    7853            6 :         });
    7854            2 : 
    7855            2 :         let updated_lease_0 = timeline
    7856            2 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    7857            2 :             .expect("lease renewal should succeed");
    7858            2 :         assert_eq!(
    7859            2 :             updated_lease_0.valid_until, leases[0].valid_until,
    7860            2 :             " Renewing with shorter lease should not change the lease."
    7861            2 :         );
    7862            2 : 
    7863            2 :         let updated_lease_1 = timeline
    7864            2 :             .renew_lsn_lease(
    7865            2 :                 Lsn(leased_lsns[1]),
    7866            2 :                 timeline.get_lsn_lease_length() * 2,
    7867            2 :                 &ctx,
    7868            2 :             )
    7869            2 :             .expect("lease renewal should succeed");
    7870            2 :         assert!(
    7871            2 :             updated_lease_1.valid_until > leases[1].valid_until,
    7872            2 :             "Renewing with a long lease should renew lease with later expiration time."
    7873            2 :         );
    7874            2 : 
    7875            2 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    7876            2 :         info!(
    7877            2 :             "latest_gc_cutoff_lsn: {}",
    7878            0 :             *timeline.get_latest_gc_cutoff_lsn()
    7879            2 :         );
    7880            2 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    7881            2 : 
    7882            2 :         let res = tenant
    7883            2 :             .gc_iteration(
    7884            2 :                 Some(TIMELINE_ID),
    7885            2 :                 0,
    7886            2 :                 Duration::ZERO,
    7887            2 :                 &CancellationToken::new(),
    7888            2 :                 &ctx,
    7889            2 :             )
    7890            2 :             .await
    7891            2 :             .unwrap();
    7892            2 : 
    7893            2 :         // Keeping everything <= Lsn(0x80) b/c leases:
    7894            2 :         // 0/10: initdb layer
    7895            2 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    7896            2 :         assert_eq!(res.layers_needed_by_leases, 7);
    7897            2 :         // Keeping 0/90 b/c it is the latest layer.
    7898            2 :         assert_eq!(res.layers_not_updated, 1);
    7899            2 :         // Removed 0/80.
    7900            2 :         assert_eq!(res.layers_removed, 1);
    7901            2 : 
    7902            2 :         // Make lease on a already GC-ed LSN.
    7903            2 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    7904            2 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    7905            2 :         timeline
    7906            2 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    7907            2 :             .expect_err("lease request on GC-ed LSN should fail");
    7908            2 : 
    7909            2 :         // Should still be able to renew a currently valid lease
    7910            2 :         // Assumption: original lease to is still valid for 0/50.
    7911            2 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    7912            2 :         timeline
    7913            2 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    7914            2 :             .expect("lease renewal with validation should succeed");
    7915            2 : 
    7916            2 :         Ok(())
    7917            2 :     }
    7918              : 
    7919              :     #[cfg(feature = "testing")]
    7920              :     #[tokio::test]
    7921            2 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    7922            2 :         test_simple_bottom_most_compaction_deltas_helper(
    7923            2 :             "test_simple_bottom_most_compaction_deltas_1",
    7924            2 :             false,
    7925            2 :         )
    7926          245 :         .await
    7927            2 :     }
    7928              : 
    7929              :     #[cfg(feature = "testing")]
    7930              :     #[tokio::test]
    7931            2 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    7932            2 :         test_simple_bottom_most_compaction_deltas_helper(
    7933            2 :             "test_simple_bottom_most_compaction_deltas_2",
    7934            2 :             true,
    7935            2 :         )
    7936          226 :         .await
    7937            2 :     }
    7938              : 
    7939              :     #[cfg(feature = "testing")]
    7940            4 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    7941            4 :         test_name: &'static str,
    7942            4 :         use_delta_bottom_layer: bool,
    7943            4 :     ) -> anyhow::Result<()> {
    7944            4 :         let harness = TenantHarness::create(test_name).await?;
    7945           40 :         let (tenant, ctx) = harness.load().await;
    7946              : 
    7947          276 :         fn get_key(id: u32) -> Key {
    7948          276 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7949          276 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7950          276 :             key.field6 = id;
    7951          276 :             key
    7952          276 :         }
    7953              : 
    7954              :         // We create
    7955              :         // - one bottom-most image layer,
    7956              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    7957              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    7958              :         // - a delta layer D3 above the horizon.
    7959              :         //
    7960              :         //                             | D3 |
    7961              :         //  | D1 |
    7962              :         // -|    |-- gc horizon -----------------
    7963              :         //  |    |                | D2 |
    7964              :         // --------- img layer ------------------
    7965              :         //
    7966              :         // What we should expact from this compaction is:
    7967              :         //                             | D3 |
    7968              :         //  | Part of D1 |
    7969              :         // --------- img layer with D1+D2 at GC horizon------------------
    7970              : 
    7971              :         // img layer at 0x10
    7972            4 :         let img_layer = (0..10)
    7973           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    7974            4 :             .collect_vec();
    7975            4 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    7976            4 :         let delta4 = (0..10)
    7977           40 :             .map(|id| {
    7978           40 :                 (
    7979           40 :                     get_key(id),
    7980           40 :                     Lsn(0x08),
    7981           40 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    7982           40 :                 )
    7983           40 :             })
    7984            4 :             .collect_vec();
    7985            4 : 
    7986            4 :         let delta1 = vec![
    7987            4 :             (
    7988            4 :                 get_key(1),
    7989            4 :                 Lsn(0x20),
    7990            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    7991            4 :             ),
    7992            4 :             (
    7993            4 :                 get_key(2),
    7994            4 :                 Lsn(0x30),
    7995            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    7996            4 :             ),
    7997            4 :             (
    7998            4 :                 get_key(3),
    7999            4 :                 Lsn(0x28),
    8000            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8001            4 :             ),
    8002            4 :             (
    8003            4 :                 get_key(3),
    8004            4 :                 Lsn(0x30),
    8005            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8006            4 :             ),
    8007            4 :             (
    8008            4 :                 get_key(3),
    8009            4 :                 Lsn(0x40),
    8010            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8011            4 :             ),
    8012            4 :         ];
    8013            4 :         let delta2 = vec![
    8014            4 :             (
    8015            4 :                 get_key(5),
    8016            4 :                 Lsn(0x20),
    8017            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8018            4 :             ),
    8019            4 :             (
    8020            4 :                 get_key(6),
    8021            4 :                 Lsn(0x20),
    8022            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8023            4 :             ),
    8024            4 :         ];
    8025            4 :         let delta3 = vec![
    8026            4 :             (
    8027            4 :                 get_key(8),
    8028            4 :                 Lsn(0x48),
    8029            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8030            4 :             ),
    8031            4 :             (
    8032            4 :                 get_key(9),
    8033            4 :                 Lsn(0x48),
    8034            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8035            4 :             ),
    8036            4 :         ];
    8037              : 
    8038            4 :         let tline = if use_delta_bottom_layer {
    8039            2 :             tenant
    8040            2 :                 .create_test_timeline_with_layers(
    8041            2 :                     TIMELINE_ID,
    8042            2 :                     Lsn(0x08),
    8043            2 :                     DEFAULT_PG_VERSION,
    8044            2 :                     &ctx,
    8045            2 :                     vec![
    8046            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8047            2 :                             Lsn(0x08)..Lsn(0x10),
    8048            2 :                             delta4,
    8049            2 :                         ),
    8050            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8051            2 :                             Lsn(0x20)..Lsn(0x48),
    8052            2 :                             delta1,
    8053            2 :                         ),
    8054            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8055            2 :                             Lsn(0x20)..Lsn(0x48),
    8056            2 :                             delta2,
    8057            2 :                         ),
    8058            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8059            2 :                             Lsn(0x48)..Lsn(0x50),
    8060            2 :                             delta3,
    8061            2 :                         ),
    8062            2 :                     ], // delta layers
    8063            2 :                     vec![], // image layers
    8064            2 :                     Lsn(0x50),
    8065            2 :                 )
    8066           30 :                 .await?
    8067              :         } else {
    8068            2 :             tenant
    8069            2 :                 .create_test_timeline_with_layers(
    8070            2 :                     TIMELINE_ID,
    8071            2 :                     Lsn(0x10),
    8072            2 :                     DEFAULT_PG_VERSION,
    8073            2 :                     &ctx,
    8074            2 :                     vec![
    8075            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8076            2 :                             Lsn(0x10)..Lsn(0x48),
    8077            2 :                             delta1,
    8078            2 :                         ),
    8079            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8080            2 :                             Lsn(0x10)..Lsn(0x48),
    8081            2 :                             delta2,
    8082            2 :                         ),
    8083            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8084            2 :                             Lsn(0x48)..Lsn(0x50),
    8085            2 :                             delta3,
    8086            2 :                         ),
    8087            2 :                     ], // delta layers
    8088            2 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8089            2 :                     Lsn(0x50),
    8090            2 :                 )
    8091           49 :                 .await?
    8092              :         };
    8093            4 :         {
    8094            4 :             // Update GC info
    8095            4 :             let mut guard = tline.gc_info.write().unwrap();
    8096            4 :             *guard = GcInfo {
    8097            4 :                 retain_lsns: vec![],
    8098            4 :                 cutoffs: GcCutoffs {
    8099            4 :                     time: Lsn(0x30),
    8100            4 :                     space: Lsn(0x30),
    8101            4 :                 },
    8102            4 :                 leases: Default::default(),
    8103            4 :                 within_ancestor_pitr: false,
    8104            4 :             };
    8105            4 :         }
    8106            4 : 
    8107            4 :         let expected_result = [
    8108            4 :             Bytes::from_static(b"value 0@0x10"),
    8109            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8110            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8111            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8112            4 :             Bytes::from_static(b"value 4@0x10"),
    8113            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8114            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8115            4 :             Bytes::from_static(b"value 7@0x10"),
    8116            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8117            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8118            4 :         ];
    8119            4 : 
    8120            4 :         let expected_result_at_gc_horizon = [
    8121            4 :             Bytes::from_static(b"value 0@0x10"),
    8122            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8123            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8124            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8125            4 :             Bytes::from_static(b"value 4@0x10"),
    8126            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8127            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8128            4 :             Bytes::from_static(b"value 7@0x10"),
    8129            4 :             Bytes::from_static(b"value 8@0x10"),
    8130            4 :             Bytes::from_static(b"value 9@0x10"),
    8131            4 :         ];
    8132              : 
    8133           44 :         for idx in 0..10 {
    8134           40 :             assert_eq!(
    8135           40 :                 tline
    8136           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8137           60 :                     .await
    8138           40 :                     .unwrap(),
    8139           40 :                 &expected_result[idx]
    8140              :             );
    8141           40 :             assert_eq!(
    8142           40 :                 tline
    8143           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8144           31 :                     .await
    8145           40 :                     .unwrap(),
    8146           40 :                 &expected_result_at_gc_horizon[idx]
    8147              :             );
    8148              :         }
    8149              : 
    8150            4 :         let cancel = CancellationToken::new();
    8151            4 :         tline
    8152            4 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8153          112 :             .await
    8154            4 :             .unwrap();
    8155              : 
    8156           44 :         for idx in 0..10 {
    8157           40 :             assert_eq!(
    8158           40 :                 tline
    8159           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8160           40 :                     .await
    8161           40 :                     .unwrap(),
    8162           40 :                 &expected_result[idx]
    8163              :             );
    8164           40 :             assert_eq!(
    8165           40 :                 tline
    8166           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8167           20 :                     .await
    8168           40 :                     .unwrap(),
    8169           40 :                 &expected_result_at_gc_horizon[idx]
    8170              :             );
    8171              :         }
    8172              : 
    8173              :         // increase GC horizon and compact again
    8174            4 :         {
    8175            4 :             // Update GC info
    8176            4 :             let mut guard = tline.gc_info.write().unwrap();
    8177            4 :             guard.cutoffs.time = Lsn(0x40);
    8178            4 :             guard.cutoffs.space = Lsn(0x40);
    8179            4 :         }
    8180            4 :         tline
    8181            4 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8182           89 :             .await
    8183            4 :             .unwrap();
    8184            4 : 
    8185            4 :         Ok(())
    8186            4 :     }
    8187              : 
    8188              :     #[cfg(feature = "testing")]
    8189              :     #[tokio::test]
    8190            2 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8191            2 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8192           20 :         let (tenant, ctx) = harness.load().await;
    8193            2 :         let tline = tenant
    8194            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8195            6 :             .await?;
    8196            2 :         tline.force_advance_lsn(Lsn(0x70));
    8197            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8198            2 :         let history = vec![
    8199            2 :             (
    8200            2 :                 key,
    8201            2 :                 Lsn(0x10),
    8202            2 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8203            2 :             ),
    8204            2 :             (
    8205            2 :                 key,
    8206            2 :                 Lsn(0x20),
    8207            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8208            2 :             ),
    8209            2 :             (
    8210            2 :                 key,
    8211            2 :                 Lsn(0x30),
    8212            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8213            2 :             ),
    8214            2 :             (
    8215            2 :                 key,
    8216            2 :                 Lsn(0x40),
    8217            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8218            2 :             ),
    8219            2 :             (
    8220            2 :                 key,
    8221            2 :                 Lsn(0x50),
    8222            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8223            2 :             ),
    8224            2 :             (
    8225            2 :                 key,
    8226            2 :                 Lsn(0x60),
    8227            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8228            2 :             ),
    8229            2 :             (
    8230            2 :                 key,
    8231            2 :                 Lsn(0x70),
    8232            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8233            2 :             ),
    8234            2 :             (
    8235            2 :                 key,
    8236            2 :                 Lsn(0x80),
    8237            2 :                 Value::Image(Bytes::copy_from_slice(
    8238            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8239            2 :                 )),
    8240            2 :             ),
    8241            2 :             (
    8242            2 :                 key,
    8243            2 :                 Lsn(0x90),
    8244            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8245            2 :             ),
    8246            2 :         ];
    8247            2 :         let res = tline
    8248            2 :             .generate_key_retention(
    8249            2 :                 key,
    8250            2 :                 &history,
    8251            2 :                 Lsn(0x60),
    8252            2 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8253            2 :                 3,
    8254            2 :                 None,
    8255            2 :             )
    8256            2 :             .await
    8257            2 :             .unwrap();
    8258            2 :         let expected_res = KeyHistoryRetention {
    8259            2 :             below_horizon: vec![
    8260            2 :                 (
    8261            2 :                     Lsn(0x20),
    8262            2 :                     KeyLogAtLsn(vec![(
    8263            2 :                         Lsn(0x20),
    8264            2 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8265            2 :                     )]),
    8266            2 :                 ),
    8267            2 :                 (
    8268            2 :                     Lsn(0x40),
    8269            2 :                     KeyLogAtLsn(vec![
    8270            2 :                         (
    8271            2 :                             Lsn(0x30),
    8272            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8273            2 :                         ),
    8274            2 :                         (
    8275            2 :                             Lsn(0x40),
    8276            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8277            2 :                         ),
    8278            2 :                     ]),
    8279            2 :                 ),
    8280            2 :                 (
    8281            2 :                     Lsn(0x50),
    8282            2 :                     KeyLogAtLsn(vec![(
    8283            2 :                         Lsn(0x50),
    8284            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    8285            2 :                     )]),
    8286            2 :                 ),
    8287            2 :                 (
    8288            2 :                     Lsn(0x60),
    8289            2 :                     KeyLogAtLsn(vec![(
    8290            2 :                         Lsn(0x60),
    8291            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8292            2 :                     )]),
    8293            2 :                 ),
    8294            2 :             ],
    8295            2 :             above_horizon: KeyLogAtLsn(vec![
    8296            2 :                 (
    8297            2 :                     Lsn(0x70),
    8298            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8299            2 :                 ),
    8300            2 :                 (
    8301            2 :                     Lsn(0x80),
    8302            2 :                     Value::Image(Bytes::copy_from_slice(
    8303            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8304            2 :                     )),
    8305            2 :                 ),
    8306            2 :                 (
    8307            2 :                     Lsn(0x90),
    8308            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8309            2 :                 ),
    8310            2 :             ]),
    8311            2 :         };
    8312            2 :         assert_eq!(res, expected_res);
    8313            2 : 
    8314            2 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    8315            2 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    8316            2 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    8317            2 :         // For example, we have
    8318            2 :         // ```plain
    8319            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    8320            2 :         // ```
    8321            2 :         // Now the GC horizon moves up, and we have
    8322            2 :         // ```plain
    8323            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    8324            2 :         // ```
    8325            2 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    8326            2 :         // We will end up with
    8327            2 :         // ```plain
    8328            2 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    8329            2 :         // ```
    8330            2 :         // Now we run the GC-compaction, and this key does not have a full history.
    8331            2 :         // We should be able to handle this partial history and drop everything before the
    8332            2 :         // gc_horizon image.
    8333            2 : 
    8334            2 :         let history = vec![
    8335            2 :             (
    8336            2 :                 key,
    8337            2 :                 Lsn(0x20),
    8338            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8339            2 :             ),
    8340            2 :             (
    8341            2 :                 key,
    8342            2 :                 Lsn(0x30),
    8343            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8344            2 :             ),
    8345            2 :             (
    8346            2 :                 key,
    8347            2 :                 Lsn(0x40),
    8348            2 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8349            2 :             ),
    8350            2 :             (
    8351            2 :                 key,
    8352            2 :                 Lsn(0x50),
    8353            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8354            2 :             ),
    8355            2 :             (
    8356            2 :                 key,
    8357            2 :                 Lsn(0x60),
    8358            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8359            2 :             ),
    8360            2 :             (
    8361            2 :                 key,
    8362            2 :                 Lsn(0x70),
    8363            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8364            2 :             ),
    8365            2 :             (
    8366            2 :                 key,
    8367            2 :                 Lsn(0x80),
    8368            2 :                 Value::Image(Bytes::copy_from_slice(
    8369            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8370            2 :                 )),
    8371            2 :             ),
    8372            2 :             (
    8373            2 :                 key,
    8374            2 :                 Lsn(0x90),
    8375            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8376            2 :             ),
    8377            2 :         ];
    8378            2 :         let res = tline
    8379            2 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    8380            2 :             .await
    8381            2 :             .unwrap();
    8382            2 :         let expected_res = KeyHistoryRetention {
    8383            2 :             below_horizon: vec![
    8384            2 :                 (
    8385            2 :                     Lsn(0x40),
    8386            2 :                     KeyLogAtLsn(vec![(
    8387            2 :                         Lsn(0x40),
    8388            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8389            2 :                     )]),
    8390            2 :                 ),
    8391            2 :                 (
    8392            2 :                     Lsn(0x50),
    8393            2 :                     KeyLogAtLsn(vec![(
    8394            2 :                         Lsn(0x50),
    8395            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8396            2 :                     )]),
    8397            2 :                 ),
    8398            2 :                 (
    8399            2 :                     Lsn(0x60),
    8400            2 :                     KeyLogAtLsn(vec![(
    8401            2 :                         Lsn(0x60),
    8402            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8403            2 :                     )]),
    8404            2 :                 ),
    8405            2 :             ],
    8406            2 :             above_horizon: KeyLogAtLsn(vec![
    8407            2 :                 (
    8408            2 :                     Lsn(0x70),
    8409            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8410            2 :                 ),
    8411            2 :                 (
    8412            2 :                     Lsn(0x80),
    8413            2 :                     Value::Image(Bytes::copy_from_slice(
    8414            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8415            2 :                     )),
    8416            2 :                 ),
    8417            2 :                 (
    8418            2 :                     Lsn(0x90),
    8419            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8420            2 :                 ),
    8421            2 :             ]),
    8422            2 :         };
    8423            2 :         assert_eq!(res, expected_res);
    8424            2 : 
    8425            2 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    8426            2 :         // the ancestor image in the test case.
    8427            2 : 
    8428            2 :         let history = vec![
    8429            2 :             (
    8430            2 :                 key,
    8431            2 :                 Lsn(0x20),
    8432            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8433            2 :             ),
    8434            2 :             (
    8435            2 :                 key,
    8436            2 :                 Lsn(0x30),
    8437            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8438            2 :             ),
    8439            2 :             (
    8440            2 :                 key,
    8441            2 :                 Lsn(0x40),
    8442            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8443            2 :             ),
    8444            2 :             (
    8445            2 :                 key,
    8446            2 :                 Lsn(0x70),
    8447            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8448            2 :             ),
    8449            2 :         ];
    8450            2 :         let res = tline
    8451            2 :             .generate_key_retention(
    8452            2 :                 key,
    8453            2 :                 &history,
    8454            2 :                 Lsn(0x60),
    8455            2 :                 &[],
    8456            2 :                 3,
    8457            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    8458            2 :             )
    8459            2 :             .await
    8460            2 :             .unwrap();
    8461            2 :         let expected_res = KeyHistoryRetention {
    8462            2 :             below_horizon: vec![(
    8463            2 :                 Lsn(0x60),
    8464            2 :                 KeyLogAtLsn(vec![(
    8465            2 :                     Lsn(0x60),
    8466            2 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    8467            2 :                 )]),
    8468            2 :             )],
    8469            2 :             above_horizon: KeyLogAtLsn(vec![(
    8470            2 :                 Lsn(0x70),
    8471            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8472            2 :             )]),
    8473            2 :         };
    8474            2 :         assert_eq!(res, expected_res);
    8475            2 : 
    8476            2 :         let history = vec![
    8477            2 :             (
    8478            2 :                 key,
    8479            2 :                 Lsn(0x20),
    8480            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8481            2 :             ),
    8482            2 :             (
    8483            2 :                 key,
    8484            2 :                 Lsn(0x40),
    8485            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8486            2 :             ),
    8487            2 :             (
    8488            2 :                 key,
    8489            2 :                 Lsn(0x60),
    8490            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8491            2 :             ),
    8492            2 :             (
    8493            2 :                 key,
    8494            2 :                 Lsn(0x70),
    8495            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8496            2 :             ),
    8497            2 :         ];
    8498            2 :         let res = tline
    8499            2 :             .generate_key_retention(
    8500            2 :                 key,
    8501            2 :                 &history,
    8502            2 :                 Lsn(0x60),
    8503            2 :                 &[Lsn(0x30)],
    8504            2 :                 3,
    8505            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    8506            2 :             )
    8507            2 :             .await
    8508            2 :             .unwrap();
    8509            2 :         let expected_res = KeyHistoryRetention {
    8510            2 :             below_horizon: vec![
    8511            2 :                 (
    8512            2 :                     Lsn(0x30),
    8513            2 :                     KeyLogAtLsn(vec![(
    8514            2 :                         Lsn(0x20),
    8515            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8516            2 :                     )]),
    8517            2 :                 ),
    8518            2 :                 (
    8519            2 :                     Lsn(0x60),
    8520            2 :                     KeyLogAtLsn(vec![(
    8521            2 :                         Lsn(0x60),
    8522            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    8523            2 :                     )]),
    8524            2 :                 ),
    8525            2 :             ],
    8526            2 :             above_horizon: KeyLogAtLsn(vec![(
    8527            2 :                 Lsn(0x70),
    8528            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8529            2 :             )]),
    8530            2 :         };
    8531            2 :         assert_eq!(res, expected_res);
    8532            2 : 
    8533            2 :         Ok(())
    8534            2 :     }
    8535              : 
    8536              :     #[cfg(feature = "testing")]
    8537              :     #[tokio::test]
    8538            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    8539            2 :         let harness =
    8540            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    8541           20 :         let (tenant, ctx) = harness.load().await;
    8542            2 : 
    8543          518 :         fn get_key(id: u32) -> Key {
    8544          518 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8545          518 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8546          518 :             key.field6 = id;
    8547          518 :             key
    8548          518 :         }
    8549            2 : 
    8550            2 :         let img_layer = (0..10)
    8551           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8552            2 :             .collect_vec();
    8553            2 : 
    8554            2 :         let delta1 = vec![
    8555            2 :             (
    8556            2 :                 get_key(1),
    8557            2 :                 Lsn(0x20),
    8558            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8559            2 :             ),
    8560            2 :             (
    8561            2 :                 get_key(2),
    8562            2 :                 Lsn(0x30),
    8563            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8564            2 :             ),
    8565            2 :             (
    8566            2 :                 get_key(3),
    8567            2 :                 Lsn(0x28),
    8568            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8569            2 :             ),
    8570            2 :             (
    8571            2 :                 get_key(3),
    8572            2 :                 Lsn(0x30),
    8573            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8574            2 :             ),
    8575            2 :             (
    8576            2 :                 get_key(3),
    8577            2 :                 Lsn(0x40),
    8578            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8579            2 :             ),
    8580            2 :         ];
    8581            2 :         let delta2 = vec![
    8582            2 :             (
    8583            2 :                 get_key(5),
    8584            2 :                 Lsn(0x20),
    8585            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8586            2 :             ),
    8587            2 :             (
    8588            2 :                 get_key(6),
    8589            2 :                 Lsn(0x20),
    8590            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8591            2 :             ),
    8592            2 :         ];
    8593            2 :         let delta3 = vec![
    8594            2 :             (
    8595            2 :                 get_key(8),
    8596            2 :                 Lsn(0x48),
    8597            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8598            2 :             ),
    8599            2 :             (
    8600            2 :                 get_key(9),
    8601            2 :                 Lsn(0x48),
    8602            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8603            2 :             ),
    8604            2 :         ];
    8605            2 : 
    8606            2 :         let tline = tenant
    8607            2 :             .create_test_timeline_with_layers(
    8608            2 :                 TIMELINE_ID,
    8609            2 :                 Lsn(0x10),
    8610            2 :                 DEFAULT_PG_VERSION,
    8611            2 :                 &ctx,
    8612            2 :                 vec![
    8613            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    8614            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    8615            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8616            2 :                 ], // delta layers
    8617            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8618            2 :                 Lsn(0x50),
    8619            2 :             )
    8620           49 :             .await?;
    8621            2 :         {
    8622            2 :             // Update GC info
    8623            2 :             let mut guard = tline.gc_info.write().unwrap();
    8624            2 :             *guard = GcInfo {
    8625            2 :                 retain_lsns: vec![
    8626            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    8627            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    8628            2 :                 ],
    8629            2 :                 cutoffs: GcCutoffs {
    8630            2 :                     time: Lsn(0x30),
    8631            2 :                     space: Lsn(0x30),
    8632            2 :                 },
    8633            2 :                 leases: Default::default(),
    8634            2 :                 within_ancestor_pitr: false,
    8635            2 :             };
    8636            2 :         }
    8637            2 : 
    8638            2 :         let expected_result = [
    8639            2 :             Bytes::from_static(b"value 0@0x10"),
    8640            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8641            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8642            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8643            2 :             Bytes::from_static(b"value 4@0x10"),
    8644            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8645            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8646            2 :             Bytes::from_static(b"value 7@0x10"),
    8647            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8648            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8649            2 :         ];
    8650            2 : 
    8651            2 :         let expected_result_at_gc_horizon = [
    8652            2 :             Bytes::from_static(b"value 0@0x10"),
    8653            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8654            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8655            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8656            2 :             Bytes::from_static(b"value 4@0x10"),
    8657            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8658            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8659            2 :             Bytes::from_static(b"value 7@0x10"),
    8660            2 :             Bytes::from_static(b"value 8@0x10"),
    8661            2 :             Bytes::from_static(b"value 9@0x10"),
    8662            2 :         ];
    8663            2 : 
    8664            2 :         let expected_result_at_lsn_20 = [
    8665            2 :             Bytes::from_static(b"value 0@0x10"),
    8666            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8667            2 :             Bytes::from_static(b"value 2@0x10"),
    8668            2 :             Bytes::from_static(b"value 3@0x10"),
    8669            2 :             Bytes::from_static(b"value 4@0x10"),
    8670            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8671            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8672            2 :             Bytes::from_static(b"value 7@0x10"),
    8673            2 :             Bytes::from_static(b"value 8@0x10"),
    8674            2 :             Bytes::from_static(b"value 9@0x10"),
    8675            2 :         ];
    8676            2 : 
    8677            2 :         let expected_result_at_lsn_10 = [
    8678            2 :             Bytes::from_static(b"value 0@0x10"),
    8679            2 :             Bytes::from_static(b"value 1@0x10"),
    8680            2 :             Bytes::from_static(b"value 2@0x10"),
    8681            2 :             Bytes::from_static(b"value 3@0x10"),
    8682            2 :             Bytes::from_static(b"value 4@0x10"),
    8683            2 :             Bytes::from_static(b"value 5@0x10"),
    8684            2 :             Bytes::from_static(b"value 6@0x10"),
    8685            2 :             Bytes::from_static(b"value 7@0x10"),
    8686            2 :             Bytes::from_static(b"value 8@0x10"),
    8687            2 :             Bytes::from_static(b"value 9@0x10"),
    8688            2 :         ];
    8689            2 : 
    8690           12 :         let verify_result = || async {
    8691           12 :             let gc_horizon = {
    8692           12 :                 let gc_info = tline.gc_info.read().unwrap();
    8693           12 :                 gc_info.cutoffs.time
    8694            2 :             };
    8695          132 :             for idx in 0..10 {
    8696          120 :                 assert_eq!(
    8697          120 :                     tline
    8698          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8699          121 :                         .await
    8700          120 :                         .unwrap(),
    8701          120 :                     &expected_result[idx]
    8702            2 :                 );
    8703          120 :                 assert_eq!(
    8704          120 :                     tline
    8705          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    8706           93 :                         .await
    8707          120 :                         .unwrap(),
    8708          120 :                     &expected_result_at_gc_horizon[idx]
    8709            2 :                 );
    8710          120 :                 assert_eq!(
    8711          120 :                     tline
    8712          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    8713           86 :                         .await
    8714          120 :                         .unwrap(),
    8715          120 :                     &expected_result_at_lsn_20[idx]
    8716            2 :                 );
    8717          120 :                 assert_eq!(
    8718          120 :                     tline
    8719          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    8720           61 :                         .await
    8721          120 :                         .unwrap(),
    8722          120 :                     &expected_result_at_lsn_10[idx]
    8723            2 :                 );
    8724            2 :             }
    8725           24 :         };
    8726            2 : 
    8727           69 :         verify_result().await;
    8728            2 : 
    8729            2 :         let cancel = CancellationToken::new();
    8730            2 :         let mut dryrun_flags = EnumSet::new();
    8731            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    8732            2 : 
    8733            2 :         tline
    8734            2 :             .compact_with_gc(&cancel, dryrun_flags, &ctx)
    8735           52 :             .await
    8736            2 :             .unwrap();
    8737            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
    8738            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    8739           57 :         verify_result().await;
    8740            2 : 
    8741            2 :         tline
    8742            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8743           53 :             .await
    8744            2 :             .unwrap();
    8745           64 :         verify_result().await;
    8746            2 : 
    8747            2 :         // compact again
    8748            2 :         tline
    8749            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8750           42 :             .await
    8751            2 :             .unwrap();
    8752           57 :         verify_result().await;
    8753            2 : 
    8754            2 :         // increase GC horizon and compact again
    8755            2 :         {
    8756            2 :             // Update GC info
    8757            2 :             let mut guard = tline.gc_info.write().unwrap();
    8758            2 :             guard.cutoffs.time = Lsn(0x38);
    8759            2 :             guard.cutoffs.space = Lsn(0x38);
    8760            2 :         }
    8761            2 :         tline
    8762            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8763           40 :             .await
    8764            2 :             .unwrap();
    8765           57 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    8766            2 : 
    8767            2 :         // not increasing the GC horizon and compact again
    8768            2 :         tline
    8769            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8770           42 :             .await
    8771            2 :             .unwrap();
    8772           57 :         verify_result().await;
    8773            2 : 
    8774            2 :         Ok(())
    8775            2 :     }
    8776              : 
    8777              :     #[cfg(feature = "testing")]
    8778              :     #[tokio::test]
    8779            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    8780            2 :     {
    8781            2 :         let harness =
    8782            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    8783            2 :                 .await?;
    8784           20 :         let (tenant, ctx) = harness.load().await;
    8785            2 : 
    8786          352 :         fn get_key(id: u32) -> Key {
    8787          352 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8788          352 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8789          352 :             key.field6 = id;
    8790          352 :             key
    8791          352 :         }
    8792            2 : 
    8793            2 :         let img_layer = (0..10)
    8794           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8795            2 :             .collect_vec();
    8796            2 : 
    8797            2 :         let delta1 = vec![
    8798            2 :             (
    8799            2 :                 get_key(1),
    8800            2 :                 Lsn(0x20),
    8801            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8802            2 :             ),
    8803            2 :             (
    8804            2 :                 get_key(1),
    8805            2 :                 Lsn(0x28),
    8806            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8807            2 :             ),
    8808            2 :         ];
    8809            2 :         let delta2 = vec![
    8810            2 :             (
    8811            2 :                 get_key(1),
    8812            2 :                 Lsn(0x30),
    8813            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8814            2 :             ),
    8815            2 :             (
    8816            2 :                 get_key(1),
    8817            2 :                 Lsn(0x38),
    8818            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    8819            2 :             ),
    8820            2 :         ];
    8821            2 :         let delta3 = vec![
    8822            2 :             (
    8823            2 :                 get_key(8),
    8824            2 :                 Lsn(0x48),
    8825            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8826            2 :             ),
    8827            2 :             (
    8828            2 :                 get_key(9),
    8829            2 :                 Lsn(0x48),
    8830            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8831            2 :             ),
    8832            2 :         ];
    8833            2 : 
    8834            2 :         let tline = tenant
    8835            2 :             .create_test_timeline_with_layers(
    8836            2 :                 TIMELINE_ID,
    8837            2 :                 Lsn(0x10),
    8838            2 :                 DEFAULT_PG_VERSION,
    8839            2 :                 &ctx,
    8840            2 :                 vec![
    8841            2 :                     // delta1 and delta 2 only contain a single key but multiple updates
    8842            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    8843            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    8844            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    8845            2 :                 ], // delta layers
    8846            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8847            2 :                 Lsn(0x50),
    8848            2 :             )
    8849           49 :             .await?;
    8850            2 :         {
    8851            2 :             // Update GC info
    8852            2 :             let mut guard = tline.gc_info.write().unwrap();
    8853            2 :             *guard = GcInfo {
    8854            2 :                 retain_lsns: vec![
    8855            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    8856            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    8857            2 :                 ],
    8858            2 :                 cutoffs: GcCutoffs {
    8859            2 :                     time: Lsn(0x30),
    8860            2 :                     space: Lsn(0x30),
    8861            2 :                 },
    8862            2 :                 leases: Default::default(),
    8863            2 :                 within_ancestor_pitr: false,
    8864            2 :             };
    8865            2 :         }
    8866            2 : 
    8867            2 :         let expected_result = [
    8868            2 :             Bytes::from_static(b"value 0@0x10"),
    8869            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    8870            2 :             Bytes::from_static(b"value 2@0x10"),
    8871            2 :             Bytes::from_static(b"value 3@0x10"),
    8872            2 :             Bytes::from_static(b"value 4@0x10"),
    8873            2 :             Bytes::from_static(b"value 5@0x10"),
    8874            2 :             Bytes::from_static(b"value 6@0x10"),
    8875            2 :             Bytes::from_static(b"value 7@0x10"),
    8876            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8877            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8878            2 :         ];
    8879            2 : 
    8880            2 :         let expected_result_at_gc_horizon = [
    8881            2 :             Bytes::from_static(b"value 0@0x10"),
    8882            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    8883            2 :             Bytes::from_static(b"value 2@0x10"),
    8884            2 :             Bytes::from_static(b"value 3@0x10"),
    8885            2 :             Bytes::from_static(b"value 4@0x10"),
    8886            2 :             Bytes::from_static(b"value 5@0x10"),
    8887            2 :             Bytes::from_static(b"value 6@0x10"),
    8888            2 :             Bytes::from_static(b"value 7@0x10"),
    8889            2 :             Bytes::from_static(b"value 8@0x10"),
    8890            2 :             Bytes::from_static(b"value 9@0x10"),
    8891            2 :         ];
    8892            2 : 
    8893            2 :         let expected_result_at_lsn_20 = [
    8894            2 :             Bytes::from_static(b"value 0@0x10"),
    8895            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8896            2 :             Bytes::from_static(b"value 2@0x10"),
    8897            2 :             Bytes::from_static(b"value 3@0x10"),
    8898            2 :             Bytes::from_static(b"value 4@0x10"),
    8899            2 :             Bytes::from_static(b"value 5@0x10"),
    8900            2 :             Bytes::from_static(b"value 6@0x10"),
    8901            2 :             Bytes::from_static(b"value 7@0x10"),
    8902            2 :             Bytes::from_static(b"value 8@0x10"),
    8903            2 :             Bytes::from_static(b"value 9@0x10"),
    8904            2 :         ];
    8905            2 : 
    8906            2 :         let expected_result_at_lsn_10 = [
    8907            2 :             Bytes::from_static(b"value 0@0x10"),
    8908            2 :             Bytes::from_static(b"value 1@0x10"),
    8909            2 :             Bytes::from_static(b"value 2@0x10"),
    8910            2 :             Bytes::from_static(b"value 3@0x10"),
    8911            2 :             Bytes::from_static(b"value 4@0x10"),
    8912            2 :             Bytes::from_static(b"value 5@0x10"),
    8913            2 :             Bytes::from_static(b"value 6@0x10"),
    8914            2 :             Bytes::from_static(b"value 7@0x10"),
    8915            2 :             Bytes::from_static(b"value 8@0x10"),
    8916            2 :             Bytes::from_static(b"value 9@0x10"),
    8917            2 :         ];
    8918            2 : 
    8919            8 :         let verify_result = || async {
    8920            8 :             let gc_horizon = {
    8921            8 :                 let gc_info = tline.gc_info.read().unwrap();
    8922            8 :                 gc_info.cutoffs.time
    8923            2 :             };
    8924           88 :             for idx in 0..10 {
    8925           80 :                 assert_eq!(
    8926           80 :                     tline
    8927           80 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8928           76 :                         .await
    8929           80 :                         .unwrap(),
    8930           80 :                     &expected_result[idx]
    8931            2 :                 );
    8932           80 :                 assert_eq!(
    8933           80 :                     tline
    8934           80 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    8935           46 :                         .await
    8936           80 :                         .unwrap(),
    8937           80 :                     &expected_result_at_gc_horizon[idx]
    8938            2 :                 );
    8939           80 :                 assert_eq!(
    8940           80 :                     tline
    8941           80 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    8942           48 :                         .await
    8943           80 :                         .unwrap(),
    8944           80 :                     &expected_result_at_lsn_20[idx]
    8945            2 :                 );
    8946           80 :                 assert_eq!(
    8947           80 :                     tline
    8948           80 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    8949           41 :                         .await
    8950           80 :                         .unwrap(),
    8951           80 :                     &expected_result_at_lsn_10[idx]
    8952            2 :                 );
    8953            2 :             }
    8954           16 :         };
    8955            2 : 
    8956           61 :         verify_result().await;
    8957            2 : 
    8958            2 :         let cancel = CancellationToken::new();
    8959            2 :         let mut dryrun_flags = EnumSet::new();
    8960            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    8961            2 : 
    8962            2 :         tline
    8963            2 :             .compact_with_gc(&cancel, dryrun_flags, &ctx)
    8964           49 :             .await
    8965            2 :             .unwrap();
    8966            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
    8967            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    8968           49 :         verify_result().await;
    8969            2 : 
    8970            2 :         tline
    8971            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8972           55 :             .await
    8973            2 :             .unwrap();
    8974           54 :         verify_result().await;
    8975            2 : 
    8976            2 :         // compact again
    8977            2 :         tline
    8978            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8979           41 :             .await
    8980            2 :             .unwrap();
    8981           47 :         verify_result().await;
    8982            2 : 
    8983            2 :         Ok(())
    8984            2 :     }
    8985              : 
    8986              :     #[cfg(feature = "testing")]
    8987              :     #[tokio::test]
    8988            2 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    8989            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    8990           20 :         let (tenant, ctx) = harness.load().await;
    8991            2 : 
    8992          126 :         fn get_key(id: u32) -> Key {
    8993          126 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8994          126 :             key.field6 = id;
    8995          126 :             key
    8996          126 :         }
    8997            2 : 
    8998            2 :         let img_layer = (0..10)
    8999           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9000            2 :             .collect_vec();
    9001            2 : 
    9002            2 :         let delta1 = vec![
    9003            2 :             (
    9004            2 :                 get_key(1),
    9005            2 :                 Lsn(0x20),
    9006            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9007            2 :             ),
    9008            2 :             (
    9009            2 :                 get_key(2),
    9010            2 :                 Lsn(0x30),
    9011            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9012            2 :             ),
    9013            2 :             (
    9014            2 :                 get_key(3),
    9015            2 :                 Lsn(0x28),
    9016            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9017            2 :             ),
    9018            2 :             (
    9019            2 :                 get_key(3),
    9020            2 :                 Lsn(0x30),
    9021            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9022            2 :             ),
    9023            2 :             (
    9024            2 :                 get_key(3),
    9025            2 :                 Lsn(0x40),
    9026            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9027            2 :             ),
    9028            2 :         ];
    9029            2 :         let delta2 = vec![
    9030            2 :             (
    9031            2 :                 get_key(5),
    9032            2 :                 Lsn(0x20),
    9033            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9034            2 :             ),
    9035            2 :             (
    9036            2 :                 get_key(6),
    9037            2 :                 Lsn(0x20),
    9038            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9039            2 :             ),
    9040            2 :         ];
    9041            2 :         let delta3 = vec![
    9042            2 :             (
    9043            2 :                 get_key(8),
    9044            2 :                 Lsn(0x48),
    9045            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9046            2 :             ),
    9047            2 :             (
    9048            2 :                 get_key(9),
    9049            2 :                 Lsn(0x48),
    9050            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9051            2 :             ),
    9052            2 :         ];
    9053            2 : 
    9054            2 :         let parent_tline = tenant
    9055            2 :             .create_test_timeline_with_layers(
    9056            2 :                 TIMELINE_ID,
    9057            2 :                 Lsn(0x10),
    9058            2 :                 DEFAULT_PG_VERSION,
    9059            2 :                 &ctx,
    9060            2 :                 vec![],                       // delta layers
    9061            2 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9062            2 :                 Lsn(0x18),
    9063            2 :             )
    9064           31 :             .await?;
    9065            2 : 
    9066            2 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9067            2 : 
    9068            2 :         let branch_tline = tenant
    9069            2 :             .branch_timeline_test_with_layers(
    9070            2 :                 &parent_tline,
    9071            2 :                 NEW_TIMELINE_ID,
    9072            2 :                 Some(Lsn(0x18)),
    9073            2 :                 &ctx,
    9074            2 :                 vec![
    9075            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9076            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9077            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9078            2 :                 ], // delta layers
    9079            2 :                 vec![], // image layers
    9080            2 :                 Lsn(0x50),
    9081            2 :             )
    9082           20 :             .await?;
    9083            2 : 
    9084            2 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9085            2 : 
    9086            2 :         {
    9087            2 :             // Update GC info
    9088            2 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9089            2 :             *guard = GcInfo {
    9090            2 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9091            2 :                 cutoffs: GcCutoffs {
    9092            2 :                     time: Lsn(0x10),
    9093            2 :                     space: Lsn(0x10),
    9094            2 :                 },
    9095            2 :                 leases: Default::default(),
    9096            2 :                 within_ancestor_pitr: false,
    9097            2 :             };
    9098            2 :         }
    9099            2 : 
    9100            2 :         {
    9101            2 :             // Update GC info
    9102            2 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9103            2 :             *guard = GcInfo {
    9104            2 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9105            2 :                 cutoffs: GcCutoffs {
    9106            2 :                     time: Lsn(0x50),
    9107            2 :                     space: Lsn(0x50),
    9108            2 :                 },
    9109            2 :                 leases: Default::default(),
    9110            2 :                 within_ancestor_pitr: false,
    9111            2 :             };
    9112            2 :         }
    9113            2 : 
    9114            2 :         let expected_result_at_gc_horizon = [
    9115            2 :             Bytes::from_static(b"value 0@0x10"),
    9116            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9117            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9118            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9119            2 :             Bytes::from_static(b"value 4@0x10"),
    9120            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9121            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9122            2 :             Bytes::from_static(b"value 7@0x10"),
    9123            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9124            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9125            2 :         ];
    9126            2 : 
    9127            2 :         let expected_result_at_lsn_40 = [
    9128            2 :             Bytes::from_static(b"value 0@0x10"),
    9129            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9130            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9131            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9132            2 :             Bytes::from_static(b"value 4@0x10"),
    9133            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9134            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9135            2 :             Bytes::from_static(b"value 7@0x10"),
    9136            2 :             Bytes::from_static(b"value 8@0x10"),
    9137            2 :             Bytes::from_static(b"value 9@0x10"),
    9138            2 :         ];
    9139            2 : 
    9140            4 :         let verify_result = || async {
    9141           44 :             for idx in 0..10 {
    9142           40 :                 assert_eq!(
    9143           40 :                     branch_tline
    9144           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9145           50 :                         .await
    9146           40 :                         .unwrap(),
    9147           40 :                     &expected_result_at_gc_horizon[idx]
    9148            2 :                 );
    9149           40 :                 assert_eq!(
    9150           40 :                     branch_tline
    9151           40 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9152           31 :                         .await
    9153           40 :                         .unwrap(),
    9154           40 :                     &expected_result_at_lsn_40[idx]
    9155            2 :                 );
    9156            2 :             }
    9157            8 :         };
    9158            2 : 
    9159           45 :         verify_result().await;
    9160            2 : 
    9161            2 :         let cancel = CancellationToken::new();
    9162            2 :         branch_tline
    9163            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    9164           19 :             .await
    9165            2 :             .unwrap();
    9166            2 : 
    9167           36 :         verify_result().await;
    9168            2 : 
    9169            2 :         Ok(())
    9170            2 :     }
    9171              : 
    9172              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9173              :     // Create an image arrangement where we have to read at different LSN ranges
    9174              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9175              :     // a delta layer. Like so:
    9176              :     //
    9177              :     //     A      B
    9178              :     // +----------------+ -> delta_layer
    9179              :     // |                |                           ^ lsn
    9180              :     // |       =========|-> nested_image_layer      |
    9181              :     // |       C        |                           |
    9182              :     // +----------------+                           |
    9183              :     // ======== -> baseline_image_layer             +-------> key
    9184              :     //
    9185              :     //
    9186              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9187              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9188              :     #[cfg(feature = "testing")]
    9189              :     #[tokio::test]
    9190            2 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9191            2 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9192           20 :         let (tenant, ctx) = harness.load().await;
    9193            2 : 
    9194            2 :         let will_init_keys = [2, 6];
    9195           44 :         fn get_key(id: u32) -> Key {
    9196           44 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9197           44 :             key.field6 = id;
    9198           44 :             key
    9199           44 :         }
    9200            2 : 
    9201            2 :         let mut expected_key_values = HashMap::new();
    9202            2 : 
    9203            2 :         let baseline_image_layer_lsn = Lsn(0x10);
    9204            2 :         let mut baseline_img_layer = Vec::new();
    9205           12 :         for i in 0..5 {
    9206           10 :             let key = get_key(i);
    9207           10 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
    9208           10 : 
    9209           10 :             let removed = expected_key_values.insert(key, value.clone());
    9210           10 :             assert!(removed.is_none());
    9211            2 : 
    9212           10 :             baseline_img_layer.push((key, Bytes::from(value)));
    9213            2 :         }
    9214            2 : 
    9215            2 :         let nested_image_layer_lsn = Lsn(0x50);
    9216            2 :         let mut nested_img_layer = Vec::new();
    9217           12 :         for i in 5..10 {
    9218           10 :             let key = get_key(i);
    9219           10 :             let value = format!("value {i}@{nested_image_layer_lsn}");
    9220           10 : 
    9221           10 :             let removed = expected_key_values.insert(key, value.clone());
    9222           10 :             assert!(removed.is_none());
    9223            2 : 
    9224           10 :             nested_img_layer.push((key, Bytes::from(value)));
    9225            2 :         }
    9226            2 : 
    9227            2 :         let mut delta_layer_spec = Vec::default();
    9228            2 :         let delta_layer_start_lsn = Lsn(0x20);
    9229            2 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
    9230            2 : 
    9231           22 :         for i in 0..10 {
    9232           20 :             let key = get_key(i);
    9233           20 :             let key_in_nested = nested_img_layer
    9234           20 :                 .iter()
    9235           80 :                 .any(|(key_with_img, _)| *key_with_img == key);
    9236           20 :             let lsn = {
    9237           20 :                 if key_in_nested {
    9238           10 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
    9239            2 :                 } else {
    9240           10 :                     delta_layer_start_lsn
    9241            2 :                 }
    9242            2 :             };
    9243            2 : 
    9244           20 :             let will_init = will_init_keys.contains(&i);
    9245           20 :             if will_init {
    9246            4 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
    9247            4 : 
    9248            4 :                 expected_key_values.insert(key, "".to_string());
    9249           16 :             } else {
    9250           16 :                 let delta = format!("@{lsn}");
    9251           16 :                 delta_layer_spec.push((
    9252           16 :                     key,
    9253           16 :                     lsn,
    9254           16 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
    9255           16 :                 ));
    9256           16 : 
    9257           16 :                 expected_key_values
    9258           16 :                     .get_mut(&key)
    9259           16 :                     .expect("An image exists for each key")
    9260           16 :                     .push_str(delta.as_str());
    9261           16 :             }
    9262           20 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
    9263            2 :         }
    9264            2 : 
    9265            2 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
    9266            2 : 
    9267            2 :         assert!(
    9268            2 :             nested_image_layer_lsn > delta_layer_start_lsn
    9269            2 :                 && nested_image_layer_lsn < delta_layer_end_lsn
    9270            2 :         );
    9271            2 : 
    9272            2 :         let tline = tenant
    9273            2 :             .create_test_timeline_with_layers(
    9274            2 :                 TIMELINE_ID,
    9275            2 :                 baseline_image_layer_lsn,
    9276            2 :                 DEFAULT_PG_VERSION,
    9277            2 :                 &ctx,
    9278            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9279            2 :                     delta_layer_start_lsn..delta_layer_end_lsn,
    9280            2 :                     delta_layer_spec,
    9281            2 :                 )], // delta layers
    9282            2 :                 vec![
    9283            2 :                     (baseline_image_layer_lsn, baseline_img_layer),
    9284            2 :                     (nested_image_layer_lsn, nested_img_layer),
    9285            2 :                 ], // image layers
    9286            2 :                 delta_layer_end_lsn,
    9287            2 :             )
    9288           42 :             .await?;
    9289            2 : 
    9290            2 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
    9291            2 :         let results = tline
    9292            2 :             .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
    9293           13 :             .await
    9294            2 :             .expect("No vectored errors");
    9295           22 :         for (key, res) in results {
    9296           20 :             let value = res.expect("No key errors");
    9297           20 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
    9298           20 :             assert_eq!(value, Bytes::from(expected_value));
    9299            2 :         }
    9300            2 : 
    9301            2 :         Ok(())
    9302            2 :     }
    9303              : 
    9304          142 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
    9305          142 :         (
    9306          142 :             k1.is_delta,
    9307          142 :             k1.key_range.start,
    9308          142 :             k1.key_range.end,
    9309          142 :             k1.lsn_range.start,
    9310          142 :             k1.lsn_range.end,
    9311          142 :         )
    9312          142 :             .cmp(&(
    9313          142 :                 k2.is_delta,
    9314          142 :                 k2.key_range.start,
    9315          142 :                 k2.key_range.end,
    9316          142 :                 k2.lsn_range.start,
    9317          142 :                 k2.lsn_range.end,
    9318          142 :             ))
    9319          142 :     }
    9320              : 
    9321           12 :     async fn inspect_and_sort(
    9322           12 :         tline: &Arc<Timeline>,
    9323           12 :         filter: Option<std::ops::Range<Key>>,
    9324           12 :     ) -> Vec<PersistentLayerKey> {
    9325           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
    9326           12 :         if let Some(filter) = filter {
    9327           64 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
    9328           10 :         }
    9329           12 :         all_layers.sort_by(sort_layer_key);
    9330           12 :         all_layers
    9331           12 :     }
    9332              : 
    9333              :     #[cfg(feature = "testing")]
    9334           10 :     fn check_layer_map_key_eq(
    9335           10 :         mut left: Vec<PersistentLayerKey>,
    9336           10 :         mut right: Vec<PersistentLayerKey>,
    9337           10 :     ) {
    9338           10 :         left.sort_by(sort_layer_key);
    9339           10 :         right.sort_by(sort_layer_key);
    9340           10 :         if left != right {
    9341            0 :             eprintln!("---LEFT---");
    9342            0 :             for left in left.iter() {
    9343            0 :                 eprintln!("{}", left);
    9344            0 :             }
    9345            0 :             eprintln!("---RIGHT---");
    9346            0 :             for right in right.iter() {
    9347            0 :                 eprintln!("{}", right);
    9348            0 :             }
    9349            0 :             assert_eq!(left, right);
    9350           10 :         }
    9351           10 :     }
    9352              : 
    9353              :     #[cfg(feature = "testing")]
    9354              :     #[tokio::test]
    9355            2 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
    9356            2 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
    9357           20 :         let (tenant, ctx) = harness.load().await;
    9358            2 : 
    9359          182 :         fn get_key(id: u32) -> Key {
    9360          182 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9361          182 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9362          182 :             key.field6 = id;
    9363          182 :             key
    9364          182 :         }
    9365            2 : 
    9366            2 :         // img layer at 0x10
    9367            2 :         let img_layer = (0..10)
    9368           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9369            2 :             .collect_vec();
    9370            2 : 
    9371            2 :         let delta1 = vec![
    9372            2 :             (
    9373            2 :                 get_key(1),
    9374            2 :                 Lsn(0x20),
    9375            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    9376            2 :             ),
    9377            2 :             (
    9378            2 :                 get_key(2),
    9379            2 :                 Lsn(0x30),
    9380            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    9381            2 :             ),
    9382            2 :             (
    9383            2 :                 get_key(3),
    9384            2 :                 Lsn(0x40),
    9385            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    9386            2 :             ),
    9387            2 :         ];
    9388            2 :         let delta2 = vec![
    9389            2 :             (
    9390            2 :                 get_key(5),
    9391            2 :                 Lsn(0x20),
    9392            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    9393            2 :             ),
    9394            2 :             (
    9395            2 :                 get_key(6),
    9396            2 :                 Lsn(0x20),
    9397            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    9398            2 :             ),
    9399            2 :         ];
    9400            2 :         let delta3 = vec![
    9401            2 :             (
    9402            2 :                 get_key(8),
    9403            2 :                 Lsn(0x48),
    9404            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    9405            2 :             ),
    9406            2 :             (
    9407            2 :                 get_key(9),
    9408            2 :                 Lsn(0x48),
    9409            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    9410            2 :             ),
    9411            2 :         ];
    9412            2 : 
    9413            2 :         let tline = tenant
    9414            2 :             .create_test_timeline_with_layers(
    9415            2 :                 TIMELINE_ID,
    9416            2 :                 Lsn(0x10),
    9417            2 :                 DEFAULT_PG_VERSION,
    9418            2 :                 &ctx,
    9419            2 :                 vec![
    9420            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9421            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9422            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9423            2 :                 ], // delta layers
    9424            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9425            2 :                 Lsn(0x50),
    9426            2 :             )
    9427           49 :             .await?;
    9428            2 : 
    9429            2 :         {
    9430            2 :             // Update GC info
    9431            2 :             let mut guard = tline.gc_info.write().unwrap();
    9432            2 :             *guard = GcInfo {
    9433            2 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
    9434            2 :                 cutoffs: GcCutoffs {
    9435            2 :                     time: Lsn(0x30),
    9436            2 :                     space: Lsn(0x30),
    9437            2 :                 },
    9438            2 :                 leases: Default::default(),
    9439            2 :                 within_ancestor_pitr: false,
    9440            2 :             };
    9441            2 :         }
    9442            2 : 
    9443            2 :         let cancel = CancellationToken::new();
    9444            2 : 
    9445            2 :         // Do a partial compaction on key range 0..2
    9446            2 :         tline
    9447            2 :             .partial_compact_with_gc(get_key(0)..get_key(2), &cancel, EnumSet::new(), &ctx)
    9448           27 :             .await
    9449            2 :             .unwrap();
    9450            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9451            2 :         check_layer_map_key_eq(
    9452            2 :             all_layers,
    9453            2 :             vec![
    9454            2 :                 // newly-generated image layer for the partial compaction range 0-2
    9455            2 :                 PersistentLayerKey {
    9456            2 :                     key_range: get_key(0)..get_key(2),
    9457            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9458            2 :                     is_delta: false,
    9459            2 :                 },
    9460            2 :                 PersistentLayerKey {
    9461            2 :                     key_range: get_key(0)..get_key(10),
    9462            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9463            2 :                     is_delta: false,
    9464            2 :                 },
    9465            2 :                 // delta1 is split and the second part is rewritten
    9466            2 :                 PersistentLayerKey {
    9467            2 :                     key_range: get_key(2)..get_key(4),
    9468            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9469            2 :                     is_delta: true,
    9470            2 :                 },
    9471            2 :                 PersistentLayerKey {
    9472            2 :                     key_range: get_key(5)..get_key(7),
    9473            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9474            2 :                     is_delta: true,
    9475            2 :                 },
    9476            2 :                 PersistentLayerKey {
    9477            2 :                     key_range: get_key(8)..get_key(10),
    9478            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9479            2 :                     is_delta: true,
    9480            2 :                 },
    9481            2 :             ],
    9482            2 :         );
    9483            2 : 
    9484            2 :         // Do a partial compaction on key range 2..4
    9485            2 :         tline
    9486            2 :             .partial_compact_with_gc(get_key(2)..get_key(4), &cancel, EnumSet::new(), &ctx)
    9487           17 :             .await
    9488            2 :             .unwrap();
    9489            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9490            2 :         check_layer_map_key_eq(
    9491            2 :             all_layers,
    9492            2 :             vec![
    9493            2 :                 PersistentLayerKey {
    9494            2 :                     key_range: get_key(0)..get_key(2),
    9495            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9496            2 :                     is_delta: false,
    9497            2 :                 },
    9498            2 :                 PersistentLayerKey {
    9499            2 :                     key_range: get_key(0)..get_key(10),
    9500            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9501            2 :                     is_delta: false,
    9502            2 :                 },
    9503            2 :                 // image layer generated for the compaction range 2-4
    9504            2 :                 PersistentLayerKey {
    9505            2 :                     key_range: get_key(2)..get_key(4),
    9506            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9507            2 :                     is_delta: false,
    9508            2 :                 },
    9509            2 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
    9510            2 :                 PersistentLayerKey {
    9511            2 :                     key_range: get_key(2)..get_key(4),
    9512            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9513            2 :                     is_delta: true,
    9514            2 :                 },
    9515            2 :                 PersistentLayerKey {
    9516            2 :                     key_range: get_key(5)..get_key(7),
    9517            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9518            2 :                     is_delta: true,
    9519            2 :                 },
    9520            2 :                 PersistentLayerKey {
    9521            2 :                     key_range: get_key(8)..get_key(10),
    9522            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9523            2 :                     is_delta: true,
    9524            2 :                 },
    9525            2 :             ],
    9526            2 :         );
    9527            2 : 
    9528            2 :         // Do a partial compaction on key range 4..9
    9529            2 :         tline
    9530            2 :             .partial_compact_with_gc(get_key(4)..get_key(9), &cancel, EnumSet::new(), &ctx)
    9531           22 :             .await
    9532            2 :             .unwrap();
    9533            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9534            2 :         check_layer_map_key_eq(
    9535            2 :             all_layers,
    9536            2 :             vec![
    9537            2 :                 PersistentLayerKey {
    9538            2 :                     key_range: get_key(0)..get_key(2),
    9539            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9540            2 :                     is_delta: false,
    9541            2 :                 },
    9542            2 :                 PersistentLayerKey {
    9543            2 :                     key_range: get_key(0)..get_key(10),
    9544            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9545            2 :                     is_delta: false,
    9546            2 :                 },
    9547            2 :                 PersistentLayerKey {
    9548            2 :                     key_range: get_key(2)..get_key(4),
    9549            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9550            2 :                     is_delta: false,
    9551            2 :                 },
    9552            2 :                 PersistentLayerKey {
    9553            2 :                     key_range: get_key(2)..get_key(4),
    9554            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9555            2 :                     is_delta: true,
    9556            2 :                 },
    9557            2 :                 // image layer generated for this compaction range
    9558            2 :                 PersistentLayerKey {
    9559            2 :                     key_range: get_key(4)..get_key(9),
    9560            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9561            2 :                     is_delta: false,
    9562            2 :                 },
    9563            2 :                 PersistentLayerKey {
    9564            2 :                     key_range: get_key(8)..get_key(10),
    9565            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9566            2 :                     is_delta: true,
    9567            2 :                 },
    9568            2 :             ],
    9569            2 :         );
    9570            2 : 
    9571            2 :         // Do a partial compaction on key range 9..10
    9572            2 :         tline
    9573            2 :             .partial_compact_with_gc(get_key(9)..get_key(10), &cancel, EnumSet::new(), &ctx)
    9574            9 :             .await
    9575            2 :             .unwrap();
    9576            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9577            2 :         check_layer_map_key_eq(
    9578            2 :             all_layers,
    9579            2 :             vec![
    9580            2 :                 PersistentLayerKey {
    9581            2 :                     key_range: get_key(0)..get_key(2),
    9582            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9583            2 :                     is_delta: false,
    9584            2 :                 },
    9585            2 :                 PersistentLayerKey {
    9586            2 :                     key_range: get_key(0)..get_key(10),
    9587            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9588            2 :                     is_delta: false,
    9589            2 :                 },
    9590            2 :                 PersistentLayerKey {
    9591            2 :                     key_range: get_key(2)..get_key(4),
    9592            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9593            2 :                     is_delta: false,
    9594            2 :                 },
    9595            2 :                 PersistentLayerKey {
    9596            2 :                     key_range: get_key(2)..get_key(4),
    9597            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9598            2 :                     is_delta: true,
    9599            2 :                 },
    9600            2 :                 PersistentLayerKey {
    9601            2 :                     key_range: get_key(4)..get_key(9),
    9602            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9603            2 :                     is_delta: false,
    9604            2 :                 },
    9605            2 :                 // image layer generated for the compaction range
    9606            2 :                 PersistentLayerKey {
    9607            2 :                     key_range: get_key(9)..get_key(10),
    9608            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9609            2 :                     is_delta: false,
    9610            2 :                 },
    9611            2 :                 PersistentLayerKey {
    9612            2 :                     key_range: get_key(8)..get_key(10),
    9613            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9614            2 :                     is_delta: true,
    9615            2 :                 },
    9616            2 :             ],
    9617            2 :         );
    9618            2 : 
    9619            2 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
    9620            2 :         tline
    9621            2 :             .partial_compact_with_gc(get_key(0)..get_key(10), &cancel, EnumSet::new(), &ctx)
    9622           50 :             .await
    9623            2 :             .unwrap();
    9624            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9625            2 :         check_layer_map_key_eq(
    9626            2 :             all_layers,
    9627            2 :             vec![
    9628            2 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
    9629            2 :                 PersistentLayerKey {
    9630            2 :                     key_range: get_key(0)..get_key(10),
    9631            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9632            2 :                     is_delta: false,
    9633            2 :                 },
    9634            2 :                 PersistentLayerKey {
    9635            2 :                     key_range: get_key(2)..get_key(4),
    9636            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9637            2 :                     is_delta: true,
    9638            2 :                 },
    9639            2 :                 PersistentLayerKey {
    9640            2 :                     key_range: get_key(8)..get_key(10),
    9641            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9642            2 :                     is_delta: true,
    9643            2 :                 },
    9644            2 :             ],
    9645            2 :         );
    9646            2 : 
    9647            2 :         Ok(())
    9648            2 :     }
    9649              : }
        

Generated by: LCOV version 2.1-beta