LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 09e7485004805bd42b53a0c369170b3228136512.info Lines: 76.0 % 7337 5579
Test Date: 2024-11-21 18:36:18 Functions: 58.6 % 430 252

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

Generated by: LCOV version 2.1-beta