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

Generated by: LCOV version 2.1-beta