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

Generated by: LCOV version 2.1-beta