LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: f2bfe5dc5ab550768e936d6bc7b94d9b2e2d4cc9.info Lines: 76.8 % 8443 6486
Test Date: 2025-01-27 20:39:28 Functions: 60.6 % 429 260

            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::CompactInfoResponse;
      25              : use pageserver_api::models::LsnLease;
      26              : use pageserver_api::models::TimelineArchivalState;
      27              : use pageserver_api::models::TimelineState;
      28              : use pageserver_api::models::TopTenantShardItem;
      29              : use pageserver_api::models::WalRedoManagerStatus;
      30              : use pageserver_api::shard::ShardIdentity;
      31              : use pageserver_api::shard::ShardStripeSize;
      32              : use pageserver_api::shard::TenantShardId;
      33              : use remote_storage::DownloadError;
      34              : use remote_storage::GenericRemoteStorage;
      35              : use remote_storage::TimeoutOrCancel;
      36              : use remote_timeline_client::manifest::{
      37              :     OffloadedTimelineManifest, TenantManifest, LATEST_TENANT_MANIFEST_VERSION,
      38              : };
      39              : use remote_timeline_client::UploadQueueNotReadyError;
      40              : use std::collections::BTreeMap;
      41              : use std::fmt;
      42              : use std::future::Future;
      43              : use std::sync::atomic::AtomicBool;
      44              : use std::sync::Weak;
      45              : use std::time::SystemTime;
      46              : use storage_broker::BrokerClientChannel;
      47              : use timeline::compaction::GcCompactionQueue;
      48              : use timeline::import_pgdata;
      49              : use timeline::offload::offload_timeline;
      50              : use timeline::offload::OffloadError;
      51              : use timeline::CompactOptions;
      52              : use timeline::ShutdownMode;
      53              : use tokio::io::BufReader;
      54              : use tokio::sync::watch;
      55              : use tokio::task::JoinSet;
      56              : use tokio_util::sync::CancellationToken;
      57              : use tracing::*;
      58              : use upload_queue::NotInitialized;
      59              : use utils::backoff;
      60              : use utils::circuit_breaker::CircuitBreaker;
      61              : use utils::completion;
      62              : use utils::crashsafe::path_with_suffix_extension;
      63              : use utils::failpoint_support;
      64              : use utils::fs_ext;
      65              : use utils::pausable_failpoint;
      66              : use utils::sync::gate::Gate;
      67              : use utils::sync::gate::GateGuard;
      68              : use utils::timeout::timeout_cancellable;
      69              : use utils::timeout::TimeoutCancellableError;
      70              : use utils::try_rcu::ArcSwapExt;
      71              : use utils::zstd::create_zst_tarball;
      72              : use utils::zstd::extract_zst_tarball;
      73              : 
      74              : use self::config::AttachedLocationConfig;
      75              : use self::config::AttachmentMode;
      76              : use self::config::LocationConf;
      77              : use self::config::TenantConf;
      78              : use self::metadata::TimelineMetadata;
      79              : use self::mgr::GetActiveTenantError;
      80              : use self::mgr::GetTenantError;
      81              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      82              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      83              : use self::timeline::uninit::TimelineCreateGuard;
      84              : use self::timeline::uninit::TimelineExclusionError;
      85              : use self::timeline::uninit::UninitializedTimeline;
      86              : use self::timeline::EvictionTaskTenantState;
      87              : use self::timeline::GcCutoffs;
      88              : use self::timeline::TimelineDeleteProgress;
      89              : use self::timeline::TimelineResources;
      90              : use self::timeline::WaitLsnError;
      91              : use crate::config::PageServerConf;
      92              : use crate::context::{DownloadBehavior, RequestContext};
      93              : use crate::deletion_queue::DeletionQueueClient;
      94              : use crate::deletion_queue::DeletionQueueError;
      95              : use crate::import_datadir;
      96              : use crate::is_uninit_mark;
      97              : use crate::l0_flush::L0FlushGlobalState;
      98              : use crate::metrics::CONCURRENT_INITDBS;
      99              : use crate::metrics::INITDB_RUN_TIME;
     100              : use crate::metrics::INITDB_SEMAPHORE_ACQUISITION_TIME;
     101              : use crate::metrics::TENANT;
     102              : use crate::metrics::{
     103              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
     104              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
     105              : };
     106              : use crate::task_mgr;
     107              : use crate::task_mgr::TaskKind;
     108              : use crate::tenant::config::LocationMode;
     109              : use crate::tenant::config::TenantConfOpt;
     110              : use crate::tenant::gc_result::GcResult;
     111              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     112              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     113              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     114              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     115              : use crate::tenant::storage_layer::DeltaLayer;
     116              : use crate::tenant::storage_layer::ImageLayer;
     117              : use crate::walingest::WalLagCooldown;
     118              : use crate::walredo;
     119              : use crate::InitializationOrder;
     120              : use std::collections::hash_map::Entry;
     121              : use std::collections::HashMap;
     122              : use std::collections::HashSet;
     123              : use std::fmt::Debug;
     124              : use std::fmt::Display;
     125              : use std::fs;
     126              : use std::fs::File;
     127              : use std::sync::atomic::{AtomicU64, Ordering};
     128              : use std::sync::Arc;
     129              : use std::sync::Mutex;
     130              : use std::time::{Duration, Instant};
     131              : 
     132              : use crate::span;
     133              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     134              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     135              : use crate::virtual_file::VirtualFile;
     136              : use crate::walredo::PostgresRedoManager;
     137              : use crate::TEMP_FILE_SUFFIX;
     138              : use once_cell::sync::Lazy;
     139              : pub use pageserver_api::models::TenantState;
     140              : use tokio::sync::Semaphore;
     141              : 
     142            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     143              : use utils::{
     144              :     crashsafe,
     145              :     generation::Generation,
     146              :     id::TimelineId,
     147              :     lsn::{Lsn, RecordLsn},
     148              : };
     149              : 
     150              : pub mod blob_io;
     151              : pub mod block_io;
     152              : pub mod vectored_blob_io;
     153              : 
     154              : pub mod disk_btree;
     155              : pub(crate) mod ephemeral_file;
     156              : pub mod layer_map;
     157              : 
     158              : pub mod metadata;
     159              : pub mod remote_timeline_client;
     160              : pub mod storage_layer;
     161              : 
     162              : pub mod checks;
     163              : pub mod config;
     164              : pub mod mgr;
     165              : pub mod secondary;
     166              : pub mod tasks;
     167              : pub mod upload_queue;
     168              : 
     169              : pub(crate) mod timeline;
     170              : 
     171              : pub mod size;
     172              : 
     173              : mod gc_block;
     174              : mod gc_result;
     175              : pub(crate) mod throttle;
     176              : 
     177              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     178              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     179              : 
     180              : // re-export for use in walreceiver
     181              : pub use crate::tenant::timeline::WalReceiverInfo;
     182              : 
     183              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     184              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     185              : 
     186              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     187              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     188              : 
     189              : /// References to shared objects that are passed into each tenant, such
     190              : /// as the shared remote storage client and process initialization state.
     191              : #[derive(Clone)]
     192              : pub struct TenantSharedResources {
     193              :     pub broker_client: storage_broker::BrokerClientChannel,
     194              :     pub remote_storage: GenericRemoteStorage,
     195              :     pub deletion_queue_client: DeletionQueueClient,
     196              :     pub l0_flush_global_state: L0FlushGlobalState,
     197              : }
     198              : 
     199              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     200              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     201              : /// in this struct.
     202              : #[derive(Clone)]
     203              : pub(super) struct AttachedTenantConf {
     204              :     tenant_conf: TenantConfOpt,
     205              :     location: AttachedLocationConfig,
     206              :     /// The deadline before which we are blocked from GC so that
     207              :     /// leases have a chance to be renewed.
     208              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     209              : }
     210              : 
     211              : impl AttachedTenantConf {
     212          440 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     213              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     214              :         //
     215              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     216              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     217              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     218          440 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     219          440 :             Some(
     220          440 :                 tokio::time::Instant::now()
     221          440 :                     + tenant_conf
     222          440 :                         .lsn_lease_length
     223          440 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     224          440 :             )
     225              :         } else {
     226              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     227              :             // because we don't do GC in these modes.
     228            0 :             None
     229              :         };
     230              : 
     231          440 :         Self {
     232          440 :             tenant_conf,
     233          440 :             location,
     234          440 :             lsn_lease_deadline,
     235          440 :         }
     236          440 :     }
     237              : 
     238          440 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     239          440 :         match &location_conf.mode {
     240          440 :             LocationMode::Attached(attach_conf) => {
     241          440 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     242              :             }
     243              :             LocationMode::Secondary(_) => {
     244            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     245              :             }
     246              :         }
     247          440 :     }
     248              : 
     249         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     250         1524 :         self.lsn_lease_deadline
     251         1524 :             .map(|d| tokio::time::Instant::now() < d)
     252         1524 :             .unwrap_or(false)
     253         1524 :     }
     254              : }
     255              : struct TimelinePreload {
     256              :     timeline_id: TimelineId,
     257              :     client: RemoteTimelineClient,
     258              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     259              : }
     260              : 
     261              : pub(crate) struct TenantPreload {
     262              :     tenant_manifest: TenantManifest,
     263              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     264              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     265              : }
     266              : 
     267              : /// When we spawn a tenant, there is a special mode for tenant creation that
     268              : /// avoids trying to read anything from remote storage.
     269              : pub(crate) enum SpawnMode {
     270              :     /// Activate as soon as possible
     271              :     Eager,
     272              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     273              :     Lazy,
     274              : }
     275              : 
     276              : ///
     277              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     278              : ///
     279              : pub struct Tenant {
     280              :     // Global pageserver config parameters
     281              :     pub conf: &'static PageServerConf,
     282              : 
     283              :     /// The value creation timestamp, used to measure activation delay, see:
     284              :     /// <https://github.com/neondatabase/neon/issues/4025>
     285              :     constructed_at: Instant,
     286              : 
     287              :     state: watch::Sender<TenantState>,
     288              : 
     289              :     // Overridden tenant-specific config parameters.
     290              :     // We keep TenantConfOpt sturct here to preserve the information
     291              :     // about parameters that are not set.
     292              :     // This is necessary to allow global config updates.
     293              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     294              : 
     295              :     tenant_shard_id: TenantShardId,
     296              : 
     297              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     298              :     shard_identity: ShardIdentity,
     299              : 
     300              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     301              :     /// Does not change over the lifetime of the [`Tenant`] object.
     302              :     ///
     303              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     304              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     305              :     generation: Generation,
     306              : 
     307              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     308              : 
     309              :     /// During timeline creation, we first insert the TimelineId to the
     310              :     /// creating map, then `timelines`, then remove it from the creating map.
     311              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     312              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     313              : 
     314              :     /// Possibly offloaded and archived timelines
     315              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     316              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     317              : 
     318              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     319              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     320              :     /// each other (this could be optimized to coalesce writes if necessary).
     321              :     ///
     322              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     323              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     324              : 
     325              :     // This mutex prevents creation of new timelines during GC.
     326              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     327              :     // `timelines` mutex during all GC iteration
     328              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     329              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     330              :     // timeout...
     331              :     gc_cs: tokio::sync::Mutex<()>,
     332              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     333              : 
     334              :     // provides access to timeline data sitting in the remote storage
     335              :     pub(crate) remote_storage: GenericRemoteStorage,
     336              : 
     337              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     338              :     deletion_queue_client: DeletionQueueClient,
     339              : 
     340              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     341              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     342              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     343              : 
     344              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     345              : 
     346              :     /// Track repeated failures to compact, so that we can back off.
     347              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     348              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     349              : 
     350              :     /// Scheduled gc-compaction tasks.
     351              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     352              : 
     353              :     /// If the tenant is in Activating state, notify this to encourage it
     354              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     355              :     /// background warmup.
     356              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     357              : 
     358              :     /// Time it took for the tenant to activate. Zero if not active yet.
     359              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     360              : 
     361              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     362              :     // Timelines' cancellation token.
     363              :     pub(crate) cancel: CancellationToken,
     364              : 
     365              :     // Users of the Tenant such as the page service must take this Gate to avoid
     366              :     // trying to use a Tenant which is shutting down.
     367              :     pub(crate) gate: Gate,
     368              : 
     369              :     /// Throttle applied at the top of [`Timeline::get`].
     370              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     371              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     372              : 
     373              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     374              : 
     375              :     /// An ongoing timeline detach concurrency limiter.
     376              :     ///
     377              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     378              :     /// to have two running at the same time. A different one can be started if an earlier one
     379              :     /// has failed for whatever reason.
     380              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     381              : 
     382              :     /// `index_part.json` based gc blocking reason tracking.
     383              :     ///
     384              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     385              :     /// proceeding.
     386              :     pub(crate) gc_block: gc_block::GcBlock,
     387              : 
     388              :     l0_flush_global_state: L0FlushGlobalState,
     389              : }
     390              : impl std::fmt::Debug for Tenant {
     391            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     392            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     393            0 :     }
     394              : }
     395              : 
     396              : pub(crate) enum WalRedoManager {
     397              :     Prod(WalredoManagerId, PostgresRedoManager),
     398              :     #[cfg(test)]
     399              :     Test(harness::TestRedoManager),
     400              : }
     401              : 
     402              : #[derive(thiserror::Error, Debug)]
     403              : #[error("pageserver is shutting down")]
     404              : pub(crate) struct GlobalShutDown;
     405              : 
     406              : impl WalRedoManager {
     407            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     408            0 :         let id = WalredoManagerId::next();
     409            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     410            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     411            0 :         match &mut *guard {
     412            0 :             Some(map) => {
     413            0 :                 map.insert(id, Arc::downgrade(&arc));
     414            0 :                 Ok(arc)
     415              :             }
     416            0 :             None => Err(GlobalShutDown),
     417              :         }
     418            0 :     }
     419              : }
     420              : 
     421              : impl Drop for WalRedoManager {
     422           20 :     fn drop(&mut self) {
     423           20 :         match self {
     424            0 :             Self::Prod(id, _) => {
     425            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     426            0 :                 if let Some(map) = &mut *guard {
     427            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     428            0 :                 }
     429              :             }
     430              :             #[cfg(test)]
     431           20 :             Self::Test(_) => {
     432           20 :                 // Not applicable to test redo manager
     433           20 :             }
     434              :         }
     435           20 :     }
     436              : }
     437              : 
     438              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     439              : /// the walredo processes outside of the regular order.
     440              : ///
     441              : /// This is necessary to work around a systemd bug where it freezes if there are
     442              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     443              : #[allow(clippy::type_complexity)]
     444              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     445              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     446            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     447              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     448              : pub(crate) struct WalredoManagerId(u64);
     449              : impl WalredoManagerId {
     450            0 :     pub fn next() -> Self {
     451              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     452            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     453            0 :         if id == 0 {
     454            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     455            0 :         }
     456            0 :         Self(id)
     457            0 :     }
     458              : }
     459              : 
     460              : #[cfg(test)]
     461              : impl From<harness::TestRedoManager> for WalRedoManager {
     462          440 :     fn from(mgr: harness::TestRedoManager) -> Self {
     463          440 :         Self::Test(mgr)
     464          440 :     }
     465              : }
     466              : 
     467              : impl WalRedoManager {
     468           12 :     pub(crate) async fn shutdown(&self) -> bool {
     469           12 :         match self {
     470            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     471              :             #[cfg(test)]
     472              :             Self::Test(_) => {
     473              :                 // Not applicable to test redo manager
     474           12 :                 true
     475              :             }
     476              :         }
     477           12 :     }
     478              : 
     479            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     480            0 :         match self {
     481            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     482            0 :             #[cfg(test)]
     483            0 :             Self::Test(_) => {
     484            0 :                 // Not applicable to test redo manager
     485            0 :             }
     486            0 :         }
     487            0 :     }
     488              : 
     489              :     /// # Cancel-Safety
     490              :     ///
     491              :     /// This method is cancellation-safe.
     492         1636 :     pub async fn request_redo(
     493         1636 :         &self,
     494         1636 :         key: pageserver_api::key::Key,
     495         1636 :         lsn: Lsn,
     496         1636 :         base_img: Option<(Lsn, bytes::Bytes)>,
     497         1636 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     498         1636 :         pg_version: u32,
     499         1636 :     ) -> Result<bytes::Bytes, walredo::Error> {
     500         1636 :         match self {
     501            0 :             Self::Prod(_, mgr) => {
     502            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     503            0 :                     .await
     504              :             }
     505              :             #[cfg(test)]
     506         1636 :             Self::Test(mgr) => {
     507         1636 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     508         1636 :                     .await
     509              :             }
     510              :         }
     511         1636 :     }
     512              : 
     513            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     514            0 :         match self {
     515            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     516            0 :             #[cfg(test)]
     517            0 :             WalRedoManager::Test(_) => None,
     518            0 :         }
     519            0 :     }
     520              : }
     521              : 
     522              : /// A very lightweight memory representation of an offloaded timeline.
     523              : ///
     524              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     525              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     526              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     527              : /// more offloaded timelines than we can manage ones that aren't.
     528              : pub struct OffloadedTimeline {
     529              :     pub tenant_shard_id: TenantShardId,
     530              :     pub timeline_id: TimelineId,
     531              :     pub ancestor_timeline_id: Option<TimelineId>,
     532              :     /// Whether to retain the branch lsn at the ancestor or not
     533              :     pub ancestor_retain_lsn: Option<Lsn>,
     534              : 
     535              :     /// When the timeline was archived.
     536              :     ///
     537              :     /// Present for future flattening deliberations.
     538              :     pub archived_at: NaiveDateTime,
     539              : 
     540              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     541              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     542              :     pub delete_progress: TimelineDeleteProgress,
     543              : 
     544              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     545              :     pub deleted_from_ancestor: AtomicBool,
     546              : }
     547              : 
     548              : impl OffloadedTimeline {
     549              :     /// Obtains an offloaded timeline from a given timeline object.
     550              :     ///
     551              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     552              :     /// the timeline is not in a stopped state.
     553              :     /// Panics if the timeline is not archived.
     554            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     555            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     556            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     557            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     558            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     559            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     560            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     561            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     562              :             } else {
     563            0 :                 (None, None)
     564              :             };
     565            4 :         let archived_at = timeline
     566            4 :             .remote_client
     567            4 :             .archived_at_stopped_queue()?
     568            4 :             .expect("must be called on an archived timeline");
     569            4 :         Ok(Self {
     570            4 :             tenant_shard_id: timeline.tenant_shard_id,
     571            4 :             timeline_id: timeline.timeline_id,
     572            4 :             ancestor_timeline_id,
     573            4 :             ancestor_retain_lsn,
     574            4 :             archived_at,
     575            4 : 
     576            4 :             delete_progress: timeline.delete_progress.clone(),
     577            4 :             deleted_from_ancestor: AtomicBool::new(false),
     578            4 :         })
     579            4 :     }
     580            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     581            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     582            0 :         // by the `initialize_gc_info` function.
     583            0 :         let OffloadedTimelineManifest {
     584            0 :             timeline_id,
     585            0 :             ancestor_timeline_id,
     586            0 :             ancestor_retain_lsn,
     587            0 :             archived_at,
     588            0 :         } = *manifest;
     589            0 :         Self {
     590            0 :             tenant_shard_id,
     591            0 :             timeline_id,
     592            0 :             ancestor_timeline_id,
     593            0 :             ancestor_retain_lsn,
     594            0 :             archived_at,
     595            0 :             delete_progress: TimelineDeleteProgress::default(),
     596            0 :             deleted_from_ancestor: AtomicBool::new(false),
     597            0 :         }
     598            0 :     }
     599            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     600            4 :         let Self {
     601            4 :             timeline_id,
     602            4 :             ancestor_timeline_id,
     603            4 :             ancestor_retain_lsn,
     604            4 :             archived_at,
     605            4 :             ..
     606            4 :         } = self;
     607            4 :         OffloadedTimelineManifest {
     608            4 :             timeline_id: *timeline_id,
     609            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     610            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     611            4 :             archived_at: *archived_at,
     612            4 :         }
     613            4 :     }
     614              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     615            0 :     fn delete_from_ancestor_with_timelines(
     616            0 :         &self,
     617            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     618            0 :     ) {
     619            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     620            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     621              :         {
     622            0 :             if let Some((_, ancestor_timeline)) = timelines
     623            0 :                 .iter()
     624            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     625              :             {
     626            0 :                 let removal_happened = ancestor_timeline
     627            0 :                     .gc_info
     628            0 :                     .write()
     629            0 :                     .unwrap()
     630            0 :                     .remove_child_offloaded(self.timeline_id);
     631            0 :                 if !removal_happened {
     632            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     633            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     634            0 :                 }
     635            0 :             }
     636            0 :         }
     637            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     638            0 :     }
     639              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     640              :     ///
     641              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     642            4 :     fn defuse_for_tenant_drop(&self) {
     643            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     644            4 :     }
     645              : }
     646              : 
     647              : impl fmt::Debug for OffloadedTimeline {
     648            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     649            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     650            0 :     }
     651              : }
     652              : 
     653              : impl Drop for OffloadedTimeline {
     654            4 :     fn drop(&mut self) {
     655            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     656            0 :             tracing::warn!(
     657            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     658              :                 self.timeline_id
     659              :             );
     660            4 :         }
     661            4 :     }
     662              : }
     663              : 
     664              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     665              : pub enum MaybeOffloaded {
     666              :     Yes,
     667              :     No,
     668              : }
     669              : 
     670              : #[derive(Clone, Debug)]
     671              : pub enum TimelineOrOffloaded {
     672              :     Timeline(Arc<Timeline>),
     673              :     Offloaded(Arc<OffloadedTimeline>),
     674              : }
     675              : 
     676              : impl TimelineOrOffloaded {
     677            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     678            0 :         match self {
     679            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     680            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     681              :             }
     682            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     683            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     684              :             }
     685              :         }
     686            0 :     }
     687            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     688            0 :         self.arc_ref().tenant_shard_id()
     689            0 :     }
     690            0 :     pub fn timeline_id(&self) -> TimelineId {
     691            0 :         self.arc_ref().timeline_id()
     692            0 :     }
     693            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     694            4 :         match self {
     695            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     696            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     697              :         }
     698            4 :     }
     699            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     700            0 :         match self {
     701            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     702            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     703              :         }
     704            0 :     }
     705              : }
     706              : 
     707              : pub enum TimelineOrOffloadedArcRef<'a> {
     708              :     Timeline(&'a Arc<Timeline>),
     709              :     Offloaded(&'a Arc<OffloadedTimeline>),
     710              : }
     711              : 
     712              : impl TimelineOrOffloadedArcRef<'_> {
     713            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     714            0 :         match self {
     715            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     716            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     717              :         }
     718            0 :     }
     719            0 :     pub fn timeline_id(&self) -> TimelineId {
     720            0 :         match self {
     721            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     722            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     723              :         }
     724            0 :     }
     725              : }
     726              : 
     727              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     728            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     729            0 :         Self::Timeline(timeline)
     730            0 :     }
     731              : }
     732              : 
     733              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     734            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     735            0 :         Self::Offloaded(timeline)
     736            0 :     }
     737              : }
     738              : 
     739              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     740              : pub enum GetTimelineError {
     741              :     #[error("Timeline is shutting down")]
     742              :     ShuttingDown,
     743              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     744              :     NotActive {
     745              :         tenant_id: TenantShardId,
     746              :         timeline_id: TimelineId,
     747              :         state: TimelineState,
     748              :     },
     749              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     750              :     NotFound {
     751              :         tenant_id: TenantShardId,
     752              :         timeline_id: TimelineId,
     753              :     },
     754              : }
     755              : 
     756              : #[derive(Debug, thiserror::Error)]
     757              : pub enum LoadLocalTimelineError {
     758              :     #[error("FailedToLoad")]
     759              :     Load(#[source] anyhow::Error),
     760              :     #[error("FailedToResumeDeletion")]
     761              :     ResumeDeletion(#[source] anyhow::Error),
     762              : }
     763              : 
     764              : #[derive(thiserror::Error)]
     765              : pub enum DeleteTimelineError {
     766              :     #[error("NotFound")]
     767              :     NotFound,
     768              : 
     769              :     #[error("HasChildren")]
     770              :     HasChildren(Vec<TimelineId>),
     771              : 
     772              :     #[error("Timeline deletion is already in progress")]
     773              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     774              : 
     775              :     #[error("Cancelled")]
     776              :     Cancelled,
     777              : 
     778              :     #[error(transparent)]
     779              :     Other(#[from] anyhow::Error),
     780              : }
     781              : 
     782              : impl Debug for DeleteTimelineError {
     783            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     784            0 :         match self {
     785            0 :             Self::NotFound => write!(f, "NotFound"),
     786            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     787            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     788            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     789            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     790              :         }
     791            0 :     }
     792              : }
     793              : 
     794              : #[derive(thiserror::Error)]
     795              : pub enum TimelineArchivalError {
     796              :     #[error("NotFound")]
     797              :     NotFound,
     798              : 
     799              :     #[error("Timeout")]
     800              :     Timeout,
     801              : 
     802              :     #[error("Cancelled")]
     803              :     Cancelled,
     804              : 
     805              :     #[error("ancestor is archived: {}", .0)]
     806              :     HasArchivedParent(TimelineId),
     807              : 
     808              :     #[error("HasUnarchivedChildren")]
     809              :     HasUnarchivedChildren(Vec<TimelineId>),
     810              : 
     811              :     #[error("Timeline archival is already in progress")]
     812              :     AlreadyInProgress,
     813              : 
     814              :     #[error(transparent)]
     815              :     Other(anyhow::Error),
     816              : }
     817              : 
     818              : #[derive(thiserror::Error, Debug)]
     819              : pub(crate) enum TenantManifestError {
     820              :     #[error("Remote storage error: {0}")]
     821              :     RemoteStorage(anyhow::Error),
     822              : 
     823              :     #[error("Cancelled")]
     824              :     Cancelled,
     825              : }
     826              : 
     827              : impl From<TenantManifestError> for TimelineArchivalError {
     828            0 :     fn from(e: TenantManifestError) -> Self {
     829            0 :         match e {
     830            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     831            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     832              :         }
     833            0 :     }
     834              : }
     835              : 
     836              : impl Debug for TimelineArchivalError {
     837            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     838            0 :         match self {
     839            0 :             Self::NotFound => write!(f, "NotFound"),
     840            0 :             Self::Timeout => write!(f, "Timeout"),
     841            0 :             Self::Cancelled => write!(f, "Cancelled"),
     842            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     843            0 :             Self::HasUnarchivedChildren(c) => {
     844            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     845              :             }
     846            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     847            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     848              :         }
     849            0 :     }
     850              : }
     851              : 
     852              : pub enum SetStoppingError {
     853              :     AlreadyStopping(completion::Barrier),
     854              :     Broken,
     855              : }
     856              : 
     857              : impl Debug for SetStoppingError {
     858            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     859            0 :         match self {
     860            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     861            0 :             Self::Broken => write!(f, "Broken"),
     862              :         }
     863            0 :     }
     864              : }
     865              : 
     866              : /// Arguments to [`Tenant::create_timeline`].
     867              : ///
     868              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     869              : /// is `None`, the result of the timeline create call is not deterministic.
     870              : ///
     871              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     872              : #[derive(Debug)]
     873              : pub(crate) enum CreateTimelineParams {
     874              :     Bootstrap(CreateTimelineParamsBootstrap),
     875              :     Branch(CreateTimelineParamsBranch),
     876              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     877              : }
     878              : 
     879              : #[derive(Debug)]
     880              : pub(crate) struct CreateTimelineParamsBootstrap {
     881              :     pub(crate) new_timeline_id: TimelineId,
     882              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     883              :     pub(crate) pg_version: u32,
     884              : }
     885              : 
     886              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     887              : #[derive(Debug)]
     888              : pub(crate) struct CreateTimelineParamsBranch {
     889              :     pub(crate) new_timeline_id: TimelineId,
     890              :     pub(crate) ancestor_timeline_id: TimelineId,
     891              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     892              : }
     893              : 
     894              : #[derive(Debug)]
     895              : pub(crate) struct CreateTimelineParamsImportPgdata {
     896              :     pub(crate) new_timeline_id: TimelineId,
     897              :     pub(crate) location: import_pgdata::index_part_format::Location,
     898              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     899              : }
     900              : 
     901              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     902              : ///
     903              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     904              : ///
     905              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     906              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     907              : ///
     908              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     909              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     910              : ///
     911              : /// Notes:
     912              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     913              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     914              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     915              : ///
     916              : #[derive(Debug, Clone, PartialEq, Eq)]
     917              : pub(crate) enum CreateTimelineIdempotency {
     918              :     /// NB: special treatment, see comment in [`Self`].
     919              :     FailWithConflict,
     920              :     Bootstrap {
     921              :         pg_version: u32,
     922              :     },
     923              :     /// NB: branches always have the same `pg_version` as their ancestor.
     924              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     925              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     926              :     /// determining the child branch pg_version.
     927              :     Branch {
     928              :         ancestor_timeline_id: TimelineId,
     929              :         ancestor_start_lsn: Lsn,
     930              :     },
     931              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     932              : }
     933              : 
     934              : #[derive(Debug, Clone, PartialEq, Eq)]
     935              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     936              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     937              : }
     938              : 
     939              : /// What is returned by [`Tenant::start_creating_timeline`].
     940              : #[must_use]
     941              : enum StartCreatingTimelineResult {
     942              :     CreateGuard(TimelineCreateGuard),
     943              :     Idempotent(Arc<Timeline>),
     944              : }
     945              : 
     946              : enum TimelineInitAndSyncResult {
     947              :     ReadyToActivate(Arc<Timeline>),
     948              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     949              : }
     950              : 
     951              : impl TimelineInitAndSyncResult {
     952            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     953            0 :         match self {
     954            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     955            0 :             _ => None,
     956              :         }
     957            0 :     }
     958              : }
     959              : 
     960              : #[must_use]
     961              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     962              :     timeline: Arc<Timeline>,
     963              :     import_pgdata: import_pgdata::index_part_format::Root,
     964              :     guard: TimelineCreateGuard,
     965              : }
     966              : 
     967              : /// What is returned by [`Tenant::create_timeline`].
     968              : enum CreateTimelineResult {
     969              :     Created(Arc<Timeline>),
     970              :     Idempotent(Arc<Timeline>),
     971              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     972              :     /// we return this result, nor will this concrete object ever be added there.
     973              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     974              :     ImportSpawned(Arc<Timeline>),
     975              : }
     976              : 
     977              : impl CreateTimelineResult {
     978            0 :     fn discriminant(&self) -> &'static str {
     979            0 :         match self {
     980            0 :             Self::Created(_) => "Created",
     981            0 :             Self::Idempotent(_) => "Idempotent",
     982            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     983              :         }
     984            0 :     }
     985            0 :     fn timeline(&self) -> &Arc<Timeline> {
     986            0 :         match self {
     987            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     988            0 :         }
     989            0 :     }
     990              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     991              :     #[cfg(test)]
     992          460 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     993          460 :         match self {
     994          460 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     995          460 :         }
     996          460 :     }
     997              : }
     998              : 
     999              : #[derive(thiserror::Error, Debug)]
    1000              : pub enum CreateTimelineError {
    1001              :     #[error("creation of timeline with the given ID is in progress")]
    1002              :     AlreadyCreating,
    1003              :     #[error("timeline already exists with different parameters")]
    1004              :     Conflict,
    1005              :     #[error(transparent)]
    1006              :     AncestorLsn(anyhow::Error),
    1007              :     #[error("ancestor timeline is not active")]
    1008              :     AncestorNotActive,
    1009              :     #[error("ancestor timeline is archived")]
    1010              :     AncestorArchived,
    1011              :     #[error("tenant shutting down")]
    1012              :     ShuttingDown,
    1013              :     #[error(transparent)]
    1014              :     Other(#[from] anyhow::Error),
    1015              : }
    1016              : 
    1017              : #[derive(thiserror::Error, Debug)]
    1018              : pub enum InitdbError {
    1019              :     #[error("Operation was cancelled")]
    1020              :     Cancelled,
    1021              :     #[error(transparent)]
    1022              :     Other(anyhow::Error),
    1023              :     #[error(transparent)]
    1024              :     Inner(postgres_initdb::Error),
    1025              : }
    1026              : 
    1027              : enum CreateTimelineCause {
    1028              :     Load,
    1029              :     Delete,
    1030              : }
    1031              : 
    1032              : enum LoadTimelineCause {
    1033              :     Attach,
    1034              :     Unoffload,
    1035              :     ImportPgdata {
    1036              :         create_guard: TimelineCreateGuard,
    1037              :         activate: ActivateTimelineArgs,
    1038              :     },
    1039              : }
    1040              : 
    1041              : #[derive(thiserror::Error, Debug)]
    1042              : pub(crate) enum GcError {
    1043              :     // The tenant is shutting down
    1044              :     #[error("tenant shutting down")]
    1045              :     TenantCancelled,
    1046              : 
    1047              :     // The tenant is shutting down
    1048              :     #[error("timeline shutting down")]
    1049              :     TimelineCancelled,
    1050              : 
    1051              :     // The tenant is in a state inelegible to run GC
    1052              :     #[error("not active")]
    1053              :     NotActive,
    1054              : 
    1055              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1056              :     #[error("not active")]
    1057              :     BadLsn { why: String },
    1058              : 
    1059              :     // A remote storage error while scheduling updates after compaction
    1060              :     #[error(transparent)]
    1061              :     Remote(anyhow::Error),
    1062              : 
    1063              :     // An error reading while calculating GC cutoffs
    1064              :     #[error(transparent)]
    1065              :     GcCutoffs(PageReconstructError),
    1066              : 
    1067              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1068              :     #[error("timeline not found")]
    1069              :     TimelineNotFound,
    1070              : }
    1071              : 
    1072              : impl From<PageReconstructError> for GcError {
    1073            0 :     fn from(value: PageReconstructError) -> Self {
    1074            0 :         match value {
    1075            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1076            0 :             other => Self::GcCutoffs(other),
    1077              :         }
    1078            0 :     }
    1079              : }
    1080              : 
    1081              : impl From<NotInitialized> for GcError {
    1082            0 :     fn from(value: NotInitialized) -> Self {
    1083            0 :         match value {
    1084            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1085            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1086              :         }
    1087            0 :     }
    1088              : }
    1089              : 
    1090              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1091            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1092            0 :         GcError::TimelineCancelled
    1093            0 :     }
    1094              : }
    1095              : 
    1096              : #[derive(thiserror::Error, Debug)]
    1097              : pub(crate) enum LoadConfigError {
    1098              :     #[error("TOML deserialization error: '{0}'")]
    1099              :     DeserializeToml(#[from] toml_edit::de::Error),
    1100              : 
    1101              :     #[error("Config not found at {0}")]
    1102              :     NotFound(Utf8PathBuf),
    1103              : }
    1104              : 
    1105              : impl Tenant {
    1106              :     /// Yet another helper for timeline initialization.
    1107              :     ///
    1108              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1109              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1110              :     /// - Downloads remote index file and adds remote files to the layer map
    1111              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1112              :     ///
    1113              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1114              :     /// it is marked as Active.
    1115              :     #[allow(clippy::too_many_arguments)]
    1116           12 :     async fn timeline_init_and_sync(
    1117           12 :         self: &Arc<Self>,
    1118           12 :         timeline_id: TimelineId,
    1119           12 :         resources: TimelineResources,
    1120           12 :         mut index_part: IndexPart,
    1121           12 :         metadata: TimelineMetadata,
    1122           12 :         ancestor: Option<Arc<Timeline>>,
    1123           12 :         cause: LoadTimelineCause,
    1124           12 :         ctx: &RequestContext,
    1125           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1126           12 :         let tenant_id = self.tenant_shard_id;
    1127           12 : 
    1128           12 :         let import_pgdata = index_part.import_pgdata.take();
    1129           12 :         let idempotency = match &import_pgdata {
    1130            0 :             Some(import_pgdata) => {
    1131            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1132            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1133            0 :                 })
    1134              :             }
    1135              :             None => {
    1136           12 :                 if metadata.ancestor_timeline().is_none() {
    1137            8 :                     CreateTimelineIdempotency::Bootstrap {
    1138            8 :                         pg_version: metadata.pg_version(),
    1139            8 :                     }
    1140              :                 } else {
    1141            4 :                     CreateTimelineIdempotency::Branch {
    1142            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1143            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1144            4 :                     }
    1145              :                 }
    1146              :             }
    1147              :         };
    1148              : 
    1149           12 :         let timeline = self.create_timeline_struct(
    1150           12 :             timeline_id,
    1151           12 :             &metadata,
    1152           12 :             ancestor.clone(),
    1153           12 :             resources,
    1154           12 :             CreateTimelineCause::Load,
    1155           12 :             idempotency.clone(),
    1156           12 :         )?;
    1157           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1158           12 :         anyhow::ensure!(
    1159           12 :             disk_consistent_lsn.is_valid(),
    1160            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1161              :         );
    1162           12 :         assert_eq!(
    1163           12 :             disk_consistent_lsn,
    1164           12 :             metadata.disk_consistent_lsn(),
    1165            0 :             "these are used interchangeably"
    1166              :         );
    1167              : 
    1168           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1169              : 
    1170           12 :         timeline
    1171           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1172           12 :             .await
    1173           12 :             .with_context(|| {
    1174            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1175           12 :             })?;
    1176              : 
    1177            0 :         match import_pgdata {
    1178            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1179            0 :                 match cause {
    1180            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1181              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1182            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1183              :                     }
    1184              :                 }
    1185            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1186            0 :                 if !guard.insert(timeline_id) {
    1187              :                     // We should never try and load the same timeline twice during startup
    1188            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1189            0 :                 }
    1190            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1191            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1192            0 :                     owning_tenant: self.clone(),
    1193            0 :                     timeline_id,
    1194            0 :                     idempotency,
    1195            0 :                     // The users of this specific return value don't need the timline_path in there.
    1196            0 :                     timeline_path: timeline
    1197            0 :                         .conf
    1198            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1199            0 :                 };
    1200            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1201            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1202            0 :                         timeline,
    1203            0 :                         import_pgdata,
    1204            0 :                         guard: timeline_create_guard,
    1205            0 :                     },
    1206            0 :                 ))
    1207              :             }
    1208              :             Some(_) | None => {
    1209              :                 {
    1210           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1211           12 :                     match timelines_accessor.entry(timeline_id) {
    1212              :                         // We should never try and load the same timeline twice during startup
    1213              :                         Entry::Occupied(_) => {
    1214            0 :                             unreachable!(
    1215            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1216            0 :                         );
    1217              :                         }
    1218           12 :                         Entry::Vacant(v) => {
    1219           12 :                             v.insert(Arc::clone(&timeline));
    1220           12 :                             timeline.maybe_spawn_flush_loop();
    1221           12 :                         }
    1222              :                     }
    1223              :                 }
    1224              : 
    1225              :                 // Sanity check: a timeline should have some content.
    1226           12 :                 anyhow::ensure!(
    1227           12 :                     ancestor.is_some()
    1228            8 :                         || timeline
    1229            8 :                             .layers
    1230            8 :                             .read()
    1231            8 :                             .await
    1232            8 :                             .layer_map()
    1233            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1234            8 :                             .iter_historic_layers()
    1235            8 :                             .next()
    1236            8 :                             .is_some(),
    1237            0 :                     "Timeline has no ancestor and no layer files"
    1238              :                 );
    1239              : 
    1240           12 :                 match cause {
    1241           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1242              :                     LoadTimelineCause::ImportPgdata {
    1243            0 :                         create_guard,
    1244            0 :                         activate,
    1245            0 :                     } => {
    1246            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1247            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1248            0 :                         match activate {
    1249            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1250            0 :                                 info!("activating timeline after reload from pgdata import task");
    1251            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1252              :                             }
    1253            0 :                             ActivateTimelineArgs::No => (),
    1254              :                         }
    1255            0 :                         drop(create_guard);
    1256              :                     }
    1257              :                 }
    1258              : 
    1259           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1260              :             }
    1261              :         }
    1262           12 :     }
    1263              : 
    1264              :     /// Attach a tenant that's available in cloud storage.
    1265              :     ///
    1266              :     /// This returns quickly, after just creating the in-memory object
    1267              :     /// Tenant struct and launching a background task to download
    1268              :     /// the remote index files.  On return, the tenant is most likely still in
    1269              :     /// Attaching state, and it will become Active once the background task
    1270              :     /// finishes. You can use wait_until_active() to wait for the task to
    1271              :     /// complete.
    1272              :     ///
    1273              :     #[allow(clippy::too_many_arguments)]
    1274            0 :     pub(crate) fn spawn(
    1275            0 :         conf: &'static PageServerConf,
    1276            0 :         tenant_shard_id: TenantShardId,
    1277            0 :         resources: TenantSharedResources,
    1278            0 :         attached_conf: AttachedTenantConf,
    1279            0 :         shard_identity: ShardIdentity,
    1280            0 :         init_order: Option<InitializationOrder>,
    1281            0 :         mode: SpawnMode,
    1282            0 :         ctx: &RequestContext,
    1283            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1284            0 :         let wal_redo_manager =
    1285            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1286              : 
    1287              :         let TenantSharedResources {
    1288            0 :             broker_client,
    1289            0 :             remote_storage,
    1290            0 :             deletion_queue_client,
    1291            0 :             l0_flush_global_state,
    1292            0 :         } = resources;
    1293            0 : 
    1294            0 :         let attach_mode = attached_conf.location.attach_mode;
    1295            0 :         let generation = attached_conf.location.generation;
    1296            0 : 
    1297            0 :         let tenant = Arc::new(Tenant::new(
    1298            0 :             TenantState::Attaching,
    1299            0 :             conf,
    1300            0 :             attached_conf,
    1301            0 :             shard_identity,
    1302            0 :             Some(wal_redo_manager),
    1303            0 :             tenant_shard_id,
    1304            0 :             remote_storage.clone(),
    1305            0 :             deletion_queue_client,
    1306            0 :             l0_flush_global_state,
    1307            0 :         ));
    1308            0 : 
    1309            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1310            0 :         // we shut down while attaching.
    1311            0 :         let attach_gate_guard = tenant
    1312            0 :             .gate
    1313            0 :             .enter()
    1314            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1315            0 : 
    1316            0 :         // Do all the hard work in the background
    1317            0 :         let tenant_clone = Arc::clone(&tenant);
    1318            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1319            0 :         task_mgr::spawn(
    1320            0 :             &tokio::runtime::Handle::current(),
    1321            0 :             TaskKind::Attach,
    1322            0 :             tenant_shard_id,
    1323            0 :             None,
    1324            0 :             "attach tenant",
    1325            0 :             async move {
    1326            0 : 
    1327            0 :                 info!(
    1328              :                     ?attach_mode,
    1329            0 :                     "Attaching tenant"
    1330              :                 );
    1331              : 
    1332            0 :                 let _gate_guard = attach_gate_guard;
    1333            0 : 
    1334            0 :                 // Is this tenant being spawned as part of process startup?
    1335            0 :                 let starting_up = init_order.is_some();
    1336            0 :                 scopeguard::defer! {
    1337            0 :                     if starting_up {
    1338            0 :                         TENANT.startup_complete.inc();
    1339            0 :                     }
    1340            0 :                 }
    1341              : 
    1342              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1343              :                 enum BrokenVerbosity {
    1344              :                     Error,
    1345              :                     Info
    1346              :                 }
    1347            0 :                 let make_broken =
    1348            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1349            0 :                         match verbosity {
    1350              :                             BrokenVerbosity::Info => {
    1351            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1352              :                             },
    1353              :                             BrokenVerbosity::Error => {
    1354            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1355              :                             }
    1356              :                         }
    1357            0 :                         t.state.send_modify(|state| {
    1358            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1359            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1360            0 :                             assert!(
    1361            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1362            0 :                                 "the attach task owns the tenant state until activation is complete"
    1363              :                             );
    1364              : 
    1365            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1366            0 :                         });
    1367            0 :                     };
    1368              : 
    1369              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1370            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1371            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1372            0 :                     return Ok(());
    1373            0 :                 }
    1374            0 : 
    1375            0 :                 let mut init_order = init_order;
    1376            0 :                 // take the completion because initial tenant loading will complete when all of
    1377            0 :                 // these tasks complete.
    1378            0 :                 let _completion = init_order
    1379            0 :                     .as_mut()
    1380            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1381            0 :                 let remote_load_completion = init_order
    1382            0 :                     .as_mut()
    1383            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1384              : 
    1385              :                 enum AttachType<'a> {
    1386              :                     /// We are attaching this tenant lazily in the background.
    1387              :                     Warmup {
    1388              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1389              :                         during_startup: bool
    1390              :                     },
    1391              :                     /// We are attaching this tenant as soon as we can, because for example an
    1392              :                     /// endpoint tried to access it.
    1393              :                     OnDemand,
    1394              :                     /// During normal operations after startup, we are attaching a tenant, and
    1395              :                     /// eager attach was requested.
    1396              :                     Normal,
    1397              :                 }
    1398              : 
    1399            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1400              :                     // Before doing any I/O, wait for at least one of:
    1401              :                     // - A client attempting to access to this tenant (on-demand loading)
    1402              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1403              : 
    1404            0 :                     tokio::select!(
    1405            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1406            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1407            0 :                             tracing::info!("Activating tenant (on-demand)");
    1408            0 :                             AttachType::OnDemand
    1409              :                         },
    1410            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1411            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1412            0 :                             tracing::info!("Activating tenant (warmup)");
    1413            0 :                             AttachType::Warmup {
    1414            0 :                                 _permit,
    1415            0 :                                 during_startup: init_order.is_some()
    1416            0 :                             }
    1417              :                         }
    1418            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1419              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1420              :                             // stayed in Activating for such a long time that shutdown found it in
    1421              :                             // that state.
    1422            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1423              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1424              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1425              :                             // just shutting down), but ensures progress.
    1426            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1427            0 :                             return Ok(());
    1428              :                         },
    1429              :                     )
    1430              :                 } else {
    1431              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1432              :                     // concurrent_tenant_warmup queue
    1433            0 :                     AttachType::Normal
    1434              :                 };
    1435              : 
    1436            0 :                 let preload = match &mode {
    1437              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1438            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1439            0 :                         let res = tenant_clone
    1440            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1441            0 :                             .await;
    1442            0 :                         match res {
    1443            0 :                             Ok(p) => Some(p),
    1444            0 :                             Err(e) => {
    1445            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1446            0 :                                 return Ok(());
    1447              :                             }
    1448              :                         }
    1449              :                     }
    1450              : 
    1451              :                 };
    1452              : 
    1453              :                 // Remote preload is complete.
    1454            0 :                 drop(remote_load_completion);
    1455            0 : 
    1456            0 : 
    1457            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1458            0 :                 let attach_start = std::time::Instant::now();
    1459            0 :                 let attached = {
    1460            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1461            0 :                     tenant_clone.attach(preload, &ctx).await
    1462              :                 };
    1463            0 :                 let attach_duration = attach_start.elapsed();
    1464            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1465            0 : 
    1466            0 :                 match attached {
    1467              :                     Ok(()) => {
    1468            0 :                         info!("attach finished, activating");
    1469            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1470              :                     }
    1471            0 :                     Err(e) => {
    1472            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1473            0 :                     }
    1474              :                 }
    1475              : 
    1476              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1477              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1478              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1479              :                 //
    1480              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1481              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1482              :                 // then warmup will wait for that before proceeding to the next tenant.
    1483            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1484            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1485            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1486            0 :                     while futs.next().await.is_some() {}
    1487            0 :                     tracing::info!("Warm-up complete");
    1488            0 :                 }
    1489              : 
    1490            0 :                 Ok(())
    1491            0 :             }
    1492            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1493              :         );
    1494            0 :         Ok(tenant)
    1495            0 :     }
    1496              : 
    1497              :     #[instrument(skip_all)]
    1498              :     pub(crate) async fn preload(
    1499              :         self: &Arc<Self>,
    1500              :         remote_storage: &GenericRemoteStorage,
    1501              :         cancel: CancellationToken,
    1502              :     ) -> anyhow::Result<TenantPreload> {
    1503              :         span::debug_assert_current_span_has_tenant_id();
    1504              :         // Get list of remote timelines
    1505              :         // download index files for every tenant timeline
    1506              :         info!("listing remote timelines");
    1507              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1508              :             remote_storage,
    1509              :             self.tenant_shard_id,
    1510              :             cancel.clone(),
    1511              :         )
    1512              :         .await?;
    1513              :         let (offloaded_add, tenant_manifest) =
    1514              :             match remote_timeline_client::download_tenant_manifest(
    1515              :                 remote_storage,
    1516              :                 &self.tenant_shard_id,
    1517              :                 self.generation,
    1518              :                 &cancel,
    1519              :             )
    1520              :             .await
    1521              :             {
    1522              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1523              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1524              :                     tenant_manifest,
    1525              :                 ),
    1526              :                 Err(DownloadError::NotFound) => {
    1527              :                     ("no manifest".to_string(), TenantManifest::empty())
    1528              :                 }
    1529              :                 Err(e) => Err(e)?,
    1530              :             };
    1531              : 
    1532              :         info!(
    1533              :             "found {} timelines, and {offloaded_add}",
    1534              :             remote_timeline_ids.len()
    1535              :         );
    1536              : 
    1537              :         for k in other_keys {
    1538              :             warn!("Unexpected non timeline key {k}");
    1539              :         }
    1540              : 
    1541              :         // Avoid downloading IndexPart of offloaded timelines.
    1542              :         let mut offloaded_with_prefix = HashSet::new();
    1543              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1544              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1545              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1546              :             } else {
    1547              :                 // We'll take care later of timelines in the manifest without a prefix
    1548              :             }
    1549              :         }
    1550              : 
    1551              :         let timelines = self
    1552              :             .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1553              :             .await?;
    1554              : 
    1555              :         Ok(TenantPreload {
    1556              :             tenant_manifest,
    1557              :             timelines: timelines
    1558              :                 .into_iter()
    1559           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1560            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1561              :                 .collect(),
    1562              :         })
    1563              :     }
    1564              : 
    1565              :     ///
    1566              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1567              :     ///
    1568              :     /// No background tasks are started as part of this routine.
    1569              :     ///
    1570          440 :     async fn attach(
    1571          440 :         self: &Arc<Tenant>,
    1572          440 :         preload: Option<TenantPreload>,
    1573          440 :         ctx: &RequestContext,
    1574          440 :     ) -> anyhow::Result<()> {
    1575          440 :         span::debug_assert_current_span_has_tenant_id();
    1576          440 : 
    1577          440 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1578              : 
    1579          440 :         let Some(preload) = preload else {
    1580            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1581              :         };
    1582              : 
    1583          440 :         let mut offloaded_timeline_ids = HashSet::new();
    1584          440 :         let mut offloaded_timelines_list = Vec::new();
    1585          440 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1586            0 :             let timeline_id = timeline_manifest.timeline_id;
    1587            0 :             let offloaded_timeline =
    1588            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1589            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1590            0 :             offloaded_timeline_ids.insert(timeline_id);
    1591            0 :         }
    1592              :         // Complete deletions for offloaded timeline id's from manifest.
    1593              :         // The manifest will be uploaded later in this function.
    1594          440 :         offloaded_timelines_list
    1595          440 :             .retain(|(offloaded_id, offloaded)| {
    1596            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1597            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1598            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1599            0 :                 if delete {
    1600            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1601            0 :                     offloaded.defuse_for_tenant_drop();
    1602            0 :                 }
    1603            0 :                 !delete
    1604          440 :         });
    1605          440 : 
    1606          440 :         let mut timelines_to_resume_deletions = vec![];
    1607          440 : 
    1608          440 :         let mut remote_index_and_client = HashMap::new();
    1609          440 :         let mut timeline_ancestors = HashMap::new();
    1610          440 :         let mut existent_timelines = HashSet::new();
    1611          452 :         for (timeline_id, preload) in preload.timelines {
    1612           12 :             let Some(preload) = preload else { continue };
    1613              :             // This is an invariant of the `preload` function's API
    1614           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1615           12 :             let index_part = match preload.index_part {
    1616           12 :                 Ok(i) => {
    1617           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1618              :                     // We found index_part on the remote, this is the standard case.
    1619           12 :                     existent_timelines.insert(timeline_id);
    1620           12 :                     i
    1621              :                 }
    1622              :                 Err(DownloadError::NotFound) => {
    1623              :                     // There is no index_part on the remote. We only get here
    1624              :                     // if there is some prefix for the timeline in the remote storage.
    1625              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1626              :                     // remnant from a prior incomplete creation or deletion attempt.
    1627              :                     // Delete the local directory as the deciding criterion for a
    1628              :                     // timeline's existence is presence of index_part.
    1629            0 :                     info!(%timeline_id, "index_part not found on remote");
    1630            0 :                     continue;
    1631              :                 }
    1632            0 :                 Err(DownloadError::Fatal(why)) => {
    1633            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1634            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1635            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1636            0 :                     anyhow::bail!(why.to_string());
    1637              :                 }
    1638            0 :                 Err(e) => {
    1639            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1640            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1641            0 :                     // as it might be a temporary issue and we don't want to re-download
    1642            0 :                     // everything after it resolves.
    1643            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1644              : 
    1645            0 :                     existent_timelines.insert(timeline_id);
    1646            0 :                     continue;
    1647              :                 }
    1648              :             };
    1649           12 :             match index_part {
    1650           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1651           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1652           12 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1653           12 :                 }
    1654            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1655            0 :                     info!(
    1656            0 :                         "timeline {} is deleted, picking to resume deletion",
    1657              :                         timeline_id
    1658              :                     );
    1659            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1660              :                 }
    1661              :             }
    1662              :         }
    1663              : 
    1664          440 :         let mut gc_blocks = HashMap::new();
    1665              : 
    1666              :         // For every timeline, download the metadata file, scan the local directory,
    1667              :         // and build a layer map that contains an entry for each remote and local
    1668              :         // layer file.
    1669          440 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1670          452 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1671           12 :             let (index_part, remote_client) = remote_index_and_client
    1672           12 :                 .remove(&timeline_id)
    1673           12 :                 .expect("just put it in above");
    1674              : 
    1675           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1676              :                 // could just filter these away, but it helps while testing
    1677            0 :                 anyhow::ensure!(
    1678            0 :                     !blocking.reasons.is_empty(),
    1679            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1680              :                 );
    1681            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1682            0 :                 assert!(prev.is_none());
    1683           12 :             }
    1684              : 
    1685              :             // TODO again handle early failure
    1686           12 :             let effect = self
    1687           12 :                 .load_remote_timeline(
    1688           12 :                     timeline_id,
    1689           12 :                     index_part,
    1690           12 :                     remote_metadata,
    1691           12 :                     TimelineResources {
    1692           12 :                         remote_client,
    1693           12 :                         pagestream_throttle: self.pagestream_throttle.clone(),
    1694           12 :                         pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    1695           12 :                         l0_flush_global_state: self.l0_flush_global_state.clone(),
    1696           12 :                     },
    1697           12 :                     LoadTimelineCause::Attach,
    1698           12 :                     ctx,
    1699           12 :                 )
    1700           12 :                 .await
    1701           12 :                 .with_context(|| {
    1702            0 :                     format!(
    1703            0 :                         "failed to load remote timeline {} for tenant {}",
    1704            0 :                         timeline_id, self.tenant_shard_id
    1705            0 :                     )
    1706           12 :                 })?;
    1707              : 
    1708           12 :             match effect {
    1709           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1710           12 :                     // activation happens later, on Tenant::activate
    1711           12 :                 }
    1712              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1713              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1714            0 :                         timeline,
    1715            0 :                         import_pgdata,
    1716            0 :                         guard,
    1717            0 :                     },
    1718            0 :                 ) => {
    1719            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1720            0 :                         timeline,
    1721            0 :                         import_pgdata,
    1722            0 :                         ActivateTimelineArgs::No,
    1723            0 :                         guard,
    1724            0 :                     ));
    1725            0 :                 }
    1726              :             }
    1727              :         }
    1728              : 
    1729              :         // Walk through deleted timelines, resume deletion
    1730          440 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1731            0 :             remote_timeline_client
    1732            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1733            0 :                 .context("init queue stopped")
    1734            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1735              : 
    1736            0 :             DeleteTimelineFlow::resume_deletion(
    1737            0 :                 Arc::clone(self),
    1738            0 :                 timeline_id,
    1739            0 :                 &index_part.metadata,
    1740            0 :                 remote_timeline_client,
    1741            0 :             )
    1742            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1743            0 :             .await
    1744            0 :             .context("resume_deletion")
    1745            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1746              :         }
    1747          440 :         let needs_manifest_upload =
    1748          440 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1749          440 :         {
    1750          440 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1751          440 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1752          440 :         }
    1753          440 :         if needs_manifest_upload {
    1754            0 :             self.store_tenant_manifest().await?;
    1755          440 :         }
    1756              : 
    1757              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1758              :         // IndexPart is the source of truth.
    1759          440 :         self.clean_up_timelines(&existent_timelines)?;
    1760              : 
    1761          440 :         self.gc_block.set_scanned(gc_blocks);
    1762          440 : 
    1763          440 :         fail::fail_point!("attach-before-activate", |_| {
    1764            0 :             anyhow::bail!("attach-before-activate");
    1765          440 :         });
    1766          440 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1767              : 
    1768          440 :         info!("Done");
    1769              : 
    1770          440 :         Ok(())
    1771          440 :     }
    1772              : 
    1773              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1774              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1775              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1776          440 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1777          440 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1778              : 
    1779          440 :         let entries = match timelines_dir.read_dir_utf8() {
    1780          440 :             Ok(d) => d,
    1781            0 :             Err(e) => {
    1782            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1783            0 :                     return Ok(());
    1784              :                 } else {
    1785            0 :                     return Err(e).context("list timelines directory for tenant");
    1786              :                 }
    1787              :             }
    1788              :         };
    1789              : 
    1790          456 :         for entry in entries {
    1791           16 :             let entry = entry.context("read timeline dir entry")?;
    1792           16 :             let entry_path = entry.path();
    1793              : 
    1794           16 :             let purge = if crate::is_temporary(entry_path)
    1795              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1796           16 :                 || is_uninit_mark(entry_path)
    1797           16 :                 || crate::is_delete_mark(entry_path)
    1798              :             {
    1799            0 :                 true
    1800              :             } else {
    1801           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1802           16 :                     Ok(i) => {
    1803           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1804           16 :                         !existent_timelines.contains(&i)
    1805              :                     }
    1806            0 :                     Err(e) => {
    1807            0 :                         tracing::warn!(
    1808            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1809              :                         );
    1810              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1811            0 :                         false
    1812              :                     }
    1813              :                 }
    1814              :             };
    1815              : 
    1816           16 :             if purge {
    1817            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1818            4 :                 if let Err(e) = match entry.file_type() {
    1819            4 :                     Ok(t) => if t.is_dir() {
    1820            4 :                         std::fs::remove_dir_all(entry_path)
    1821              :                     } else {
    1822            0 :                         std::fs::remove_file(entry_path)
    1823              :                     }
    1824            4 :                     .or_else(fs_ext::ignore_not_found),
    1825            0 :                     Err(e) => Err(e),
    1826              :                 } {
    1827            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1828            4 :                 }
    1829           12 :             }
    1830              :         }
    1831              : 
    1832          440 :         Ok(())
    1833          440 :     }
    1834              : 
    1835              :     /// Get sum of all remote timelines sizes
    1836              :     ///
    1837              :     /// This function relies on the index_part instead of listing the remote storage
    1838            0 :     pub fn remote_size(&self) -> u64 {
    1839            0 :         let mut size = 0;
    1840              : 
    1841            0 :         for timeline in self.list_timelines() {
    1842            0 :             size += timeline.remote_client.get_remote_physical_size();
    1843            0 :         }
    1844              : 
    1845            0 :         size
    1846            0 :     }
    1847              : 
    1848              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1849              :     async fn load_remote_timeline(
    1850              :         self: &Arc<Self>,
    1851              :         timeline_id: TimelineId,
    1852              :         index_part: IndexPart,
    1853              :         remote_metadata: TimelineMetadata,
    1854              :         resources: TimelineResources,
    1855              :         cause: LoadTimelineCause,
    1856              :         ctx: &RequestContext,
    1857              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1858              :         span::debug_assert_current_span_has_tenant_id();
    1859              : 
    1860              :         info!("downloading index file for timeline {}", timeline_id);
    1861              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1862              :             .await
    1863              :             .context("Failed to create new timeline directory")?;
    1864              : 
    1865              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1866              :             let timelines = self.timelines.lock().unwrap();
    1867              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1868            0 :                 || {
    1869            0 :                     anyhow::anyhow!(
    1870            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1871            0 :                     )
    1872            0 :                 },
    1873              :             )?))
    1874              :         } else {
    1875              :             None
    1876              :         };
    1877              : 
    1878              :         self.timeline_init_and_sync(
    1879              :             timeline_id,
    1880              :             resources,
    1881              :             index_part,
    1882              :             remote_metadata,
    1883              :             ancestor,
    1884              :             cause,
    1885              :             ctx,
    1886              :         )
    1887              :         .await
    1888              :     }
    1889              : 
    1890          440 :     async fn load_timelines_metadata(
    1891          440 :         self: &Arc<Tenant>,
    1892          440 :         timeline_ids: HashSet<TimelineId>,
    1893          440 :         remote_storage: &GenericRemoteStorage,
    1894          440 :         cancel: CancellationToken,
    1895          440 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1896          440 :         let mut part_downloads = JoinSet::new();
    1897          452 :         for timeline_id in timeline_ids {
    1898           12 :             let cancel_clone = cancel.clone();
    1899           12 :             part_downloads.spawn(
    1900           12 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1901           12 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1902              :             );
    1903              :         }
    1904              : 
    1905          440 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1906              : 
    1907              :         loop {
    1908          452 :             tokio::select!(
    1909          452 :                 next = part_downloads.join_next() => {
    1910          452 :                     match next {
    1911           12 :                         Some(result) => {
    1912           12 :                             let preload = result.context("join preload task")?;
    1913           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1914              :                         },
    1915              :                         None => {
    1916          440 :                             break;
    1917              :                         }
    1918              :                     }
    1919              :                 },
    1920          452 :                 _ = cancel.cancelled() => {
    1921            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1922              :                 }
    1923              :             )
    1924              :         }
    1925              : 
    1926          440 :         Ok(timeline_preloads)
    1927          440 :     }
    1928              : 
    1929           12 :     fn build_timeline_client(
    1930           12 :         &self,
    1931           12 :         timeline_id: TimelineId,
    1932           12 :         remote_storage: GenericRemoteStorage,
    1933           12 :     ) -> RemoteTimelineClient {
    1934           12 :         RemoteTimelineClient::new(
    1935           12 :             remote_storage.clone(),
    1936           12 :             self.deletion_queue_client.clone(),
    1937           12 :             self.conf,
    1938           12 :             self.tenant_shard_id,
    1939           12 :             timeline_id,
    1940           12 :             self.generation,
    1941           12 :             &self.tenant_conf.load().location,
    1942           12 :         )
    1943           12 :     }
    1944              : 
    1945           12 :     fn load_timeline_metadata(
    1946           12 :         self: &Arc<Tenant>,
    1947           12 :         timeline_id: TimelineId,
    1948           12 :         remote_storage: GenericRemoteStorage,
    1949           12 :         cancel: CancellationToken,
    1950           12 :     ) -> impl Future<Output = TimelinePreload> {
    1951           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1952           12 :         async move {
    1953           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1954           12 :             debug!("starting index part download");
    1955              : 
    1956           12 :             let index_part = client.download_index_file(&cancel).await;
    1957              : 
    1958           12 :             debug!("finished index part download");
    1959              : 
    1960           12 :             TimelinePreload {
    1961           12 :                 client,
    1962           12 :                 timeline_id,
    1963           12 :                 index_part,
    1964           12 :             }
    1965           12 :         }
    1966           12 :     }
    1967              : 
    1968            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1969            0 :         timeline_id: TimelineId,
    1970            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1971            0 :     ) -> Result<(), TimelineArchivalError> {
    1972            0 :         let children: Vec<TimelineId> = timelines
    1973            0 :             .iter()
    1974            0 :             .filter_map(|(id, entry)| {
    1975            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1976            0 :                     return None;
    1977            0 :                 }
    1978            0 :                 if entry.is_archived() == Some(true) {
    1979            0 :                     return None;
    1980            0 :                 }
    1981            0 :                 Some(*id)
    1982            0 :             })
    1983            0 :             .collect();
    1984            0 : 
    1985            0 :         if !children.is_empty() {
    1986            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1987            0 :         }
    1988            0 :         Ok(())
    1989            0 :     }
    1990              : 
    1991            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1992            0 :         ancestor_timeline_id: TimelineId,
    1993            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1994            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1995            0 :             '_,
    1996            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1997            0 :         >,
    1998            0 :     ) -> Result<(), TimelineArchivalError> {
    1999            0 :         let has_archived_parent =
    2000            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2001            0 :                 ancestor_timeline.is_archived() == Some(true)
    2002            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2003            0 :                 true
    2004              :             } else {
    2005            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2006            0 :                 if cfg!(debug_assertions) {
    2007            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2008            0 :                 }
    2009            0 :                 return Err(TimelineArchivalError::NotFound);
    2010              :             };
    2011            0 :         if has_archived_parent {
    2012            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2013            0 :                 ancestor_timeline_id,
    2014            0 :             ));
    2015            0 :         }
    2016            0 :         Ok(())
    2017            0 :     }
    2018              : 
    2019            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2020            0 :         timeline: &Arc<Timeline>,
    2021            0 :     ) -> Result<(), TimelineArchivalError> {
    2022            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2023            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2024            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2025            0 :                     ancestor_timeline.timeline_id,
    2026            0 :                 ));
    2027            0 :             }
    2028            0 :         }
    2029            0 :         Ok(())
    2030            0 :     }
    2031              : 
    2032              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2033              :     ///
    2034              :     /// Counterpart to [`offload_timeline`].
    2035            0 :     async fn unoffload_timeline(
    2036            0 :         self: &Arc<Self>,
    2037            0 :         timeline_id: TimelineId,
    2038            0 :         broker_client: storage_broker::BrokerClientChannel,
    2039            0 :         ctx: RequestContext,
    2040            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2041            0 :         info!("unoffloading timeline");
    2042              : 
    2043              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2044              :         // We expect callers of this function to ensure this.
    2045            0 :         match self.current_state() {
    2046              :             TenantState::Activating { .. }
    2047              :             | TenantState::Attaching
    2048              :             | TenantState::Broken { .. } => {
    2049            0 :                 panic!("Timeline expected to be active")
    2050              :             }
    2051            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2052            0 :             TenantState::Active => {}
    2053            0 :         }
    2054            0 :         let cancel = self.cancel.clone();
    2055            0 : 
    2056            0 :         // Protect against concurrent attempts to use this TimelineId
    2057            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2058            0 :         let allow_offloaded = true;
    2059            0 :         let _create_guard = self
    2060            0 :             .create_timeline_create_guard(
    2061            0 :                 timeline_id,
    2062            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2063            0 :                 allow_offloaded,
    2064            0 :             )
    2065            0 :             .map_err(|err| match err {
    2066            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2067              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2068            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2069              :                 }
    2070            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2071            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2072            0 :             })?;
    2073              : 
    2074            0 :         let timeline_preload = self
    2075            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    2076            0 :             .await;
    2077              : 
    2078            0 :         let index_part = match timeline_preload.index_part {
    2079            0 :             Ok(index_part) => {
    2080            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2081            0 :                 index_part
    2082              :             }
    2083              :             Err(DownloadError::NotFound) => {
    2084            0 :                 error!(%timeline_id, "index_part not found on remote");
    2085            0 :                 return Err(TimelineArchivalError::NotFound);
    2086              :             }
    2087            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2088            0 :             Err(e) => {
    2089            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2090            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2091            0 :                 return Err(TimelineArchivalError::Other(
    2092            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2093            0 :                 ));
    2094              :             }
    2095              :         };
    2096            0 :         let index_part = match index_part {
    2097            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2098            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2099            0 :                 info!("timeline is deleted according to index_part.json");
    2100            0 :                 return Err(TimelineArchivalError::NotFound);
    2101              :             }
    2102              :         };
    2103            0 :         let remote_metadata = index_part.metadata.clone();
    2104            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2105            0 :         self.load_remote_timeline(
    2106            0 :             timeline_id,
    2107            0 :             index_part,
    2108            0 :             remote_metadata,
    2109            0 :             timeline_resources,
    2110            0 :             LoadTimelineCause::Unoffload,
    2111            0 :             &ctx,
    2112            0 :         )
    2113            0 :         .await
    2114            0 :         .with_context(|| {
    2115            0 :             format!(
    2116            0 :                 "failed to load remote timeline {} for tenant {}",
    2117            0 :                 timeline_id, self.tenant_shard_id
    2118            0 :             )
    2119            0 :         })
    2120            0 :         .map_err(TimelineArchivalError::Other)?;
    2121              : 
    2122            0 :         let timeline = {
    2123            0 :             let timelines = self.timelines.lock().unwrap();
    2124            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2125            0 :                 warn!("timeline not available directly after attach");
    2126              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2127              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2128            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2129            0 :                     "timeline not available directly after attach"
    2130            0 :                 )));
    2131              :             };
    2132            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2133            0 :             match offloaded_timelines.remove(&timeline_id) {
    2134            0 :                 Some(offloaded) => {
    2135            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2136            0 :                 }
    2137            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2138              :             }
    2139              : 
    2140            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2141            0 : 
    2142            0 :             Arc::clone(timeline)
    2143            0 :         };
    2144            0 : 
    2145            0 :         // Upload new list of offloaded timelines to S3
    2146            0 :         self.store_tenant_manifest().await?;
    2147              : 
    2148              :         // Activate the timeline (if it makes sense)
    2149            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2150            0 :             let background_jobs_can_start = None;
    2151            0 :             timeline.activate(
    2152            0 :                 self.clone(),
    2153            0 :                 broker_client.clone(),
    2154            0 :                 background_jobs_can_start,
    2155            0 :                 &ctx,
    2156            0 :             );
    2157            0 :         }
    2158              : 
    2159            0 :         info!("timeline unoffloading complete");
    2160            0 :         Ok(timeline)
    2161            0 :     }
    2162              : 
    2163            0 :     pub(crate) async fn apply_timeline_archival_config(
    2164            0 :         self: &Arc<Self>,
    2165            0 :         timeline_id: TimelineId,
    2166            0 :         new_state: TimelineArchivalState,
    2167            0 :         broker_client: storage_broker::BrokerClientChannel,
    2168            0 :         ctx: RequestContext,
    2169            0 :     ) -> Result<(), TimelineArchivalError> {
    2170            0 :         info!("setting timeline archival config");
    2171              :         // First part: figure out what is needed to do, and do validation
    2172            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2173            0 :             let timelines = self.timelines.lock().unwrap();
    2174              : 
    2175            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2176            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2177            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2178            0 :                     return Err(TimelineArchivalError::NotFound);
    2179              :                 };
    2180            0 :                 if new_state == TimelineArchivalState::Archived {
    2181              :                     // It's offloaded already, so nothing to do
    2182            0 :                     return Ok(());
    2183            0 :                 }
    2184            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2185            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2186            0 :                         ancestor_timeline_id,
    2187            0 :                         &timelines,
    2188            0 :                         &offloaded_timelines,
    2189            0 :                     )?;
    2190            0 :                 }
    2191            0 :                 break 'outer None;
    2192              :             };
    2193              : 
    2194              :             // Do some validation. We release the timelines lock below, so there is potential
    2195              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2196              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2197            0 :             match new_state {
    2198              :                 TimelineArchivalState::Unarchived => {
    2199            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2200              :                 }
    2201              :                 TimelineArchivalState::Archived => {
    2202            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2203              :                 }
    2204              :             }
    2205            0 :             Some(Arc::clone(timeline))
    2206              :         };
    2207              : 
    2208              :         // Second part: unoffload timeline (if needed)
    2209            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2210            0 :             timeline
    2211              :         } else {
    2212              :             // Turn offloaded timeline into a non-offloaded one
    2213            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2214            0 :                 .await?
    2215              :         };
    2216              : 
    2217              :         // Third part: upload new timeline archival state and block until it is present in S3
    2218            0 :         let upload_needed = match timeline
    2219            0 :             .remote_client
    2220            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2221              :         {
    2222            0 :             Ok(upload_needed) => upload_needed,
    2223            0 :             Err(e) => {
    2224            0 :                 if timeline.cancel.is_cancelled() {
    2225            0 :                     return Err(TimelineArchivalError::Cancelled);
    2226              :                 } else {
    2227            0 :                     return Err(TimelineArchivalError::Other(e));
    2228              :                 }
    2229              :             }
    2230              :         };
    2231              : 
    2232            0 :         if upload_needed {
    2233            0 :             info!("Uploading new state");
    2234              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2235            0 :             let Ok(v) =
    2236            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2237              :             else {
    2238            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2239            0 :                 return Err(TimelineArchivalError::Timeout);
    2240              :             };
    2241            0 :             v.map_err(|e| match e {
    2242            0 :                 WaitCompletionError::NotInitialized(e) => {
    2243            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2244              :                 }
    2245              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2246            0 :                     TimelineArchivalError::Cancelled
    2247              :                 }
    2248            0 :             })?;
    2249            0 :         }
    2250            0 :         Ok(())
    2251            0 :     }
    2252              : 
    2253            4 :     pub fn get_offloaded_timeline(
    2254            4 :         &self,
    2255            4 :         timeline_id: TimelineId,
    2256            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2257            4 :         self.timelines_offloaded
    2258            4 :             .lock()
    2259            4 :             .unwrap()
    2260            4 :             .get(&timeline_id)
    2261            4 :             .map(Arc::clone)
    2262            4 :             .ok_or(GetTimelineError::NotFound {
    2263            4 :                 tenant_id: self.tenant_shard_id,
    2264            4 :                 timeline_id,
    2265            4 :             })
    2266            4 :     }
    2267              : 
    2268            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2269            8 :         self.tenant_shard_id
    2270            8 :     }
    2271              : 
    2272              :     /// Get Timeline handle for given Neon timeline ID.
    2273              :     /// This function is idempotent. It doesn't change internal state in any way.
    2274          444 :     pub fn get_timeline(
    2275          444 :         &self,
    2276          444 :         timeline_id: TimelineId,
    2277          444 :         active_only: bool,
    2278          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2279          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2280          444 :         let timeline = timelines_accessor
    2281          444 :             .get(&timeline_id)
    2282          444 :             .ok_or(GetTimelineError::NotFound {
    2283          444 :                 tenant_id: self.tenant_shard_id,
    2284          444 :                 timeline_id,
    2285          444 :             })?;
    2286              : 
    2287          440 :         if active_only && !timeline.is_active() {
    2288            0 :             Err(GetTimelineError::NotActive {
    2289            0 :                 tenant_id: self.tenant_shard_id,
    2290            0 :                 timeline_id,
    2291            0 :                 state: timeline.current_state(),
    2292            0 :             })
    2293              :         } else {
    2294          440 :             Ok(Arc::clone(timeline))
    2295              :         }
    2296          444 :     }
    2297              : 
    2298              :     /// Lists timelines the tenant contains.
    2299              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2300            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2301            0 :         self.timelines
    2302            0 :             .lock()
    2303            0 :             .unwrap()
    2304            0 :             .values()
    2305            0 :             .map(Arc::clone)
    2306            0 :             .collect()
    2307            0 :     }
    2308              : 
    2309              :     /// Lists timelines the tenant manages, including offloaded ones.
    2310              :     ///
    2311              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2312            0 :     pub fn list_timelines_and_offloaded(
    2313            0 :         &self,
    2314            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2315            0 :         let timelines = self
    2316            0 :             .timelines
    2317            0 :             .lock()
    2318            0 :             .unwrap()
    2319            0 :             .values()
    2320            0 :             .map(Arc::clone)
    2321            0 :             .collect();
    2322            0 :         let offloaded = self
    2323            0 :             .timelines_offloaded
    2324            0 :             .lock()
    2325            0 :             .unwrap()
    2326            0 :             .values()
    2327            0 :             .map(Arc::clone)
    2328            0 :             .collect();
    2329            0 :         (timelines, offloaded)
    2330            0 :     }
    2331              : 
    2332            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2333            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2334            0 :     }
    2335              : 
    2336              :     /// This is used by tests & import-from-basebackup.
    2337              :     ///
    2338              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2339              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2340              :     ///
    2341              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2342              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2343              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2344              :     /// to the [`Tenant::timelines`].
    2345              :     ///
    2346              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2347          424 :     pub(crate) async fn create_empty_timeline(
    2348          424 :         self: &Arc<Self>,
    2349          424 :         new_timeline_id: TimelineId,
    2350          424 :         initdb_lsn: Lsn,
    2351          424 :         pg_version: u32,
    2352          424 :         _ctx: &RequestContext,
    2353          424 :     ) -> anyhow::Result<UninitializedTimeline> {
    2354          424 :         anyhow::ensure!(
    2355          424 :             self.is_active(),
    2356            0 :             "Cannot create empty timelines on inactive tenant"
    2357              :         );
    2358              : 
    2359              :         // Protect against concurrent attempts to use this TimelineId
    2360          424 :         let create_guard = match self
    2361          424 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2362          424 :             .await?
    2363              :         {
    2364          420 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2365              :             StartCreatingTimelineResult::Idempotent(_) => {
    2366            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2367              :             }
    2368              :         };
    2369              : 
    2370          420 :         let new_metadata = TimelineMetadata::new(
    2371          420 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2372          420 :             // make it valid, before calling finish_creation()
    2373          420 :             Lsn(0),
    2374          420 :             None,
    2375          420 :             None,
    2376          420 :             Lsn(0),
    2377          420 :             initdb_lsn,
    2378          420 :             initdb_lsn,
    2379          420 :             pg_version,
    2380          420 :         );
    2381          420 :         self.prepare_new_timeline(
    2382          420 :             new_timeline_id,
    2383          420 :             &new_metadata,
    2384          420 :             create_guard,
    2385          420 :             initdb_lsn,
    2386          420 :             None,
    2387          420 :         )
    2388          420 :         .await
    2389          424 :     }
    2390              : 
    2391              :     /// Helper for unit tests to create an empty timeline.
    2392              :     ///
    2393              :     /// The timeline is has state value `Active` but its background loops are not running.
    2394              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2395              :     // Our current tests don't need the background loops.
    2396              :     #[cfg(test)]
    2397          404 :     pub async fn create_test_timeline(
    2398          404 :         self: &Arc<Self>,
    2399          404 :         new_timeline_id: TimelineId,
    2400          404 :         initdb_lsn: Lsn,
    2401          404 :         pg_version: u32,
    2402          404 :         ctx: &RequestContext,
    2403          404 :     ) -> anyhow::Result<Arc<Timeline>> {
    2404          404 :         let uninit_tl = self
    2405          404 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2406          404 :             .await?;
    2407          404 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2408          404 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2409              : 
    2410              :         // Setup minimum keys required for the timeline to be usable.
    2411          404 :         let mut modification = tline.begin_modification(initdb_lsn);
    2412          404 :         modification
    2413          404 :             .init_empty_test_timeline()
    2414          404 :             .context("init_empty_test_timeline")?;
    2415          404 :         modification
    2416          404 :             .commit(ctx)
    2417          404 :             .await
    2418          404 :             .context("commit init_empty_test_timeline modification")?;
    2419              : 
    2420              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2421          404 :         tline.maybe_spawn_flush_loop();
    2422          404 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2423              : 
    2424              :         // Make sure the freeze_and_flush reaches remote storage.
    2425          404 :         tline.remote_client.wait_completion().await.unwrap();
    2426              : 
    2427          404 :         let tl = uninit_tl.finish_creation()?;
    2428              :         // The non-test code would call tl.activate() here.
    2429          404 :         tl.set_state(TimelineState::Active);
    2430          404 :         Ok(tl)
    2431          404 :     }
    2432              : 
    2433              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2434              :     #[cfg(test)]
    2435              :     #[allow(clippy::too_many_arguments)]
    2436           76 :     pub async fn create_test_timeline_with_layers(
    2437           76 :         self: &Arc<Self>,
    2438           76 :         new_timeline_id: TimelineId,
    2439           76 :         initdb_lsn: Lsn,
    2440           76 :         pg_version: u32,
    2441           76 :         ctx: &RequestContext,
    2442           76 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2443           76 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2444           76 :         end_lsn: Lsn,
    2445           76 :     ) -> anyhow::Result<Arc<Timeline>> {
    2446              :         use checks::check_valid_layermap;
    2447              :         use itertools::Itertools;
    2448              : 
    2449           76 :         let tline = self
    2450           76 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2451           76 :             .await?;
    2452           76 :         tline.force_advance_lsn(end_lsn);
    2453          244 :         for deltas in delta_layer_desc {
    2454          168 :             tline
    2455          168 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2456          168 :                 .await?;
    2457              :         }
    2458          184 :         for (lsn, images) in image_layer_desc {
    2459          108 :             tline
    2460          108 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2461          108 :                 .await?;
    2462              :         }
    2463           76 :         let layer_names = tline
    2464           76 :             .layers
    2465           76 :             .read()
    2466           76 :             .await
    2467           76 :             .layer_map()
    2468           76 :             .unwrap()
    2469           76 :             .iter_historic_layers()
    2470          352 :             .map(|layer| layer.layer_name())
    2471           76 :             .collect_vec();
    2472           76 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2473            0 :             bail!("invalid layermap: {err}");
    2474           76 :         }
    2475           76 :         Ok(tline)
    2476           76 :     }
    2477              : 
    2478              :     /// Create a new timeline.
    2479              :     ///
    2480              :     /// Returns the new timeline ID and reference to its Timeline object.
    2481              :     ///
    2482              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2483              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2484              :     #[allow(clippy::too_many_arguments)]
    2485            0 :     pub(crate) async fn create_timeline(
    2486            0 :         self: &Arc<Tenant>,
    2487            0 :         params: CreateTimelineParams,
    2488            0 :         broker_client: storage_broker::BrokerClientChannel,
    2489            0 :         ctx: &RequestContext,
    2490            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2491            0 :         if !self.is_active() {
    2492            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2493            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2494              :             } else {
    2495            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2496            0 :                     "Cannot create timelines on inactive tenant"
    2497            0 :                 )));
    2498              :             }
    2499            0 :         }
    2500              : 
    2501            0 :         let _gate = self
    2502            0 :             .gate
    2503            0 :             .enter()
    2504            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2505              : 
    2506            0 :         let result: CreateTimelineResult = match params {
    2507              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2508            0 :                 new_timeline_id,
    2509            0 :                 existing_initdb_timeline_id,
    2510            0 :                 pg_version,
    2511            0 :             }) => {
    2512            0 :                 self.bootstrap_timeline(
    2513            0 :                     new_timeline_id,
    2514            0 :                     pg_version,
    2515            0 :                     existing_initdb_timeline_id,
    2516            0 :                     ctx,
    2517            0 :                 )
    2518            0 :                 .await?
    2519              :             }
    2520              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2521            0 :                 new_timeline_id,
    2522            0 :                 ancestor_timeline_id,
    2523            0 :                 mut ancestor_start_lsn,
    2524              :             }) => {
    2525            0 :                 let ancestor_timeline = self
    2526            0 :                     .get_timeline(ancestor_timeline_id, false)
    2527            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2528              : 
    2529              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2530              :                 // ready for other purposes either.
    2531            0 :                 if !ancestor_timeline.is_active() {
    2532            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2533            0 :                 }
    2534            0 : 
    2535            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2536            0 :                     info!("tried to branch archived timeline");
    2537            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2538            0 :                 }
    2539              : 
    2540            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2541            0 :                     *lsn = lsn.align();
    2542            0 : 
    2543            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2544            0 :                     if ancestor_ancestor_lsn > *lsn {
    2545              :                         // can we safely just branch from the ancestor instead?
    2546            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2547            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2548            0 :                             lsn,
    2549            0 :                             ancestor_timeline_id,
    2550            0 :                             ancestor_ancestor_lsn,
    2551            0 :                         )));
    2552            0 :                     }
    2553            0 : 
    2554            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2555            0 :                     // to the requested branch point. The repository code itself doesn't
    2556            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2557            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2558            0 :                     // sizes etc. and that would get confused if the previous page versions
    2559            0 :                     // are not in the repository yet.
    2560            0 :                     ancestor_timeline
    2561            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    2562            0 :                         .await
    2563            0 :                         .map_err(|e| match e {
    2564            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2565            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2566              :                             }
    2567            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2568            0 :                         })?;
    2569            0 :                 }
    2570              : 
    2571            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2572            0 :                     .await?
    2573              :             }
    2574            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2575            0 :                 self.create_timeline_import_pgdata(
    2576            0 :                     params,
    2577            0 :                     ActivateTimelineArgs::Yes {
    2578            0 :                         broker_client: broker_client.clone(),
    2579            0 :                     },
    2580            0 :                     ctx,
    2581            0 :                 )
    2582            0 :                 .await?
    2583              :             }
    2584              :         };
    2585              : 
    2586              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2587              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2588              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2589              :         //
    2590              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2591              :         // assume that, because they can see the timeline via API, that the creation is done and
    2592              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2593              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2594              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2595              :         //
    2596              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2597              :         // creation API until it returns success. Only then is durability guaranteed.
    2598            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2599            0 :         result
    2600            0 :             .timeline()
    2601            0 :             .remote_client
    2602            0 :             .wait_completion()
    2603            0 :             .await
    2604            0 :             .map_err(|e| match e {
    2605              :                 WaitCompletionError::NotInitialized(
    2606            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2607            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2608              :                 WaitCompletionError::NotInitialized(_) => {
    2609              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2610            0 :                     debug_assert!(false);
    2611            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2612              :                 }
    2613              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2614            0 :                     CreateTimelineError::ShuttingDown
    2615              :                 }
    2616            0 :             })?;
    2617              : 
    2618              :         // The creating task is responsible for activating the timeline.
    2619              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2620              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2621            0 :         let activated_timeline = match result {
    2622            0 :             CreateTimelineResult::Created(timeline) => {
    2623            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2624            0 :                 timeline
    2625              :             }
    2626            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2627            0 :                 info!(
    2628            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2629              :                 );
    2630            0 :                 timeline
    2631              :             }
    2632            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2633            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2634            0 :                 timeline
    2635              :             }
    2636              :         };
    2637              : 
    2638            0 :         Ok(activated_timeline)
    2639            0 :     }
    2640              : 
    2641              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2642              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2643              :     /// [`Tenant::timelines`] map when the import completes.
    2644              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2645              :     /// for the response.
    2646            0 :     async fn create_timeline_import_pgdata(
    2647            0 :         self: &Arc<Tenant>,
    2648            0 :         params: CreateTimelineParamsImportPgdata,
    2649            0 :         activate: ActivateTimelineArgs,
    2650            0 :         ctx: &RequestContext,
    2651            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2652            0 :         let CreateTimelineParamsImportPgdata {
    2653            0 :             new_timeline_id,
    2654            0 :             location,
    2655            0 :             idempotency_key,
    2656            0 :         } = params;
    2657            0 : 
    2658            0 :         let started_at = chrono::Utc::now().naive_utc();
    2659              : 
    2660              :         //
    2661              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2662              :         // is the canonical way we do it.
    2663              :         // - create an empty timeline in-memory
    2664              :         // - use its remote_timeline_client to do the upload
    2665              :         // - dispose of the uninit timeline
    2666              :         // - keep the creation guard alive
    2667              : 
    2668            0 :         let timeline_create_guard = match self
    2669            0 :             .start_creating_timeline(
    2670            0 :                 new_timeline_id,
    2671            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2672            0 :                     idempotency_key: idempotency_key.clone(),
    2673            0 :                 }),
    2674            0 :             )
    2675            0 :             .await?
    2676              :         {
    2677            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2678            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2679            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2680              :             }
    2681              :         };
    2682              : 
    2683            0 :         let mut uninit_timeline = {
    2684            0 :             let this = &self;
    2685            0 :             let initdb_lsn = Lsn(0);
    2686            0 :             let _ctx = ctx;
    2687            0 :             async move {
    2688            0 :                 let new_metadata = TimelineMetadata::new(
    2689            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2690            0 :                     // make it valid, before calling finish_creation()
    2691            0 :                     Lsn(0),
    2692            0 :                     None,
    2693            0 :                     None,
    2694            0 :                     Lsn(0),
    2695            0 :                     initdb_lsn,
    2696            0 :                     initdb_lsn,
    2697            0 :                     15,
    2698            0 :                 );
    2699            0 :                 this.prepare_new_timeline(
    2700            0 :                     new_timeline_id,
    2701            0 :                     &new_metadata,
    2702            0 :                     timeline_create_guard,
    2703            0 :                     initdb_lsn,
    2704            0 :                     None,
    2705            0 :                 )
    2706            0 :                 .await
    2707            0 :             }
    2708            0 :         }
    2709            0 :         .await?;
    2710              : 
    2711            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2712            0 :             idempotency_key,
    2713            0 :             location,
    2714            0 :             started_at,
    2715            0 :         };
    2716            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2717            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2718            0 :         );
    2719            0 :         uninit_timeline
    2720            0 :             .raw_timeline()
    2721            0 :             .unwrap()
    2722            0 :             .remote_client
    2723            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2724              : 
    2725              :         // wait_completion happens in caller
    2726              : 
    2727            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2728            0 : 
    2729            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2730            0 :             timeline.clone(),
    2731            0 :             index_part,
    2732            0 :             activate,
    2733            0 :             timeline_create_guard,
    2734            0 :         ));
    2735            0 : 
    2736            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2737            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2738            0 :     }
    2739              : 
    2740              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
    2741              :     async fn create_timeline_import_pgdata_task(
    2742              :         self: Arc<Tenant>,
    2743              :         timeline: Arc<Timeline>,
    2744              :         index_part: import_pgdata::index_part_format::Root,
    2745              :         activate: ActivateTimelineArgs,
    2746              :         timeline_create_guard: TimelineCreateGuard,
    2747              :     ) {
    2748              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2749              :         info!("starting");
    2750              :         scopeguard::defer! {info!("exiting")};
    2751              : 
    2752              :         let res = self
    2753              :             .create_timeline_import_pgdata_task_impl(
    2754              :                 timeline,
    2755              :                 index_part,
    2756              :                 activate,
    2757              :                 timeline_create_guard,
    2758              :             )
    2759              :             .await;
    2760              :         if let Err(err) = &res {
    2761              :             error!(?err, "task failed");
    2762              :             // TODO sleep & retry, sensitive to tenant shutdown
    2763              :             // TODO: allow timeline deletion requests => should cancel the task
    2764              :         }
    2765              :     }
    2766              : 
    2767            0 :     async fn create_timeline_import_pgdata_task_impl(
    2768            0 :         self: Arc<Tenant>,
    2769            0 :         timeline: Arc<Timeline>,
    2770            0 :         index_part: import_pgdata::index_part_format::Root,
    2771            0 :         activate: ActivateTimelineArgs,
    2772            0 :         timeline_create_guard: TimelineCreateGuard,
    2773            0 :     ) -> Result<(), anyhow::Error> {
    2774            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2775            0 : 
    2776            0 :         info!("importing pgdata");
    2777            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2778            0 :             .await
    2779            0 :             .context("import")?;
    2780            0 :         info!("import done");
    2781              : 
    2782              :         //
    2783              :         // Reload timeline from remote.
    2784              :         // This proves that the remote state is attachable, and it reuses the code.
    2785              :         //
    2786              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2787              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2788              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2789              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2790              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2791              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2792              :         // to manifest because of the long runtime of this import task.
    2793              : 
    2794              :         //        in theory this shouldn't even .await anything except for coop yield
    2795            0 :         info!("shutting down timeline");
    2796            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2797            0 :         info!("timeline shut down, reloading from remote");
    2798              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2799              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2800              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2801              :         // };
    2802            0 :         let timeline_id = timeline.timeline_id;
    2803            0 : 
    2804            0 :         // load from object storage like Tenant::attach does
    2805            0 :         let resources = self.build_timeline_resources(timeline_id);
    2806            0 :         let index_part = resources
    2807            0 :             .remote_client
    2808            0 :             .download_index_file(&self.cancel)
    2809            0 :             .await?;
    2810            0 :         let index_part = match index_part {
    2811              :             MaybeDeletedIndexPart::Deleted(_) => {
    2812              :                 // likely concurrent delete call, cplane should prevent this
    2813            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2814              :             }
    2815            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2816            0 :         };
    2817            0 :         let metadata = index_part.metadata.clone();
    2818            0 :         self
    2819            0 :             .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
    2820            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2821            0 :             .await?
    2822            0 :             .ready_to_activate()
    2823            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2824              : 
    2825            0 :         anyhow::Ok(())
    2826            0 :     }
    2827              : 
    2828            0 :     pub(crate) async fn delete_timeline(
    2829            0 :         self: Arc<Self>,
    2830            0 :         timeline_id: TimelineId,
    2831            0 :     ) -> Result<(), DeleteTimelineError> {
    2832            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2833              : 
    2834            0 :         Ok(())
    2835            0 :     }
    2836              : 
    2837              :     /// perform one garbage collection iteration, removing old data files from disk.
    2838              :     /// this function is periodically called by gc task.
    2839              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2840              :     ///
    2841              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2842              :     ///
    2843              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2844              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2845              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2846              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2847              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2848              :     /// requires more history to be retained.
    2849              :     //
    2850         1508 :     pub(crate) async fn gc_iteration(
    2851         1508 :         &self,
    2852         1508 :         target_timeline_id: Option<TimelineId>,
    2853         1508 :         horizon: u64,
    2854         1508 :         pitr: Duration,
    2855         1508 :         cancel: &CancellationToken,
    2856         1508 :         ctx: &RequestContext,
    2857         1508 :     ) -> Result<GcResult, GcError> {
    2858         1508 :         // Don't start doing work during shutdown
    2859         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2860            0 :             return Ok(GcResult::default());
    2861         1508 :         }
    2862         1508 : 
    2863         1508 :         // there is a global allowed_error for this
    2864         1508 :         if !self.is_active() {
    2865            0 :             return Err(GcError::NotActive);
    2866         1508 :         }
    2867         1508 : 
    2868         1508 :         {
    2869         1508 :             let conf = self.tenant_conf.load();
    2870         1508 : 
    2871         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2872         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2873         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2874         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2875         1508 :             if !conf.location.may_delete_layers_hint() {
    2876            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2877            0 :                 return Ok(GcResult::default());
    2878         1508 :             }
    2879         1508 : 
    2880         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2881         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2882         1500 :                 return Ok(GcResult::default());
    2883            8 :             }
    2884              :         }
    2885              : 
    2886            8 :         let _guard = match self.gc_block.start().await {
    2887            8 :             Ok(guard) => guard,
    2888            0 :             Err(reasons) => {
    2889            0 :                 info!("Skipping GC: {reasons}");
    2890            0 :                 return Ok(GcResult::default());
    2891              :             }
    2892              :         };
    2893              : 
    2894            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2895            8 :             .await
    2896         1508 :     }
    2897              : 
    2898              :     /// Perform one compaction iteration.
    2899              :     /// This function is periodically called by compactor task.
    2900              :     /// Also it can be explicitly requested per timeline through page server
    2901              :     /// api's 'compact' command.
    2902              :     ///
    2903              :     /// Returns whether we have pending compaction task.
    2904            0 :     async fn compaction_iteration(
    2905            0 :         self: &Arc<Self>,
    2906            0 :         cancel: &CancellationToken,
    2907            0 :         ctx: &RequestContext,
    2908            0 :     ) -> Result<bool, timeline::CompactionError> {
    2909            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2910            0 :         if !self.is_active() {
    2911            0 :             return Ok(false);
    2912            0 :         }
    2913            0 : 
    2914            0 :         {
    2915            0 :             let conf = self.tenant_conf.load();
    2916            0 : 
    2917            0 :             // Note that compaction usually requires deletions, but we don't respect
    2918            0 :             // may_delete_layers_hint here: that is because tenants in AttachedMulti
    2919            0 :             // should proceed with compaction even if they can't do deletion, to avoid
    2920            0 :             // accumulating dangerously deep stacks of L0 layers.  Deletions will be
    2921            0 :             // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
    2922            0 :             // to AttachedSingle state.
    2923            0 :             if !conf.location.may_upload_layers_hint() {
    2924            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2925            0 :                 return Ok(false);
    2926            0 :             }
    2927            0 :         }
    2928            0 : 
    2929            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2930            0 :         // while holding the lock. Then drop the lock and actually perform the
    2931            0 :         // compactions.  We don't want to block everything else while the
    2932            0 :         // compaction runs.
    2933            0 :         let timelines_to_compact_or_offload;
    2934            0 :         {
    2935            0 :             let timelines = self.timelines.lock().unwrap();
    2936            0 :             timelines_to_compact_or_offload = timelines
    2937            0 :                 .iter()
    2938            0 :                 .filter_map(|(timeline_id, timeline)| {
    2939            0 :                     let (is_active, (can_offload, _)) =
    2940            0 :                         (timeline.is_active(), timeline.can_offload());
    2941            0 :                     let has_no_unoffloaded_children = {
    2942            0 :                         !timelines
    2943            0 :                             .iter()
    2944            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2945              :                     };
    2946            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2947            0 :                         || self
    2948            0 :                             .tenant_conf
    2949            0 :                             .load()
    2950            0 :                             .tenant_conf
    2951            0 :                             .timeline_offloading
    2952            0 :                             .unwrap_or_default();
    2953            0 :                     let can_offload =
    2954            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2955            0 :                     if (is_active, can_offload) == (false, false) {
    2956            0 :                         None
    2957              :                     } else {
    2958            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2959              :                     }
    2960            0 :                 })
    2961            0 :                 .collect::<Vec<_>>();
    2962            0 :             drop(timelines);
    2963            0 :         }
    2964            0 : 
    2965            0 :         // Before doing any I/O work, check our circuit breaker
    2966            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2967            0 :             info!("Skipping compaction due to previous failures");
    2968            0 :             return Ok(false);
    2969            0 :         }
    2970            0 : 
    2971            0 :         let mut has_pending_task = false;
    2972              : 
    2973            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2974              :         {
    2975              :             // pending_task_left == None: cannot compact, maybe still pending tasks
    2976              :             // pending_task_left == Some(true): compaction task left
    2977              :             // pending_task_left == Some(false): no compaction task left
    2978            0 :             let pending_task_left = if *can_compact {
    2979            0 :                 let has_pending_l0_compaction_task = timeline
    2980            0 :                     .compact(cancel, EnumSet::empty(), ctx)
    2981            0 :                     .instrument(info_span!("compact_timeline", %timeline_id))
    2982            0 :                     .await
    2983            0 :                     .inspect_err(|e| match e {
    2984            0 :                         timeline::CompactionError::ShuttingDown => (),
    2985            0 :                         timeline::CompactionError::Offload(_) => {
    2986            0 :                             // Failures to offload timelines do not trip the circuit breaker, because
    2987            0 :                             // they do not do lots of writes the way compaction itself does: it is cheap
    2988            0 :                             // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2989            0 :                         }
    2990            0 :                         timeline::CompactionError::Other(e) => {
    2991            0 :                             self.compaction_circuit_breaker
    2992            0 :                                 .lock()
    2993            0 :                                 .unwrap()
    2994            0 :                                 .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2995            0 :                         }
    2996            0 :                     })?;
    2997            0 :                 if has_pending_l0_compaction_task {
    2998            0 :                     Some(true)
    2999              :                 } else {
    3000            0 :                     let queue = {
    3001            0 :                         let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3002            0 :                         guard.get(timeline_id).cloned()
    3003              :                     };
    3004            0 :                     if let Some(queue) = queue {
    3005            0 :                         let has_pending_tasks = queue
    3006            0 :                             .iteration(cancel, ctx, &self.gc_block, timeline)
    3007            0 :                             .await?;
    3008            0 :                         Some(has_pending_tasks)
    3009              :                     } else {
    3010            0 :                         Some(false)
    3011              :                     }
    3012              :                 }
    3013              :             } else {
    3014            0 :                 None
    3015              :             };
    3016            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    3017            0 :             if pending_task_left == Some(false) && *can_offload {
    3018            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3019            0 :                 match offload_timeline(self, timeline)
    3020            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    3021            0 :                     .await
    3022              :                 {
    3023              :                     Err(OffloadError::NotArchived) => {
    3024              :                         // Ignore this, we likely raced with unarchival
    3025            0 :                         Ok(())
    3026              :                     }
    3027            0 :                     other => other,
    3028            0 :                 }?;
    3029            0 :             }
    3030              :         }
    3031              : 
    3032            0 :         self.compaction_circuit_breaker
    3033            0 :             .lock()
    3034            0 :             .unwrap()
    3035            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3036            0 : 
    3037            0 :         Ok(has_pending_task)
    3038            0 :     }
    3039              : 
    3040              :     /// Cancel scheduled compaction tasks
    3041            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3042            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3043            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3044            0 :             q.cancel_scheduled();
    3045            0 :         }
    3046            0 :     }
    3047              : 
    3048            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3049            0 :         &self,
    3050            0 :         timeline_id: TimelineId,
    3051            0 :     ) -> Vec<CompactInfoResponse> {
    3052            0 :         let res = {
    3053            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3054            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3055              :         };
    3056            0 :         let Some((running, remaining)) = res else {
    3057            0 :             return Vec::new();
    3058              :         };
    3059            0 :         let mut result = Vec::new();
    3060            0 :         if let Some((id, running)) = running {
    3061            0 :             result.extend(running.into_compact_info_resp(id, true));
    3062            0 :         }
    3063            0 :         for (id, job) in remaining {
    3064            0 :             result.extend(job.into_compact_info_resp(id, false));
    3065            0 :         }
    3066            0 :         result
    3067            0 :     }
    3068              : 
    3069              :     /// Schedule a compaction task for a timeline.
    3070            0 :     pub(crate) async fn schedule_compaction(
    3071            0 :         &self,
    3072            0 :         timeline_id: TimelineId,
    3073            0 :         options: CompactOptions,
    3074            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3075            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3076            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3077            0 :         let q = guard
    3078            0 :             .entry(timeline_id)
    3079            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3080            0 :         q.schedule_manual_compaction(options, Some(tx));
    3081            0 :         Ok(rx)
    3082            0 :     }
    3083              : 
    3084              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    3085              :     // this happens during ingest: this background housekeeping is for freezing layers
    3086              :     // that are open but haven't been written to for some time.
    3087            0 :     async fn ingest_housekeeping(&self) {
    3088            0 :         // Scan through the hashmap and collect a list of all the timelines,
    3089            0 :         // while holding the lock. Then drop the lock and actually perform the
    3090            0 :         // compactions.  We don't want to block everything else while the
    3091            0 :         // compaction runs.
    3092            0 :         let timelines = {
    3093            0 :             self.timelines
    3094            0 :                 .lock()
    3095            0 :                 .unwrap()
    3096            0 :                 .values()
    3097            0 :                 .filter_map(|timeline| {
    3098            0 :                     if timeline.is_active() {
    3099            0 :                         Some(timeline.clone())
    3100              :                     } else {
    3101            0 :                         None
    3102              :                     }
    3103            0 :                 })
    3104            0 :                 .collect::<Vec<_>>()
    3105              :         };
    3106              : 
    3107            0 :         for timeline in &timelines {
    3108            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3109              :         }
    3110            0 :     }
    3111              : 
    3112            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3113            0 :         let timelines = self.timelines.lock().unwrap();
    3114            0 :         !timelines
    3115            0 :             .iter()
    3116            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3117            0 :     }
    3118              : 
    3119         3464 :     pub fn current_state(&self) -> TenantState {
    3120         3464 :         self.state.borrow().clone()
    3121         3464 :     }
    3122              : 
    3123         1940 :     pub fn is_active(&self) -> bool {
    3124         1940 :         self.current_state() == TenantState::Active
    3125         1940 :     }
    3126              : 
    3127            0 :     pub fn generation(&self) -> Generation {
    3128            0 :         self.generation
    3129            0 :     }
    3130              : 
    3131            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3132            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3133            0 :     }
    3134              : 
    3135              :     /// Changes tenant status to active, unless shutdown was already requested.
    3136              :     ///
    3137              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3138              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3139            0 :     fn activate(
    3140            0 :         self: &Arc<Self>,
    3141            0 :         broker_client: BrokerClientChannel,
    3142            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3143            0 :         ctx: &RequestContext,
    3144            0 :     ) {
    3145            0 :         span::debug_assert_current_span_has_tenant_id();
    3146            0 : 
    3147            0 :         let mut activating = false;
    3148            0 :         self.state.send_modify(|current_state| {
    3149              :             use pageserver_api::models::ActivatingFrom;
    3150            0 :             match &*current_state {
    3151              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3152            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3153              :                 }
    3154            0 :                 TenantState::Attaching => {
    3155            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3156            0 :                 }
    3157            0 :             }
    3158            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3159            0 :             activating = true;
    3160            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3161            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3162            0 :         });
    3163            0 : 
    3164            0 :         if activating {
    3165            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3166            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3167            0 :             let timelines_to_activate = timelines_accessor
    3168            0 :                 .values()
    3169            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3170            0 : 
    3171            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3172            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3173            0 : 
    3174            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3175            0 :             // down when they notice that the tenant is inactive.
    3176            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3177            0 : 
    3178            0 :             let mut activated_timelines = 0;
    3179              : 
    3180            0 :             for timeline in timelines_to_activate {
    3181            0 :                 timeline.activate(
    3182            0 :                     self.clone(),
    3183            0 :                     broker_client.clone(),
    3184            0 :                     background_jobs_can_start,
    3185            0 :                     ctx,
    3186            0 :                 );
    3187            0 :                 activated_timelines += 1;
    3188            0 :             }
    3189              : 
    3190            0 :             self.state.send_modify(move |current_state| {
    3191            0 :                 assert!(
    3192            0 :                     matches!(current_state, TenantState::Activating(_)),
    3193            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3194              :                 );
    3195            0 :                 *current_state = TenantState::Active;
    3196            0 : 
    3197            0 :                 let elapsed = self.constructed_at.elapsed();
    3198            0 :                 let total_timelines = timelines_accessor.len();
    3199            0 : 
    3200            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3201            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3202            0 :                 info!(
    3203            0 :                     since_creation_millis = elapsed.as_millis(),
    3204            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3205            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3206            0 :                     activated_timelines,
    3207            0 :                     total_timelines,
    3208            0 :                     post_state = <&'static str>::from(&*current_state),
    3209            0 :                     "activation attempt finished"
    3210              :                 );
    3211              : 
    3212            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3213            0 :             });
    3214            0 :         }
    3215            0 :     }
    3216              : 
    3217              :     /// Shutdown the tenant and join all of the spawned tasks.
    3218              :     ///
    3219              :     /// The method caters for all use-cases:
    3220              :     /// - pageserver shutdown (freeze_and_flush == true)
    3221              :     /// - detach + ignore (freeze_and_flush == false)
    3222              :     ///
    3223              :     /// This will attempt to shutdown even if tenant is broken.
    3224              :     ///
    3225              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3226              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3227              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3228              :     /// the ongoing shutdown.
    3229           12 :     async fn shutdown(
    3230           12 :         &self,
    3231           12 :         shutdown_progress: completion::Barrier,
    3232           12 :         shutdown_mode: timeline::ShutdownMode,
    3233           12 :     ) -> Result<(), completion::Barrier> {
    3234           12 :         span::debug_assert_current_span_has_tenant_id();
    3235              : 
    3236              :         // Set tenant (and its timlines) to Stoppping state.
    3237              :         //
    3238              :         // Since we can only transition into Stopping state after activation is complete,
    3239              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3240              :         //
    3241              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3242              :         // 1. Lock out any new requests to the tenants.
    3243              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3244              :         // 3. Signal cancellation for other tenant background loops.
    3245              :         // 4. ???
    3246              :         //
    3247              :         // The waiting for the cancellation is not done uniformly.
    3248              :         // We certainly wait for WAL receivers to shut down.
    3249              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3250              :         // But the tenant background loops are joined-on in our caller.
    3251              :         // It's mesed up.
    3252              :         // we just ignore the failure to stop
    3253              : 
    3254              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3255              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3256              :         // is very slow.
    3257           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3258            0 :             self.cancel.cancel();
    3259            0 : 
    3260            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3261            0 :             // are children of ours, so their flush loops will have shut down already
    3262            0 :             timeline::ShutdownMode::Hard
    3263              :         } else {
    3264           12 :             shutdown_mode
    3265              :         };
    3266              : 
    3267           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3268           12 :             Ok(()) => {}
    3269            0 :             Err(SetStoppingError::Broken) => {
    3270            0 :                 // assume that this is acceptable
    3271            0 :             }
    3272            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3273            0 :                 // give caller the option to wait for this this shutdown
    3274            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3275            0 :                 return Err(other);
    3276              :             }
    3277              :         };
    3278              : 
    3279           12 :         let mut js = tokio::task::JoinSet::new();
    3280           12 :         {
    3281           12 :             let timelines = self.timelines.lock().unwrap();
    3282           12 :             timelines.values().for_each(|timeline| {
    3283           12 :                 let timeline = Arc::clone(timeline);
    3284           12 :                 let timeline_id = timeline.timeline_id;
    3285           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3286           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3287           12 :             });
    3288           12 :         }
    3289           12 :         {
    3290           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3291           12 :             timelines_offloaded.values().for_each(|timeline| {
    3292            0 :                 timeline.defuse_for_tenant_drop();
    3293           12 :             });
    3294           12 :         }
    3295           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3296           12 :         tracing::info!("Waiting for timelines...");
    3297           24 :         while let Some(res) = js.join_next().await {
    3298            0 :             match res {
    3299           12 :                 Ok(()) => {}
    3300            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3301            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3302            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3303              :             }
    3304              :         }
    3305              : 
    3306           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3307            0 :             tracing::info!("Flushing deletion queue");
    3308            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3309            0 :                 match e {
    3310            0 :                     DeletionQueueError::ShuttingDown => {
    3311            0 :                         // This is the only error we expect for now. In the future, if more error
    3312            0 :                         // variants are added, we should handle them here.
    3313            0 :                     }
    3314              :                 }
    3315            0 :             }
    3316           12 :         }
    3317              : 
    3318              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3319              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3320           12 :         tracing::debug!("Cancelling CancellationToken");
    3321           12 :         self.cancel.cancel();
    3322           12 : 
    3323           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3324           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3325           12 :         //
    3326           12 :         // this will additionally shutdown and await all timeline tasks.
    3327           12 :         tracing::debug!("Waiting for tasks...");
    3328           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3329              : 
    3330           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3331           12 :             walredo_mgr.shutdown().await;
    3332            0 :         }
    3333              : 
    3334              :         // Wait for any in-flight operations to complete
    3335           12 :         self.gate.close().await;
    3336              : 
    3337           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3338           12 : 
    3339           12 :         Ok(())
    3340           12 :     }
    3341              : 
    3342              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3343              :     ///
    3344              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3345              :     ///
    3346              :     /// This function is not cancel-safe!
    3347              :     ///
    3348              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3349              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3350           12 :     async fn set_stopping(
    3351           12 :         &self,
    3352           12 :         progress: completion::Barrier,
    3353           12 :         _allow_transition_from_loading: bool,
    3354           12 :         allow_transition_from_attaching: bool,
    3355           12 :     ) -> Result<(), SetStoppingError> {
    3356           12 :         let mut rx = self.state.subscribe();
    3357           12 : 
    3358           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3359           12 :         rx.wait_for(|state| match state {
    3360            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3361              :             TenantState::Activating(_) | TenantState::Attaching => {
    3362            0 :                 info!(
    3363            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3364            0 :                     <&'static str>::from(state)
    3365              :                 );
    3366            0 :                 false
    3367              :             }
    3368           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3369           12 :         })
    3370           12 :         .await
    3371           12 :         .expect("cannot drop self.state while on a &self method");
    3372           12 : 
    3373           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3374           12 :         let mut err = None;
    3375           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3376              :             TenantState::Activating(_) => {
    3377            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3378              :             }
    3379              :             TenantState::Attaching => {
    3380            0 :                 if !allow_transition_from_attaching {
    3381            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3382            0 :                 };
    3383            0 :                 *current_state = TenantState::Stopping { progress };
    3384            0 :                 true
    3385              :             }
    3386              :             TenantState::Active => {
    3387              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3388              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3389              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3390           12 :                 *current_state = TenantState::Stopping { progress };
    3391           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3392           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3393           12 :                 true
    3394              :             }
    3395            0 :             TenantState::Broken { reason, .. } => {
    3396            0 :                 info!(
    3397            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3398              :                 );
    3399            0 :                 err = Some(SetStoppingError::Broken);
    3400            0 :                 false
    3401              :             }
    3402            0 :             TenantState::Stopping { progress } => {
    3403            0 :                 info!("Tenant is already in Stopping state");
    3404            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3405            0 :                 false
    3406              :             }
    3407           12 :         });
    3408           12 :         match (stopping, err) {
    3409           12 :             (true, None) => {} // continue
    3410            0 :             (false, Some(err)) => return Err(err),
    3411            0 :             (true, Some(_)) => unreachable!(
    3412            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3413            0 :             ),
    3414            0 :             (false, None) => unreachable!(
    3415            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3416            0 :             ),
    3417              :         }
    3418              : 
    3419           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3420           12 :         let not_broken_timelines = timelines_accessor
    3421           12 :             .values()
    3422           12 :             .filter(|timeline| !timeline.is_broken());
    3423           24 :         for timeline in not_broken_timelines {
    3424           12 :             timeline.set_state(TimelineState::Stopping);
    3425           12 :         }
    3426           12 :         Ok(())
    3427           12 :     }
    3428              : 
    3429              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3430              :     /// `remove_tenant_from_memory`
    3431              :     ///
    3432              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3433              :     ///
    3434              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3435            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3436            0 :         let mut rx = self.state.subscribe();
    3437            0 : 
    3438            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3439            0 :         // So, wait until it's done.
    3440            0 :         rx.wait_for(|state| match state {
    3441              :             TenantState::Activating(_) | TenantState::Attaching => {
    3442            0 :                 info!(
    3443            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3444            0 :                     <&'static str>::from(state)
    3445              :                 );
    3446            0 :                 false
    3447              :             }
    3448            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3449            0 :         })
    3450            0 :         .await
    3451            0 :         .expect("cannot drop self.state while on a &self method");
    3452            0 : 
    3453            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3454            0 :         self.set_broken_no_wait(reason)
    3455            0 :     }
    3456              : 
    3457            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3458            0 :         let reason = reason.to_string();
    3459            0 :         self.state.send_modify(|current_state| {
    3460            0 :             match *current_state {
    3461              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3462            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3463              :                 }
    3464              :                 TenantState::Active => {
    3465            0 :                     if cfg!(feature = "testing") {
    3466            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3467            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3468              :                     } else {
    3469            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3470              :                     }
    3471              :                 }
    3472              :                 TenantState::Broken { .. } => {
    3473            0 :                     warn!("Tenant is already in Broken state");
    3474              :                 }
    3475              :                 // This is the only "expected" path, any other path is a bug.
    3476              :                 TenantState::Stopping { .. } => {
    3477            0 :                     warn!(
    3478            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3479              :                         reason
    3480              :                     );
    3481            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3482              :                 }
    3483              :            }
    3484            0 :         });
    3485            0 :     }
    3486              : 
    3487            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3488            0 :         self.state.subscribe()
    3489            0 :     }
    3490              : 
    3491              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3492              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3493            0 :     pub(crate) fn activate_now(&self) {
    3494            0 :         self.activate_now_sem.add_permits(1);
    3495            0 :     }
    3496              : 
    3497            0 :     pub(crate) async fn wait_to_become_active(
    3498            0 :         &self,
    3499            0 :         timeout: Duration,
    3500            0 :     ) -> Result<(), GetActiveTenantError> {
    3501            0 :         let mut receiver = self.state.subscribe();
    3502              :         loop {
    3503            0 :             let current_state = receiver.borrow_and_update().clone();
    3504            0 :             match current_state {
    3505              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3506              :                     // in these states, there's a chance that we can reach ::Active
    3507            0 :                     self.activate_now();
    3508            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3509            0 :                         Ok(r) => {
    3510            0 :                             r.map_err(
    3511            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3512              :                                 // Tenant existed but was dropped: report it as non-existent
    3513            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3514            0 :                         )?
    3515              :                         }
    3516              :                         Err(TimeoutCancellableError::Cancelled) => {
    3517            0 :                             return Err(GetActiveTenantError::Cancelled);
    3518              :                         }
    3519              :                         Err(TimeoutCancellableError::Timeout) => {
    3520            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3521            0 :                                 latest_state: Some(self.current_state()),
    3522            0 :                                 wait_time: timeout,
    3523            0 :                             });
    3524              :                         }
    3525              :                     }
    3526              :                 }
    3527              :                 TenantState::Active { .. } => {
    3528            0 :                     return Ok(());
    3529              :                 }
    3530            0 :                 TenantState::Broken { reason, .. } => {
    3531            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3532            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3533            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3534              :                 }
    3535              :                 TenantState::Stopping { .. } => {
    3536              :                     // There's no chance the tenant can transition back into ::Active
    3537            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3538              :                 }
    3539              :             }
    3540              :         }
    3541            0 :     }
    3542              : 
    3543            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3544            0 :         self.tenant_conf.load().location.attach_mode
    3545            0 :     }
    3546              : 
    3547              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3548              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3549              :     /// rare external API calls, like a reconciliation at startup.
    3550            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3551            0 :         let conf = self.tenant_conf.load();
    3552              : 
    3553            0 :         let location_config_mode = match conf.location.attach_mode {
    3554            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3555            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3556            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3557              :         };
    3558              : 
    3559              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3560            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3561            0 : 
    3562            0 :         models::LocationConfig {
    3563            0 :             mode: location_config_mode,
    3564            0 :             generation: self.generation.into(),
    3565            0 :             secondary_conf: None,
    3566            0 :             shard_number: self.shard_identity.number.0,
    3567            0 :             shard_count: self.shard_identity.count.literal(),
    3568            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3569            0 :             tenant_conf: tenant_config,
    3570            0 :         }
    3571            0 :     }
    3572              : 
    3573            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3574            0 :         &self.tenant_shard_id
    3575            0 :     }
    3576              : 
    3577            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3578            0 :         self.shard_identity.stripe_size
    3579            0 :     }
    3580              : 
    3581            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3582            0 :         self.generation
    3583            0 :     }
    3584              : 
    3585              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3586              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3587              :     /// resetting this tenant to a valid state if we fail.
    3588            0 :     pub(crate) async fn split_prepare(
    3589            0 :         &self,
    3590            0 :         child_shards: &Vec<TenantShardId>,
    3591            0 :     ) -> anyhow::Result<()> {
    3592            0 :         let (timelines, offloaded) = {
    3593            0 :             let timelines = self.timelines.lock().unwrap();
    3594            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3595            0 :             (timelines.clone(), offloaded.clone())
    3596            0 :         };
    3597            0 :         let timelines_iter = timelines
    3598            0 :             .values()
    3599            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3600            0 :             .chain(
    3601            0 :                 offloaded
    3602            0 :                     .values()
    3603            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3604            0 :             );
    3605            0 :         for timeline in timelines_iter {
    3606              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3607              :             // to ensure that they do not start a split if currently in the process of doing these.
    3608              : 
    3609            0 :             let timeline_id = timeline.timeline_id();
    3610              : 
    3611            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3612              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3613              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3614              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3615            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3616            0 :                 timeline
    3617            0 :                     .remote_client
    3618            0 :                     .schedule_index_upload_for_file_changes()?;
    3619            0 :                 timeline.remote_client.wait_completion().await?;
    3620            0 :             }
    3621              : 
    3622            0 :             let remote_client = match timeline {
    3623            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3624            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3625            0 :                     let remote_client = self
    3626            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3627            0 :                     Arc::new(remote_client)
    3628              :                 }
    3629              :             };
    3630              : 
    3631              :             // Shut down the timeline's remote client: this means that the indices we write
    3632              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3633            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3634            0 :             remote_client.shutdown().await;
    3635              : 
    3636              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3637              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3638              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3639              :             // we use here really is the remotely persistent one).
    3640            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3641            0 :             let result = remote_client
    3642            0 :                 .download_index_file(&self.cancel)
    3643            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))
    3644            0 :                 .await?;
    3645            0 :             let index_part = match result {
    3646              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3647            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3648              :                 }
    3649            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3650              :             };
    3651              : 
    3652            0 :             for child_shard in child_shards {
    3653            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3654            0 :                 upload_index_part(
    3655            0 :                     &self.remote_storage,
    3656            0 :                     child_shard,
    3657            0 :                     &timeline_id,
    3658            0 :                     self.generation,
    3659            0 :                     &index_part,
    3660            0 :                     &self.cancel,
    3661            0 :                 )
    3662            0 :                 .await?;
    3663              :             }
    3664              :         }
    3665              : 
    3666            0 :         let tenant_manifest = self.build_tenant_manifest();
    3667            0 :         for child_shard in child_shards {
    3668            0 :             tracing::info!(
    3669            0 :                 "Uploading tenant manifest for child {}",
    3670            0 :                 child_shard.to_index()
    3671              :             );
    3672            0 :             upload_tenant_manifest(
    3673            0 :                 &self.remote_storage,
    3674            0 :                 child_shard,
    3675            0 :                 self.generation,
    3676            0 :                 &tenant_manifest,
    3677            0 :                 &self.cancel,
    3678            0 :             )
    3679            0 :             .await?;
    3680              :         }
    3681              : 
    3682            0 :         Ok(())
    3683            0 :     }
    3684              : 
    3685            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3686            0 :         let mut result = TopTenantShardItem {
    3687            0 :             id: self.tenant_shard_id,
    3688            0 :             resident_size: 0,
    3689            0 :             physical_size: 0,
    3690            0 :             max_logical_size: 0,
    3691            0 :         };
    3692              : 
    3693            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3694            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3695            0 : 
    3696            0 :             result.physical_size += timeline
    3697            0 :                 .remote_client
    3698            0 :                 .metrics
    3699            0 :                 .remote_physical_size_gauge
    3700            0 :                 .get();
    3701            0 :             result.max_logical_size = std::cmp::max(
    3702            0 :                 result.max_logical_size,
    3703            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3704            0 :             );
    3705            0 :         }
    3706              : 
    3707            0 :         result
    3708            0 :     }
    3709              : }
    3710              : 
    3711              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3712              : /// perform a topological sort, so that the parent of each timeline comes
    3713              : /// before the children.
    3714              : /// E extracts the ancestor from T
    3715              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3716          440 : fn tree_sort_timelines<T, E>(
    3717          440 :     timelines: HashMap<TimelineId, T>,
    3718          440 :     extractor: E,
    3719          440 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3720          440 : where
    3721          440 :     E: Fn(&T) -> Option<TimelineId>,
    3722          440 : {
    3723          440 :     let mut result = Vec::with_capacity(timelines.len());
    3724          440 : 
    3725          440 :     let mut now = Vec::with_capacity(timelines.len());
    3726          440 :     // (ancestor, children)
    3727          440 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3728          440 :         HashMap::with_capacity(timelines.len());
    3729              : 
    3730          452 :     for (timeline_id, value) in timelines {
    3731           12 :         if let Some(ancestor_id) = extractor(&value) {
    3732            4 :             let children = later.entry(ancestor_id).or_default();
    3733            4 :             children.push((timeline_id, value));
    3734            8 :         } else {
    3735            8 :             now.push((timeline_id, value));
    3736            8 :         }
    3737              :     }
    3738              : 
    3739          452 :     while let Some((timeline_id, metadata)) = now.pop() {
    3740           12 :         result.push((timeline_id, metadata));
    3741              :         // All children of this can be loaded now
    3742           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3743            4 :             now.append(&mut children);
    3744            8 :         }
    3745              :     }
    3746              : 
    3747              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3748          440 :     if !later.is_empty() {
    3749            0 :         for (missing_id, orphan_ids) in later {
    3750            0 :             for (orphan_id, _) in orphan_ids {
    3751            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3752              :             }
    3753              :         }
    3754            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3755          440 :     }
    3756          440 : 
    3757          440 :     Ok(result)
    3758          440 : }
    3759              : 
    3760              : enum ActivateTimelineArgs {
    3761              :     Yes {
    3762              :         broker_client: storage_broker::BrokerClientChannel,
    3763              :     },
    3764              :     No,
    3765              : }
    3766              : 
    3767              : impl Tenant {
    3768            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3769            0 :         self.tenant_conf.load().tenant_conf.clone()
    3770            0 :     }
    3771              : 
    3772            0 :     pub fn effective_config(&self) -> TenantConf {
    3773            0 :         self.tenant_specific_overrides()
    3774            0 :             .merge(self.conf.default_tenant_conf.clone())
    3775            0 :     }
    3776              : 
    3777            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3778            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3779            0 :         tenant_conf
    3780            0 :             .checkpoint_distance
    3781            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3782            0 :     }
    3783              : 
    3784            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3785            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3786            0 :         tenant_conf
    3787            0 :             .checkpoint_timeout
    3788            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3789            0 :     }
    3790              : 
    3791            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3792            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3793            0 :         tenant_conf
    3794            0 :             .compaction_target_size
    3795            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3796            0 :     }
    3797              : 
    3798            0 :     pub fn get_compaction_period(&self) -> Duration {
    3799            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3800            0 :         tenant_conf
    3801            0 :             .compaction_period
    3802            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3803            0 :     }
    3804              : 
    3805            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3806            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3807            0 :         tenant_conf
    3808            0 :             .compaction_threshold
    3809            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3810            0 :     }
    3811              : 
    3812            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3813            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3814            0 :         tenant_conf
    3815            0 :             .gc_horizon
    3816            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3817            0 :     }
    3818              : 
    3819            0 :     pub fn get_gc_period(&self) -> Duration {
    3820            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3821            0 :         tenant_conf
    3822            0 :             .gc_period
    3823            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3824            0 :     }
    3825              : 
    3826            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3827            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3828            0 :         tenant_conf
    3829            0 :             .image_creation_threshold
    3830            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3831            0 :     }
    3832              : 
    3833            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3834            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3835            0 :         tenant_conf
    3836            0 :             .pitr_interval
    3837            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3838            0 :     }
    3839              : 
    3840            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3841            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3842            0 :         tenant_conf
    3843            0 :             .min_resident_size_override
    3844            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3845            0 :     }
    3846              : 
    3847            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3848            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3849            0 :         let heatmap_period = tenant_conf
    3850            0 :             .heatmap_period
    3851            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3852            0 :         if heatmap_period.is_zero() {
    3853            0 :             None
    3854              :         } else {
    3855            0 :             Some(heatmap_period)
    3856              :         }
    3857            0 :     }
    3858              : 
    3859            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3860            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3861            8 :         tenant_conf
    3862            8 :             .lsn_lease_length
    3863            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3864            8 :     }
    3865              : 
    3866              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3867            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3868            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3869            4 : 
    3870            4 :         let mut timeline_manifests = timelines_offloaded
    3871            4 :             .iter()
    3872            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3873            4 :             .collect::<Vec<_>>();
    3874            4 :         // Sort the manifests so that our output is deterministic
    3875            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3876            4 : 
    3877            4 :         TenantManifest {
    3878            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3879            4 :             offloaded_timelines: timeline_manifests,
    3880            4 :         }
    3881            4 :     }
    3882              : 
    3883            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    3884            0 :         &self,
    3885            0 :         update: F,
    3886            0 :     ) -> anyhow::Result<TenantConfOpt> {
    3887            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3888            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3889            0 :         // this race is not possible if both request types come from the storage
    3890            0 :         // controller (as they should!) because an exclusive op lock is required
    3891            0 :         // on the storage controller side.
    3892            0 : 
    3893            0 :         self.tenant_conf
    3894            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    3895            0 :                 Ok(Arc::new(AttachedTenantConf {
    3896            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    3897            0 :                     location: attached_conf.location,
    3898            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    3899              :                 }))
    3900            0 :             })?;
    3901              : 
    3902            0 :         let updated = self.tenant_conf.load();
    3903            0 : 
    3904            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    3905            0 :         // Don't hold self.timelines.lock() during the notifies.
    3906            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3907            0 :         // mutexes in struct Timeline in the future.
    3908            0 :         let timelines = self.list_timelines();
    3909            0 :         for timeline in timelines {
    3910            0 :             timeline.tenant_conf_updated(&updated);
    3911            0 :         }
    3912              : 
    3913            0 :         Ok(updated.tenant_conf.clone())
    3914            0 :     }
    3915              : 
    3916            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3917            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3918            0 : 
    3919            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    3920            0 : 
    3921            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3922            0 :         // Don't hold self.timelines.lock() during the notifies.
    3923            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3924            0 :         // mutexes in struct Timeline in the future.
    3925            0 :         let timelines = self.list_timelines();
    3926            0 :         for timeline in timelines {
    3927            0 :             timeline.tenant_conf_updated(&new_conf);
    3928            0 :         }
    3929            0 :     }
    3930              : 
    3931          440 :     fn get_pagestream_throttle_config(
    3932          440 :         psconf: &'static PageServerConf,
    3933          440 :         overrides: &TenantConfOpt,
    3934          440 :     ) -> throttle::Config {
    3935          440 :         overrides
    3936          440 :             .timeline_get_throttle
    3937          440 :             .clone()
    3938          440 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3939          440 :     }
    3940              : 
    3941            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3942            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    3943            0 :         self.pagestream_throttle.reconfigure(conf)
    3944            0 :     }
    3945              : 
    3946              :     /// Helper function to create a new Timeline struct.
    3947              :     ///
    3948              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3949              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3950              :     /// map.
    3951              :     ///
    3952              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3953              :     /// and we might not have the ancestor present anymore which is fine for to be
    3954              :     /// deleted timelines.
    3955              :     #[allow(clippy::too_many_arguments)]
    3956          892 :     fn create_timeline_struct(
    3957          892 :         &self,
    3958          892 :         new_timeline_id: TimelineId,
    3959          892 :         new_metadata: &TimelineMetadata,
    3960          892 :         ancestor: Option<Arc<Timeline>>,
    3961          892 :         resources: TimelineResources,
    3962          892 :         cause: CreateTimelineCause,
    3963          892 :         create_idempotency: CreateTimelineIdempotency,
    3964          892 :     ) -> anyhow::Result<Arc<Timeline>> {
    3965          892 :         let state = match cause {
    3966              :             CreateTimelineCause::Load => {
    3967          892 :                 let ancestor_id = new_metadata.ancestor_timeline();
    3968          892 :                 anyhow::ensure!(
    3969          892 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    3970            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    3971              :                 );
    3972          892 :                 TimelineState::Loading
    3973              :             }
    3974            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    3975              :         };
    3976              : 
    3977          892 :         let pg_version = new_metadata.pg_version();
    3978          892 : 
    3979          892 :         let timeline = Timeline::new(
    3980          892 :             self.conf,
    3981          892 :             Arc::clone(&self.tenant_conf),
    3982          892 :             new_metadata,
    3983          892 :             ancestor,
    3984          892 :             new_timeline_id,
    3985          892 :             self.tenant_shard_id,
    3986          892 :             self.generation,
    3987          892 :             self.shard_identity,
    3988          892 :             self.walredo_mgr.clone(),
    3989          892 :             resources,
    3990          892 :             pg_version,
    3991          892 :             state,
    3992          892 :             self.attach_wal_lag_cooldown.clone(),
    3993          892 :             create_idempotency,
    3994          892 :             self.cancel.child_token(),
    3995          892 :         );
    3996          892 : 
    3997          892 :         Ok(timeline)
    3998          892 :     }
    3999              : 
    4000              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4001              :     /// to ensure proper cleanup of background tasks and metrics.
    4002              :     //
    4003              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4004              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4005              :     #[allow(clippy::too_many_arguments)]
    4006          440 :     fn new(
    4007          440 :         state: TenantState,
    4008          440 :         conf: &'static PageServerConf,
    4009          440 :         attached_conf: AttachedTenantConf,
    4010          440 :         shard_identity: ShardIdentity,
    4011          440 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4012          440 :         tenant_shard_id: TenantShardId,
    4013          440 :         remote_storage: GenericRemoteStorage,
    4014          440 :         deletion_queue_client: DeletionQueueClient,
    4015          440 :         l0_flush_global_state: L0FlushGlobalState,
    4016          440 :     ) -> Tenant {
    4017          440 :         debug_assert!(
    4018          440 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4019              :         );
    4020              : 
    4021          440 :         let (state, mut rx) = watch::channel(state);
    4022          440 : 
    4023          440 :         tokio::spawn(async move {
    4024          439 :             // reflect tenant state in metrics:
    4025          439 :             // - global per tenant state: TENANT_STATE_METRIC
    4026          439 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4027          439 :             //
    4028          439 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4029          439 :             // alerting.
    4030          439 : 
    4031          439 :             let tid = tenant_shard_id.to_string();
    4032          439 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4033          439 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4034              : 
    4035          878 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4036          878 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4037          878 :             }
    4038              : 
    4039          439 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4040          439 : 
    4041          439 :             let is_broken = tuple.1;
    4042          439 :             let mut counted_broken = if is_broken {
    4043              :                 // add the id to the set right away, there should not be any updates on the channel
    4044              :                 // after before tenant is removed, if ever
    4045            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4046            0 :                 true
    4047              :             } else {
    4048          439 :                 false
    4049              :             };
    4050              : 
    4051              :             loop {
    4052          878 :                 let labels = &tuple.0;
    4053          878 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4054          878 :                 current.inc();
    4055          878 : 
    4056          878 :                 if rx.changed().await.is_err() {
    4057              :                     // tenant has been dropped
    4058           28 :                     current.dec();
    4059           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4060           28 :                     break;
    4061          439 :                 }
    4062          439 : 
    4063          439 :                 current.dec();
    4064          439 :                 tuple = inspect_state(&rx.borrow_and_update());
    4065          439 : 
    4066          439 :                 let is_broken = tuple.1;
    4067          439 :                 if is_broken && !counted_broken {
    4068            0 :                     counted_broken = true;
    4069            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4070            0 :                     // access
    4071            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4072          439 :                 }
    4073              :             }
    4074          440 :         });
    4075          440 : 
    4076          440 :         Tenant {
    4077          440 :             tenant_shard_id,
    4078          440 :             shard_identity,
    4079          440 :             generation: attached_conf.location.generation,
    4080          440 :             conf,
    4081          440 :             // using now here is good enough approximation to catch tenants with really long
    4082          440 :             // activation times.
    4083          440 :             constructed_at: Instant::now(),
    4084          440 :             timelines: Mutex::new(HashMap::new()),
    4085          440 :             timelines_creating: Mutex::new(HashSet::new()),
    4086          440 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4087          440 :             tenant_manifest_upload: Default::default(),
    4088          440 :             gc_cs: tokio::sync::Mutex::new(()),
    4089          440 :             walredo_mgr,
    4090          440 :             remote_storage,
    4091          440 :             deletion_queue_client,
    4092          440 :             state,
    4093          440 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4094          440 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4095          440 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4096          440 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4097          440 :                 format!("compaction-{tenant_shard_id}"),
    4098          440 :                 5,
    4099          440 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4100          440 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4101          440 :                 // use an extremely long backoff.
    4102          440 :                 Some(Duration::from_secs(3600 * 24)),
    4103          440 :             )),
    4104          440 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4105          440 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4106          440 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4107          440 :             cancel: CancellationToken::default(),
    4108          440 :             gate: Gate::default(),
    4109          440 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4110          440 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4111          440 :             )),
    4112          440 :             pagestream_throttle_metrics: Arc::new(
    4113          440 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4114          440 :             ),
    4115          440 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4116          440 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4117          440 :             gc_block: Default::default(),
    4118          440 :             l0_flush_global_state,
    4119          440 :         }
    4120          440 :     }
    4121              : 
    4122              :     /// Locate and load config
    4123            0 :     pub(super) fn load_tenant_config(
    4124            0 :         conf: &'static PageServerConf,
    4125            0 :         tenant_shard_id: &TenantShardId,
    4126            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4127            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4128            0 : 
    4129            0 :         info!("loading tenant configuration from {config_path}");
    4130              : 
    4131              :         // load and parse file
    4132            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4133            0 :             match e.kind() {
    4134              :                 std::io::ErrorKind::NotFound => {
    4135              :                     // The config should almost always exist for a tenant directory:
    4136              :                     //  - When attaching a tenant, the config is the first thing we write
    4137              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4138              :                     //    before deleting contents.
    4139              :                     //
    4140              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4141              :                     // between creating directory and writing config.  Callers should handle that as if the
    4142              :                     // directory didn't exist.
    4143              : 
    4144            0 :                     LoadConfigError::NotFound(config_path)
    4145              :                 }
    4146              :                 _ => {
    4147              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4148              :                     // that we cannot cleanly recover
    4149            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4150              :                 }
    4151              :             }
    4152            0 :         })?;
    4153              : 
    4154            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4155            0 :     }
    4156              : 
    4157              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4158              :     pub(super) async fn persist_tenant_config(
    4159              :         conf: &'static PageServerConf,
    4160              :         tenant_shard_id: &TenantShardId,
    4161              :         location_conf: &LocationConf,
    4162              :     ) -> std::io::Result<()> {
    4163              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4164              : 
    4165              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4166              :     }
    4167              : 
    4168              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4169              :     pub(super) async fn persist_tenant_config_at(
    4170              :         tenant_shard_id: &TenantShardId,
    4171              :         config_path: &Utf8Path,
    4172              :         location_conf: &LocationConf,
    4173              :     ) -> std::io::Result<()> {
    4174              :         debug!("persisting tenantconf to {config_path}");
    4175              : 
    4176              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4177              : #  It is read in case of pageserver restart.
    4178              : "#
    4179              :         .to_string();
    4180              : 
    4181            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4182            0 :             Err(std::io::Error::new(
    4183            0 :                 std::io::ErrorKind::Other,
    4184            0 :                 "tenant-config-before-write",
    4185            0 :             ))
    4186            0 :         });
    4187              : 
    4188              :         // Convert the config to a toml file.
    4189              :         conf_content +=
    4190              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4191              : 
    4192              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4193              : 
    4194              :         let conf_content = conf_content.into_bytes();
    4195              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4196              :     }
    4197              : 
    4198              :     //
    4199              :     // How garbage collection works:
    4200              :     //
    4201              :     //                    +--bar------------->
    4202              :     //                   /
    4203              :     //             +----+-----foo---------------->
    4204              :     //            /
    4205              :     // ----main--+-------------------------->
    4206              :     //                \
    4207              :     //                 +-----baz-------->
    4208              :     //
    4209              :     //
    4210              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4211              :     //    `gc_infos` are being refreshed
    4212              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4213              :     //    all the points where other timelines have been branched off.
    4214              :     //    We will refrain from removing page versions at those LSNs.
    4215              :     // 3. For each timeline, scan all layer files on the timeline.
    4216              :     //    Remove all files for which a newer file exists and which
    4217              :     //    don't cover any branch point LSNs.
    4218              :     //
    4219              :     // TODO:
    4220              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4221              :     //   don't need to keep that in the parent anymore. But currently
    4222              :     //   we do.
    4223            8 :     async fn gc_iteration_internal(
    4224            8 :         &self,
    4225            8 :         target_timeline_id: Option<TimelineId>,
    4226            8 :         horizon: u64,
    4227            8 :         pitr: Duration,
    4228            8 :         cancel: &CancellationToken,
    4229            8 :         ctx: &RequestContext,
    4230            8 :     ) -> Result<GcResult, GcError> {
    4231            8 :         let mut totals: GcResult = Default::default();
    4232            8 :         let now = Instant::now();
    4233              : 
    4234            8 :         let gc_timelines = self
    4235            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4236            8 :             .await?;
    4237              : 
    4238            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4239              : 
    4240              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4241            8 :         if !gc_timelines.is_empty() {
    4242            8 :             info!("{} timelines need GC", gc_timelines.len());
    4243              :         } else {
    4244            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4245              :         }
    4246              : 
    4247              :         // Perform GC for each timeline.
    4248              :         //
    4249              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4250              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4251              :         // with branch creation.
    4252              :         //
    4253              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4254              :         // creation task can run concurrently with timeline's GC iteration.
    4255           16 :         for timeline in gc_timelines {
    4256            8 :             if cancel.is_cancelled() {
    4257              :                 // We were requested to shut down. Stop and return with the progress we
    4258              :                 // made.
    4259            0 :                 break;
    4260            8 :             }
    4261            8 :             let result = match timeline.gc().await {
    4262              :                 Err(GcError::TimelineCancelled) => {
    4263            0 :                     if target_timeline_id.is_some() {
    4264              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4265            0 :                         return Err(GcError::TimelineCancelled);
    4266              :                     } else {
    4267              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4268              :                         // skip past this and proceed to try GC on other timelines.
    4269            0 :                         continue;
    4270              :                     }
    4271              :                 }
    4272            8 :                 r => r?,
    4273              :             };
    4274            8 :             totals += result;
    4275              :         }
    4276              : 
    4277            8 :         totals.elapsed = now.elapsed();
    4278            8 :         Ok(totals)
    4279            8 :     }
    4280              : 
    4281              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4282              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4283              :     /// [`Tenant::get_gc_horizon`].
    4284              :     ///
    4285              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4286            0 :     pub(crate) async fn refresh_gc_info(
    4287            0 :         &self,
    4288            0 :         cancel: &CancellationToken,
    4289            0 :         ctx: &RequestContext,
    4290            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4291            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4292            0 :         // might be that these configuration values get applied faster than what it was previously,
    4293            0 :         // since these were only read from the gc task.
    4294            0 :         let horizon = self.get_gc_horizon();
    4295            0 :         let pitr = self.get_pitr_interval();
    4296            0 : 
    4297            0 :         // refresh all timelines
    4298            0 :         let target_timeline_id = None;
    4299            0 : 
    4300            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4301            0 :             .await
    4302            0 :     }
    4303              : 
    4304              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4305              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4306              :     ///
    4307              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4308            0 :     fn initialize_gc_info(
    4309            0 :         &self,
    4310            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4311            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4312            0 :         restrict_to_timeline: Option<TimelineId>,
    4313            0 :     ) {
    4314            0 :         if restrict_to_timeline.is_none() {
    4315              :             // This function must be called before activation: after activation timeline create/delete operations
    4316              :             // might happen, and this function is not safe to run concurrently with those.
    4317            0 :             assert!(!self.is_active());
    4318            0 :         }
    4319              : 
    4320              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4321              :         // the branch point where it was created.
    4322            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4323            0 :             BTreeMap::new();
    4324            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4325            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4326            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4327            0 :                 ancestor_children.push((
    4328            0 :                     timeline_entry.get_ancestor_lsn(),
    4329            0 :                     *timeline_id,
    4330            0 :                     MaybeOffloaded::No,
    4331            0 :                 ));
    4332            0 :             }
    4333            0 :         });
    4334            0 :         timelines_offloaded
    4335            0 :             .iter()
    4336            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4337            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4338            0 :                     return;
    4339              :                 };
    4340            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4341            0 :                     return;
    4342              :                 };
    4343            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4344            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4345            0 :             });
    4346            0 : 
    4347            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4348            0 :         let horizon = self.get_gc_horizon();
    4349              : 
    4350              :         // Populate each timeline's GcInfo with information about its child branches
    4351            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4352            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4353              :         } else {
    4354            0 :             itertools::Either::Right(timelines.values())
    4355              :         };
    4356            0 :         for timeline in timelines_to_write {
    4357            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4358            0 :                 .remove(&timeline.timeline_id)
    4359            0 :                 .unwrap_or_default();
    4360            0 : 
    4361            0 :             branchpoints.sort_by_key(|b| b.0);
    4362            0 : 
    4363            0 :             let mut target = timeline.gc_info.write().unwrap();
    4364            0 : 
    4365            0 :             target.retain_lsns = branchpoints;
    4366            0 : 
    4367            0 :             let space_cutoff = timeline
    4368            0 :                 .get_last_record_lsn()
    4369            0 :                 .checked_sub(horizon)
    4370            0 :                 .unwrap_or(Lsn(0));
    4371            0 : 
    4372            0 :             target.cutoffs = GcCutoffs {
    4373            0 :                 space: space_cutoff,
    4374            0 :                 time: Lsn::INVALID,
    4375            0 :             };
    4376            0 :         }
    4377            0 :     }
    4378              : 
    4379            8 :     async fn refresh_gc_info_internal(
    4380            8 :         &self,
    4381            8 :         target_timeline_id: Option<TimelineId>,
    4382            8 :         horizon: u64,
    4383            8 :         pitr: Duration,
    4384            8 :         cancel: &CancellationToken,
    4385            8 :         ctx: &RequestContext,
    4386            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4387            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4388            8 :         // currently visible timelines.
    4389            8 :         let timelines = self
    4390            8 :             .timelines
    4391            8 :             .lock()
    4392            8 :             .unwrap()
    4393            8 :             .values()
    4394            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4395            8 :                 Some(target) => &tl.timeline_id == target,
    4396            0 :                 None => true,
    4397            8 :             })
    4398            8 :             .cloned()
    4399            8 :             .collect::<Vec<_>>();
    4400            8 : 
    4401            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4402              :             // We were to act on a particular timeline and it wasn't found
    4403            0 :             return Err(GcError::TimelineNotFound);
    4404            8 :         }
    4405            8 : 
    4406            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4407            8 :             HashMap::with_capacity(timelines.len());
    4408            8 : 
    4409            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4410            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4411            8 :         for timeline in timelines.iter() {
    4412            8 :             let cutoff = timeline
    4413            8 :                 .get_last_record_lsn()
    4414            8 :                 .checked_sub(horizon)
    4415            8 :                 .unwrap_or(Lsn(0));
    4416              : 
    4417            8 :             let cutoffs = timeline
    4418            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4419            8 :                 .await?;
    4420            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4421            8 :             assert!(old.is_none());
    4422              :         }
    4423              : 
    4424            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4425            0 :             return Err(GcError::TenantCancelled);
    4426            8 :         }
    4427              : 
    4428              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4429              :         // because that will stall branch creation.
    4430            8 :         let gc_cs = self.gc_cs.lock().await;
    4431              : 
    4432              :         // Ok, we now know all the branch points.
    4433              :         // Update the GC information for each timeline.
    4434            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4435           16 :         for timeline in timelines {
    4436              :             // We filtered the timeline list above
    4437            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4438            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4439            0 :             }
    4440              : 
    4441              :             {
    4442            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4443            8 : 
    4444            8 :                 // Cull any expired leases
    4445            8 :                 let now = SystemTime::now();
    4446           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4447            8 : 
    4448            8 :                 timeline
    4449            8 :                     .metrics
    4450            8 :                     .valid_lsn_lease_count_gauge
    4451            8 :                     .set(target.leases.len() as u64);
    4452              : 
    4453              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4454            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4455            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4456            0 :                         target.within_ancestor_pitr =
    4457            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4458            0 :                     }
    4459            8 :                 }
    4460              : 
    4461              :                 // Update metrics that depend on GC state
    4462            8 :                 timeline
    4463            8 :                     .metrics
    4464            8 :                     .archival_size
    4465            8 :                     .set(if target.within_ancestor_pitr {
    4466            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4467              :                     } else {
    4468            8 :                         0
    4469              :                     });
    4470            8 :                 timeline.metrics.pitr_history_size.set(
    4471            8 :                     timeline
    4472            8 :                         .get_last_record_lsn()
    4473            8 :                         .checked_sub(target.cutoffs.time)
    4474            8 :                         .unwrap_or(Lsn(0))
    4475            8 :                         .0,
    4476            8 :                 );
    4477              : 
    4478              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4479              :                 // - this timeline was created while we were finding cutoffs
    4480              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4481            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4482            8 :                     let original_cutoffs = target.cutoffs.clone();
    4483            8 :                     // GC cutoffs should never go back
    4484            8 :                     target.cutoffs = GcCutoffs {
    4485            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4486            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4487            8 :                     }
    4488            0 :                 }
    4489              :             }
    4490              : 
    4491            8 :             gc_timelines.push(timeline);
    4492              :         }
    4493            8 :         drop(gc_cs);
    4494            8 :         Ok(gc_timelines)
    4495            8 :     }
    4496              : 
    4497              :     /// A substitute for `branch_timeline` for use in unit tests.
    4498              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4499              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4500              :     /// timeline background tasks are launched, except the flush loop.
    4501              :     #[cfg(test)]
    4502          464 :     async fn branch_timeline_test(
    4503          464 :         self: &Arc<Self>,
    4504          464 :         src_timeline: &Arc<Timeline>,
    4505          464 :         dst_id: TimelineId,
    4506          464 :         ancestor_lsn: Option<Lsn>,
    4507          464 :         ctx: &RequestContext,
    4508          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4509          464 :         let tl = self
    4510          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4511          464 :             .await?
    4512          456 :             .into_timeline_for_test();
    4513          456 :         tl.set_state(TimelineState::Active);
    4514          456 :         Ok(tl)
    4515          464 :     }
    4516              : 
    4517              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4518              :     #[cfg(test)]
    4519              :     #[allow(clippy::too_many_arguments)]
    4520           12 :     pub async fn branch_timeline_test_with_layers(
    4521           12 :         self: &Arc<Self>,
    4522           12 :         src_timeline: &Arc<Timeline>,
    4523           12 :         dst_id: TimelineId,
    4524           12 :         ancestor_lsn: Option<Lsn>,
    4525           12 :         ctx: &RequestContext,
    4526           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4527           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4528           12 :         end_lsn: Lsn,
    4529           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4530              :         use checks::check_valid_layermap;
    4531              :         use itertools::Itertools;
    4532              : 
    4533           12 :         let tline = self
    4534           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4535           12 :             .await?;
    4536           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4537           12 :             ancestor_lsn
    4538              :         } else {
    4539            0 :             tline.get_last_record_lsn()
    4540              :         };
    4541           12 :         assert!(end_lsn >= ancestor_lsn);
    4542           12 :         tline.force_advance_lsn(end_lsn);
    4543           24 :         for deltas in delta_layer_desc {
    4544           12 :             tline
    4545           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4546           12 :                 .await?;
    4547              :         }
    4548           20 :         for (lsn, images) in image_layer_desc {
    4549            8 :             tline
    4550            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4551            8 :                 .await?;
    4552              :         }
    4553           12 :         let layer_names = tline
    4554           12 :             .layers
    4555           12 :             .read()
    4556           12 :             .await
    4557           12 :             .layer_map()
    4558           12 :             .unwrap()
    4559           12 :             .iter_historic_layers()
    4560           20 :             .map(|layer| layer.layer_name())
    4561           12 :             .collect_vec();
    4562           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4563            0 :             bail!("invalid layermap: {err}");
    4564           12 :         }
    4565           12 :         Ok(tline)
    4566           12 :     }
    4567              : 
    4568              :     /// Branch an existing timeline.
    4569            0 :     async fn branch_timeline(
    4570            0 :         self: &Arc<Self>,
    4571            0 :         src_timeline: &Arc<Timeline>,
    4572            0 :         dst_id: TimelineId,
    4573            0 :         start_lsn: Option<Lsn>,
    4574            0 :         ctx: &RequestContext,
    4575            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4576            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4577            0 :             .await
    4578            0 :     }
    4579              : 
    4580          464 :     async fn branch_timeline_impl(
    4581          464 :         self: &Arc<Self>,
    4582          464 :         src_timeline: &Arc<Timeline>,
    4583          464 :         dst_id: TimelineId,
    4584          464 :         start_lsn: Option<Lsn>,
    4585          464 :         _ctx: &RequestContext,
    4586          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4587          464 :         let src_id = src_timeline.timeline_id;
    4588              : 
    4589              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4590              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4591              :         // valid while we are creating the branch.
    4592          464 :         let _gc_cs = self.gc_cs.lock().await;
    4593              : 
    4594              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4595          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4596            4 :             let lsn = src_timeline.get_last_record_lsn();
    4597            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4598            4 :             lsn
    4599          464 :         });
    4600              : 
    4601              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4602          464 :         let timeline_create_guard = match self
    4603          464 :             .start_creating_timeline(
    4604          464 :                 dst_id,
    4605          464 :                 CreateTimelineIdempotency::Branch {
    4606          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4607          464 :                     ancestor_start_lsn: start_lsn,
    4608          464 :                 },
    4609          464 :             )
    4610          464 :             .await?
    4611              :         {
    4612          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4613            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4614            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4615              :             }
    4616              :         };
    4617              : 
    4618              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4619              :         // horizon on the source timeline
    4620              :         //
    4621              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4622              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4623              :         // planned GC cutoff in 'gc_info' is normally larger than
    4624              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4625              :         // changed the GC settings for the tenant to make the PITR window
    4626              :         // larger, but some of the data was already removed by an earlier GC
    4627              :         // iteration.
    4628              : 
    4629              :         // check against last actual 'latest_gc_cutoff' first
    4630          464 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4631          464 :         src_timeline
    4632          464 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4633          464 :             .context(format!(
    4634          464 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4635          464 :                 *latest_gc_cutoff_lsn,
    4636          464 :             ))
    4637          464 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4638              : 
    4639              :         // and then the planned GC cutoff
    4640              :         {
    4641          456 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4642          456 :             let cutoff = gc_info.min_cutoff();
    4643          456 :             if start_lsn < cutoff {
    4644            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4645            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4646            0 :                 )));
    4647          456 :             }
    4648          456 :         }
    4649          456 : 
    4650          456 :         //
    4651          456 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4652          456 :         // so that GC cannot advance the GC cutoff until we are finished.
    4653          456 :         // Proceed with the branch creation.
    4654          456 :         //
    4655          456 : 
    4656          456 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4657          456 :         // the timeline was branched at the current end of the source timeline.
    4658          456 :         let RecordLsn {
    4659          456 :             last: src_last,
    4660          456 :             prev: src_prev,
    4661          456 :         } = src_timeline.get_last_record_rlsn();
    4662          456 :         let dst_prev = if src_last == start_lsn {
    4663          432 :             Some(src_prev)
    4664              :         } else {
    4665           24 :             None
    4666              :         };
    4667              : 
    4668              :         // Create the metadata file, noting the ancestor of the new timeline.
    4669              :         // There is initially no data in it, but all the read-calls know to look
    4670              :         // into the ancestor.
    4671          456 :         let metadata = TimelineMetadata::new(
    4672          456 :             start_lsn,
    4673          456 :             dst_prev,
    4674          456 :             Some(src_id),
    4675          456 :             start_lsn,
    4676          456 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4677          456 :             src_timeline.initdb_lsn,
    4678          456 :             src_timeline.pg_version,
    4679          456 :         );
    4680              : 
    4681          456 :         let uninitialized_timeline = self
    4682          456 :             .prepare_new_timeline(
    4683          456 :                 dst_id,
    4684          456 :                 &metadata,
    4685          456 :                 timeline_create_guard,
    4686          456 :                 start_lsn + 1,
    4687          456 :                 Some(Arc::clone(src_timeline)),
    4688          456 :             )
    4689          456 :             .await?;
    4690              : 
    4691          456 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4692              : 
    4693              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4694              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4695              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4696              :         // could get incorrect information and remove more layers, than needed.
    4697              :         // See also https://github.com/neondatabase/neon/issues/3865
    4698          456 :         new_timeline
    4699          456 :             .remote_client
    4700          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4701          456 :             .context("branch initial metadata upload")?;
    4702              : 
    4703              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4704              : 
    4705          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4706          464 :     }
    4707              : 
    4708              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4709              :     #[cfg(test)]
    4710              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4711              :     pub(crate) async fn bootstrap_timeline_test(
    4712              :         self: &Arc<Self>,
    4713              :         timeline_id: TimelineId,
    4714              :         pg_version: u32,
    4715              :         load_existing_initdb: Option<TimelineId>,
    4716              :         ctx: &RequestContext,
    4717              :     ) -> anyhow::Result<Arc<Timeline>> {
    4718              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4719              :             .await
    4720              :             .map_err(anyhow::Error::new)
    4721            4 :             .map(|r| r.into_timeline_for_test())
    4722              :     }
    4723              : 
    4724              :     /// Get exclusive access to the timeline ID for creation.
    4725              :     ///
    4726              :     /// Timeline-creating code paths must use this function before making changes
    4727              :     /// to in-memory or persistent state.
    4728              :     ///
    4729              :     /// The `state` parameter is a description of the timeline creation operation
    4730              :     /// we intend to perform.
    4731              :     /// If the timeline was already created in the meantime, we check whether this
    4732              :     /// request conflicts or is idempotent , based on `state`.
    4733          892 :     async fn start_creating_timeline(
    4734          892 :         self: &Arc<Self>,
    4735          892 :         new_timeline_id: TimelineId,
    4736          892 :         idempotency: CreateTimelineIdempotency,
    4737          892 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4738          892 :         let allow_offloaded = false;
    4739          892 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4740          888 :             Ok(create_guard) => {
    4741          888 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4742          888 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4743              :             }
    4744            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4745              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4746              :                 // Creation is in progress, we cannot create it again, and we cannot
    4747              :                 // check if this request matches the existing one, so caller must try
    4748              :                 // again later.
    4749            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4750              :             }
    4751            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4752              :             Err(TimelineExclusionError::AlreadyExists {
    4753            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4754            0 :                 ..
    4755            0 :             }) => {
    4756            0 :                 info!("timeline already exists but is offloaded");
    4757            0 :                 Err(CreateTimelineError::Conflict)
    4758              :             }
    4759              :             Err(TimelineExclusionError::AlreadyExists {
    4760            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4761            4 :                 arg,
    4762            4 :             }) => {
    4763            4 :                 {
    4764            4 :                     let existing = &existing.create_idempotency;
    4765            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4766            4 :                     debug!("timeline already exists");
    4767              : 
    4768            4 :                     match (existing, &arg) {
    4769              :                         // FailWithConflict => no idempotency check
    4770              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4771              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4772            4 :                             warn!("timeline already exists, failing request");
    4773            4 :                             return Err(CreateTimelineError::Conflict);
    4774              :                         }
    4775              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4776            0 :                         (x, y) if x == y => {
    4777            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4778              :                             // fallthrough
    4779              :                         }
    4780              :                         (_, _) => {
    4781            0 :                             warn!("idempotency conflict, failing request");
    4782            0 :                             return Err(CreateTimelineError::Conflict);
    4783              :                         }
    4784              :                     }
    4785              :                 }
    4786              : 
    4787            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4788              :             }
    4789              :         }
    4790          892 :     }
    4791              : 
    4792            0 :     async fn upload_initdb(
    4793            0 :         &self,
    4794            0 :         timelines_path: &Utf8PathBuf,
    4795            0 :         pgdata_path: &Utf8PathBuf,
    4796            0 :         timeline_id: &TimelineId,
    4797            0 :     ) -> anyhow::Result<()> {
    4798            0 :         let temp_path = timelines_path.join(format!(
    4799            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4800            0 :         ));
    4801            0 : 
    4802            0 :         scopeguard::defer! {
    4803            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4804            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4805            0 :             }
    4806            0 :         }
    4807              : 
    4808            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4809              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4810            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4811            0 :             warn!(
    4812            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4813              :             );
    4814            0 :         }
    4815              : 
    4816            0 :         pausable_failpoint!("before-initdb-upload");
    4817              : 
    4818            0 :         backoff::retry(
    4819            0 :             || async {
    4820            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4821            0 :                     &self.remote_storage,
    4822            0 :                     &self.tenant_shard_id.tenant_id,
    4823            0 :                     timeline_id,
    4824            0 :                     pgdata_zstd.try_clone().await?,
    4825            0 :                     tar_zst_size,
    4826            0 :                     &self.cancel,
    4827            0 :                 )
    4828            0 :                 .await
    4829            0 :             },
    4830            0 :             |_| false,
    4831            0 :             3,
    4832            0 :             u32::MAX,
    4833            0 :             "persist_initdb_tar_zst",
    4834            0 :             &self.cancel,
    4835            0 :         )
    4836            0 :         .await
    4837            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4838            0 :         .and_then(|x| x)
    4839            0 :     }
    4840              : 
    4841              :     /// - run initdb to init temporary instance and get bootstrap data
    4842              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4843            4 :     async fn bootstrap_timeline(
    4844            4 :         self: &Arc<Self>,
    4845            4 :         timeline_id: TimelineId,
    4846            4 :         pg_version: u32,
    4847            4 :         load_existing_initdb: Option<TimelineId>,
    4848            4 :         ctx: &RequestContext,
    4849            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4850            4 :         let timeline_create_guard = match self
    4851            4 :             .start_creating_timeline(
    4852            4 :                 timeline_id,
    4853            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4854            4 :             )
    4855            4 :             .await?
    4856              :         {
    4857            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4858            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4859            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4860              :             }
    4861              :         };
    4862              : 
    4863              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4864              :         // temporary directory for basebackup files for the given timeline.
    4865              : 
    4866            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4867            4 :         let pgdata_path = path_with_suffix_extension(
    4868            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4869            4 :             TEMP_FILE_SUFFIX,
    4870            4 :         );
    4871            4 : 
    4872            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4873            4 :         // we won't race with other creations or existent timelines with the same path.
    4874            4 :         if pgdata_path.exists() {
    4875            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4876            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4877            0 :             })?;
    4878            4 :         }
    4879              : 
    4880              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4881            4 :         scopeguard::defer! {
    4882            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4883            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4884            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4885            4 :             }
    4886            4 :         }
    4887            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4888            4 :             if existing_initdb_timeline_id != timeline_id {
    4889            0 :                 let source_path = &remote_initdb_archive_path(
    4890            0 :                     &self.tenant_shard_id.tenant_id,
    4891            0 :                     &existing_initdb_timeline_id,
    4892            0 :                 );
    4893            0 :                 let dest_path =
    4894            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4895            0 : 
    4896            0 :                 // if this fails, it will get retried by retried control plane requests
    4897            0 :                 self.remote_storage
    4898            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4899            0 :                     .await
    4900            0 :                     .context("copy initdb tar")?;
    4901            4 :             }
    4902            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4903            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4904            4 :                     self.conf,
    4905            4 :                     &self.remote_storage,
    4906            4 :                     &self.tenant_shard_id,
    4907            4 :                     &existing_initdb_timeline_id,
    4908            4 :                     &self.cancel,
    4909            4 :                 )
    4910            4 :                 .await
    4911            4 :                 .context("download initdb tar")?;
    4912              : 
    4913            4 :             scopeguard::defer! {
    4914            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4915            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4916            4 :                 }
    4917            4 :             }
    4918            4 : 
    4919            4 :             let buf_read =
    4920            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4921            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    4922            4 :                 .await
    4923            4 :                 .context("extract initdb tar")?;
    4924              :         } else {
    4925              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4926            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4927            0 :                 .await
    4928            0 :                 .context("run initdb")?;
    4929              : 
    4930              :             // Upload the created data dir to S3
    4931            0 :             if self.tenant_shard_id().is_shard_zero() {
    4932            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4933            0 :                     .await?;
    4934            0 :             }
    4935              :         }
    4936            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4937            4 : 
    4938            4 :         // Import the contents of the data directory at the initial checkpoint
    4939            4 :         // LSN, and any WAL after that.
    4940            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4941            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4942            4 :         let new_metadata = TimelineMetadata::new(
    4943            4 :             Lsn(0),
    4944            4 :             None,
    4945            4 :             None,
    4946            4 :             Lsn(0),
    4947            4 :             pgdata_lsn,
    4948            4 :             pgdata_lsn,
    4949            4 :             pg_version,
    4950            4 :         );
    4951            4 :         let raw_timeline = self
    4952            4 :             .prepare_new_timeline(
    4953            4 :                 timeline_id,
    4954            4 :                 &new_metadata,
    4955            4 :                 timeline_create_guard,
    4956            4 :                 pgdata_lsn,
    4957            4 :                 None,
    4958            4 :             )
    4959            4 :             .await?;
    4960              : 
    4961            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4962            4 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4963              : 
    4964              :         // Flush the new layer files to disk, before we make the timeline as available to
    4965              :         // the outside world.
    4966              :         //
    4967              :         // Flush loop needs to be spawned in order to be able to flush.
    4968            4 :         unfinished_timeline.maybe_spawn_flush_loop();
    4969            4 : 
    4970            4 :         import_datadir::import_timeline_from_postgres_datadir(
    4971            4 :             unfinished_timeline,
    4972            4 :             &pgdata_path,
    4973            4 :             pgdata_lsn,
    4974            4 :             ctx,
    4975            4 :         )
    4976            4 :         .await
    4977            4 :         .with_context(|| {
    4978            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    4979            4 :         })?;
    4980              : 
    4981            4 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    4982            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    4983            0 :                 "failpoint before-checkpoint-new-timeline"
    4984            0 :             )))
    4985            4 :         });
    4986              : 
    4987            4 :         unfinished_timeline
    4988            4 :             .freeze_and_flush()
    4989            4 :             .await
    4990            4 :             .with_context(|| {
    4991            0 :                 format!(
    4992            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    4993            0 :                 )
    4994            4 :             })?;
    4995              : 
    4996              :         // All done!
    4997            4 :         let timeline = raw_timeline.finish_creation()?;
    4998              : 
    4999              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5000              : 
    5001            4 :         Ok(CreateTimelineResult::Created(timeline))
    5002            4 :     }
    5003              : 
    5004          880 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5005          880 :         RemoteTimelineClient::new(
    5006          880 :             self.remote_storage.clone(),
    5007          880 :             self.deletion_queue_client.clone(),
    5008          880 :             self.conf,
    5009          880 :             self.tenant_shard_id,
    5010          880 :             timeline_id,
    5011          880 :             self.generation,
    5012          880 :             &self.tenant_conf.load().location,
    5013          880 :         )
    5014          880 :     }
    5015              : 
    5016              :     /// Call this before constructing a timeline, to build its required structures
    5017          880 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5018          880 :         TimelineResources {
    5019          880 :             remote_client: self.build_timeline_remote_client(timeline_id),
    5020          880 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5021          880 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5022          880 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5023          880 :         }
    5024          880 :     }
    5025              : 
    5026              :     /// Creates intermediate timeline structure and its files.
    5027              :     ///
    5028              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5029              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5030              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5031          880 :     async fn prepare_new_timeline<'a>(
    5032          880 :         &'a self,
    5033          880 :         new_timeline_id: TimelineId,
    5034          880 :         new_metadata: &TimelineMetadata,
    5035          880 :         create_guard: TimelineCreateGuard,
    5036          880 :         start_lsn: Lsn,
    5037          880 :         ancestor: Option<Arc<Timeline>>,
    5038          880 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5039          880 :         let tenant_shard_id = self.tenant_shard_id;
    5040          880 : 
    5041          880 :         let resources = self.build_timeline_resources(new_timeline_id);
    5042          880 :         resources
    5043          880 :             .remote_client
    5044          880 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5045              : 
    5046          880 :         let timeline_struct = self
    5047          880 :             .create_timeline_struct(
    5048          880 :                 new_timeline_id,
    5049          880 :                 new_metadata,
    5050          880 :                 ancestor,
    5051          880 :                 resources,
    5052          880 :                 CreateTimelineCause::Load,
    5053          880 :                 create_guard.idempotency.clone(),
    5054          880 :             )
    5055          880 :             .context("Failed to create timeline data structure")?;
    5056              : 
    5057          880 :         timeline_struct.init_empty_layer_map(start_lsn);
    5058              : 
    5059          880 :         if let Err(e) = self
    5060          880 :             .create_timeline_files(&create_guard.timeline_path)
    5061          880 :             .await
    5062              :         {
    5063            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5064            0 :             cleanup_timeline_directory(create_guard);
    5065            0 :             return Err(e);
    5066          880 :         }
    5067          880 : 
    5068          880 :         debug!(
    5069            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5070              :         );
    5071              : 
    5072          880 :         Ok(UninitializedTimeline::new(
    5073          880 :             self,
    5074          880 :             new_timeline_id,
    5075          880 :             Some((timeline_struct, create_guard)),
    5076          880 :         ))
    5077          880 :     }
    5078              : 
    5079          880 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5080          880 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5081              : 
    5082          880 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5083            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5084          880 :         });
    5085              : 
    5086          880 :         Ok(())
    5087          880 :     }
    5088              : 
    5089              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5090              :     /// concurrent attempts to create the same timeline.
    5091              :     ///
    5092              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5093              :     /// offloaded timelines or not.
    5094          892 :     fn create_timeline_create_guard(
    5095          892 :         self: &Arc<Self>,
    5096          892 :         timeline_id: TimelineId,
    5097          892 :         idempotency: CreateTimelineIdempotency,
    5098          892 :         allow_offloaded: bool,
    5099          892 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5100          892 :         let tenant_shard_id = self.tenant_shard_id;
    5101          892 : 
    5102          892 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5103              : 
    5104          892 :         let create_guard = TimelineCreateGuard::new(
    5105          892 :             self,
    5106          892 :             timeline_id,
    5107          892 :             timeline_path.clone(),
    5108          892 :             idempotency,
    5109          892 :             allow_offloaded,
    5110          892 :         )?;
    5111              : 
    5112              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5113              :         // for creation.
    5114              :         // A timeline directory should never exist on disk already:
    5115              :         // - a previous failed creation would have cleaned up after itself
    5116              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5117              :         //
    5118              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5119              :         // this error may indicate a bug in cleanup on failed creations.
    5120          888 :         if timeline_path.exists() {
    5121            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5122            0 :                 "Timeline directory already exists! This is a bug."
    5123            0 :             )));
    5124          888 :         }
    5125          888 : 
    5126          888 :         Ok(create_guard)
    5127          892 :     }
    5128              : 
    5129              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5130              :     ///
    5131              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5132              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5133              :     pub async fn gather_size_inputs(
    5134              :         &self,
    5135              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5136              :         // (only if it is shorter than the real cutoff).
    5137              :         max_retention_period: Option<u64>,
    5138              :         cause: LogicalSizeCalculationCause,
    5139              :         cancel: &CancellationToken,
    5140              :         ctx: &RequestContext,
    5141              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5142              :         let logical_sizes_at_once = self
    5143              :             .conf
    5144              :             .concurrent_tenant_size_logical_size_queries
    5145              :             .inner();
    5146              : 
    5147              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5148              :         //
    5149              :         // But the only case where we need to run multiple of these at once is when we
    5150              :         // request a size for a tenant manually via API, while another background calculation
    5151              :         // is in progress (which is not a common case).
    5152              :         //
    5153              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5154              :         let mut shared_cache = tokio::select! {
    5155              :             locked = self.cached_logical_sizes.lock() => locked,
    5156              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5157              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5158              :         };
    5159              : 
    5160              :         size::gather_inputs(
    5161              :             self,
    5162              :             logical_sizes_at_once,
    5163              :             max_retention_period,
    5164              :             &mut shared_cache,
    5165              :             cause,
    5166              :             cancel,
    5167              :             ctx,
    5168              :         )
    5169              :         .await
    5170              :     }
    5171              : 
    5172              :     /// Calculate synthetic tenant size and cache the result.
    5173              :     /// This is periodically called by background worker.
    5174              :     /// result is cached in tenant struct
    5175              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5176              :     pub async fn calculate_synthetic_size(
    5177              :         &self,
    5178              :         cause: LogicalSizeCalculationCause,
    5179              :         cancel: &CancellationToken,
    5180              :         ctx: &RequestContext,
    5181              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5182              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5183              : 
    5184              :         let size = inputs.calculate();
    5185              : 
    5186              :         self.set_cached_synthetic_size(size);
    5187              : 
    5188              :         Ok(size)
    5189              :     }
    5190              : 
    5191              :     /// Cache given synthetic size and update the metric value
    5192            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5193            0 :         self.cached_synthetic_tenant_size
    5194            0 :             .store(size, Ordering::Relaxed);
    5195            0 : 
    5196            0 :         // Only shard zero should be calculating synthetic sizes
    5197            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5198              : 
    5199            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5200            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5201            0 :             .unwrap()
    5202            0 :             .set(size);
    5203            0 :     }
    5204              : 
    5205            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5206            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5207            0 :     }
    5208              : 
    5209              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5210              :     ///
    5211              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5212              :     /// from an external API handler.
    5213              :     ///
    5214              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5215              :     /// still bounded by tenant/timeline shutdown.
    5216              :     #[tracing::instrument(skip_all)]
    5217              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5218              :         let timelines = self.timelines.lock().unwrap().clone();
    5219              : 
    5220            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5221            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5222            0 :             timeline.freeze_and_flush().await?;
    5223            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5224            0 :             timeline.remote_client.wait_completion().await?;
    5225              : 
    5226            0 :             Ok(())
    5227            0 :         }
    5228              : 
    5229              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5230              :         // aborted when this function's future is cancelled: they should stay alive
    5231              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5232              :         // before Timeline shutdown completes.
    5233              :         let mut results = FuturesUnordered::new();
    5234              : 
    5235              :         for (_timeline_id, timeline) in timelines {
    5236              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5237              :             // means that if this function's future is cancelled, the Timeline shutdown
    5238              :             // will still wait for any I/O in here to complete.
    5239              :             let Ok(gate) = timeline.gate.enter() else {
    5240              :                 continue;
    5241              :             };
    5242            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5243              :             results.push(jh);
    5244              :         }
    5245              : 
    5246              :         while let Some(r) = results.next().await {
    5247              :             if let Err(e) = r {
    5248              :                 if !e.is_cancelled() && !e.is_panic() {
    5249              :                     tracing::error!("unexpected join error: {e:?}");
    5250              :                 }
    5251              :             }
    5252              :         }
    5253              : 
    5254              :         // The flushes we did above were just writes, but the Tenant might have had
    5255              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5256              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5257              :         // because it's typically a no-op.
    5258              :         match self.deletion_queue_client.flush_execute().await {
    5259              :             Ok(_) => {}
    5260              :             Err(DeletionQueueError::ShuttingDown) => {}
    5261              :         }
    5262              : 
    5263              :         Ok(())
    5264              :     }
    5265              : 
    5266            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5267            0 :         self.tenant_conf.load().tenant_conf.clone()
    5268            0 :     }
    5269              : 
    5270              :     /// How much local storage would this tenant like to have?  It can cope with
    5271              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5272              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5273              :     /// by keeping important things on local disk.
    5274              :     ///
    5275              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5276              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5277              :     /// actually use more than they report here.
    5278            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5279            0 :         let timelines = self.timelines.lock().unwrap();
    5280            0 : 
    5281            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5282            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5283            0 :         // of them is used actively enough to occupy space on disk.
    5284            0 :         timelines
    5285            0 :             .values()
    5286            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5287            0 :             .max()
    5288            0 :             .unwrap_or(0)
    5289            0 :     }
    5290              : 
    5291              :     /// Serialize and write the latest TenantManifest to remote storage.
    5292            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5293              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5294              :         // must be loaded while holding this lock. This makes it safe to call this function
    5295              :         // from anywhere without worrying about colliding updates.
    5296            4 :         let mut guard = tokio::select! {
    5297            4 :             g = self.tenant_manifest_upload.lock() => {
    5298            4 :                 g
    5299              :             },
    5300            4 :             _ = self.cancel.cancelled() => {
    5301            0 :                 return Err(TenantManifestError::Cancelled);
    5302              :             }
    5303              :         };
    5304              : 
    5305            4 :         let manifest = self.build_tenant_manifest();
    5306            4 :         if Some(&manifest) == (*guard).as_ref() {
    5307              :             // Optimisation: skip uploads that don't change anything.
    5308            0 :             return Ok(());
    5309            4 :         }
    5310            4 : 
    5311            4 :         upload_tenant_manifest(
    5312            4 :             &self.remote_storage,
    5313            4 :             &self.tenant_shard_id,
    5314            4 :             self.generation,
    5315            4 :             &manifest,
    5316            4 :             &self.cancel,
    5317            4 :         )
    5318            4 :         .await
    5319            4 :         .map_err(|e| {
    5320            0 :             if self.cancel.is_cancelled() {
    5321            0 :                 TenantManifestError::Cancelled
    5322              :             } else {
    5323            0 :                 TenantManifestError::RemoteStorage(e)
    5324              :             }
    5325            4 :         })?;
    5326              : 
    5327              :         // Store the successfully uploaded manifest, so that future callers can avoid
    5328              :         // re-uploading the same thing.
    5329            4 :         *guard = Some(manifest);
    5330            4 : 
    5331            4 :         Ok(())
    5332            4 :     }
    5333              : }
    5334              : 
    5335              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5336              : /// to get bootstrap data for timeline initialization.
    5337            0 : async fn run_initdb(
    5338            0 :     conf: &'static PageServerConf,
    5339            0 :     initdb_target_dir: &Utf8Path,
    5340            0 :     pg_version: u32,
    5341            0 :     cancel: &CancellationToken,
    5342            0 : ) -> Result<(), InitdbError> {
    5343            0 :     let initdb_bin_path = conf
    5344            0 :         .pg_bin_dir(pg_version)
    5345            0 :         .map_err(InitdbError::Other)?
    5346            0 :         .join("initdb");
    5347            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5348            0 :     info!(
    5349            0 :         "running {} in {}, libdir: {}",
    5350              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5351              :     );
    5352              : 
    5353            0 :     let _permit = {
    5354            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5355            0 :         INIT_DB_SEMAPHORE.acquire().await
    5356              :     };
    5357              : 
    5358            0 :     CONCURRENT_INITDBS.inc();
    5359            0 :     scopeguard::defer! {
    5360            0 :         CONCURRENT_INITDBS.dec();
    5361            0 :     }
    5362            0 : 
    5363            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5364            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5365            0 :         superuser: &conf.superuser,
    5366            0 :         locale: &conf.locale,
    5367            0 :         initdb_bin: &initdb_bin_path,
    5368            0 :         pg_version,
    5369            0 :         library_search_path: &initdb_lib_dir,
    5370            0 :         pgdata: initdb_target_dir,
    5371            0 :     })
    5372            0 :     .await
    5373            0 :     .map_err(InitdbError::Inner);
    5374            0 : 
    5375            0 :     // This isn't true cancellation support, see above. Still return an error to
    5376            0 :     // excercise the cancellation code path.
    5377            0 :     if cancel.is_cancelled() {
    5378            0 :         return Err(InitdbError::Cancelled);
    5379            0 :     }
    5380            0 : 
    5381            0 :     res
    5382            0 : }
    5383              : 
    5384              : /// Dump contents of a layer file to stdout.
    5385            0 : pub async fn dump_layerfile_from_path(
    5386            0 :     path: &Utf8Path,
    5387            0 :     verbose: bool,
    5388            0 :     ctx: &RequestContext,
    5389            0 : ) -> anyhow::Result<()> {
    5390              :     use std::os::unix::fs::FileExt;
    5391              : 
    5392              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5393              :     // file.
    5394            0 :     let file = File::open(path)?;
    5395            0 :     let mut header_buf = [0u8; 2];
    5396            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5397              : 
    5398            0 :     match u16::from_be_bytes(header_buf) {
    5399              :         crate::IMAGE_FILE_MAGIC => {
    5400            0 :             ImageLayer::new_for_path(path, file)?
    5401            0 :                 .dump(verbose, ctx)
    5402            0 :                 .await?
    5403              :         }
    5404              :         crate::DELTA_FILE_MAGIC => {
    5405            0 :             DeltaLayer::new_for_path(path, file)?
    5406            0 :                 .dump(verbose, ctx)
    5407            0 :                 .await?
    5408              :         }
    5409            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5410              :     }
    5411              : 
    5412            0 :     Ok(())
    5413            0 : }
    5414              : 
    5415              : #[cfg(test)]
    5416              : pub(crate) mod harness {
    5417              :     use bytes::{Bytes, BytesMut};
    5418              :     use once_cell::sync::OnceCell;
    5419              :     use pageserver_api::models::ShardParameters;
    5420              :     use pageserver_api::shard::ShardIndex;
    5421              :     use utils::logging;
    5422              : 
    5423              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5424              :     use crate::l0_flush::L0FlushConfig;
    5425              :     use crate::walredo::apply_neon;
    5426              :     use pageserver_api::key::Key;
    5427              :     use pageserver_api::record::NeonWalRecord;
    5428              : 
    5429              :     use super::*;
    5430              :     use hex_literal::hex;
    5431              :     use utils::id::TenantId;
    5432              : 
    5433              :     pub const TIMELINE_ID: TimelineId =
    5434              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5435              :     pub const NEW_TIMELINE_ID: TimelineId =
    5436              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5437              : 
    5438              :     /// Convenience function to create a page image with given string as the only content
    5439     10057565 :     pub fn test_img(s: &str) -> Bytes {
    5440     10057565 :         let mut buf = BytesMut::new();
    5441     10057565 :         buf.extend_from_slice(s.as_bytes());
    5442     10057565 :         buf.resize(64, 0);
    5443     10057565 : 
    5444     10057565 :         buf.freeze()
    5445     10057565 :     }
    5446              : 
    5447              :     impl From<TenantConf> for TenantConfOpt {
    5448          440 :         fn from(tenant_conf: TenantConf) -> Self {
    5449          440 :             Self {
    5450          440 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5451          440 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5452          440 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5453          440 :                 compaction_period: Some(tenant_conf.compaction_period),
    5454          440 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5455          440 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5456          440 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5457          440 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5458          440 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5459          440 :                 gc_period: Some(tenant_conf.gc_period),
    5460          440 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5461          440 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5462          440 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5463          440 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5464          440 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5465          440 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5466          440 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5467          440 :                 evictions_low_residence_duration_metric_threshold: Some(
    5468          440 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5469          440 :                 ),
    5470          440 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5471          440 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5472          440 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5473          440 :                 image_layer_creation_check_threshold: Some(
    5474          440 :                     tenant_conf.image_layer_creation_check_threshold,
    5475          440 :                 ),
    5476          440 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5477          440 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5478          440 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5479          440 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5480          440 :                 rel_size_v2_enabled: tenant_conf.rel_size_v2_enabled,
    5481          440 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5482          440 :                 gc_compaction_initial_threshold_kb: Some(
    5483          440 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5484          440 :                 ),
    5485          440 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5486          440 :             }
    5487          440 :         }
    5488              :     }
    5489              : 
    5490              :     pub struct TenantHarness {
    5491              :         pub conf: &'static PageServerConf,
    5492              :         pub tenant_conf: TenantConf,
    5493              :         pub tenant_shard_id: TenantShardId,
    5494              :         pub generation: Generation,
    5495              :         pub shard: ShardIndex,
    5496              :         pub remote_storage: GenericRemoteStorage,
    5497              :         pub remote_fs_dir: Utf8PathBuf,
    5498              :         pub deletion_queue: MockDeletionQueue,
    5499              :     }
    5500              : 
    5501              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5502              : 
    5503          488 :     pub(crate) fn setup_logging() {
    5504          488 :         LOG_HANDLE.get_or_init(|| {
    5505          464 :             logging::init(
    5506          464 :                 logging::LogFormat::Test,
    5507          464 :                 // enable it in case the tests exercise code paths that use
    5508          464 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5509          464 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5510          464 :                 logging::Output::Stdout,
    5511          464 :             )
    5512          464 :             .expect("Failed to init test logging")
    5513          488 :         });
    5514          488 :     }
    5515              : 
    5516              :     impl TenantHarness {
    5517          440 :         pub async fn create_custom(
    5518          440 :             test_name: &'static str,
    5519          440 :             tenant_conf: TenantConf,
    5520          440 :             tenant_id: TenantId,
    5521          440 :             shard_identity: ShardIdentity,
    5522          440 :             generation: Generation,
    5523          440 :         ) -> anyhow::Result<Self> {
    5524          440 :             setup_logging();
    5525          440 : 
    5526          440 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5527          440 :             let _ = fs::remove_dir_all(&repo_dir);
    5528          440 :             fs::create_dir_all(&repo_dir)?;
    5529              : 
    5530          440 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5531          440 :             // Make a static copy of the config. This can never be free'd, but that's
    5532          440 :             // OK in a test.
    5533          440 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5534          440 : 
    5535          440 :             let shard = shard_identity.shard_index();
    5536          440 :             let tenant_shard_id = TenantShardId {
    5537          440 :                 tenant_id,
    5538          440 :                 shard_number: shard.shard_number,
    5539          440 :                 shard_count: shard.shard_count,
    5540          440 :             };
    5541          440 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5542          440 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5543              : 
    5544              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5545          440 :             let remote_fs_dir = conf.workdir.join("localfs");
    5546          440 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5547          440 :             let config = RemoteStorageConfig {
    5548          440 :                 storage: RemoteStorageKind::LocalFs {
    5549          440 :                     local_path: remote_fs_dir.clone(),
    5550          440 :                 },
    5551          440 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5552          440 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5553          440 :             };
    5554          440 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5555          440 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5556          440 : 
    5557          440 :             Ok(Self {
    5558          440 :                 conf,
    5559          440 :                 tenant_conf,
    5560          440 :                 tenant_shard_id,
    5561          440 :                 generation,
    5562          440 :                 shard,
    5563          440 :                 remote_storage,
    5564          440 :                 remote_fs_dir,
    5565          440 :                 deletion_queue,
    5566          440 :             })
    5567          440 :         }
    5568              : 
    5569          416 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5570          416 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5571          416 :             // The tests perform them manually if needed.
    5572          416 :             let tenant_conf = TenantConf {
    5573          416 :                 gc_period: Duration::ZERO,
    5574          416 :                 compaction_period: Duration::ZERO,
    5575          416 :                 ..TenantConf::default()
    5576          416 :             };
    5577          416 :             let tenant_id = TenantId::generate();
    5578          416 :             let shard = ShardIdentity::unsharded();
    5579          416 :             Self::create_custom(
    5580          416 :                 test_name,
    5581          416 :                 tenant_conf,
    5582          416 :                 tenant_id,
    5583          416 :                 shard,
    5584          416 :                 Generation::new(0xdeadbeef),
    5585          416 :             )
    5586          416 :             .await
    5587          416 :         }
    5588              : 
    5589           40 :         pub fn span(&self) -> tracing::Span {
    5590           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5591           40 :         }
    5592              : 
    5593          440 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5594          440 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5595          440 :             (
    5596          440 :                 self.do_try_load(&ctx)
    5597          440 :                     .await
    5598          440 :                     .expect("failed to load test tenant"),
    5599          440 :                 ctx,
    5600          440 :             )
    5601          440 :         }
    5602              : 
    5603              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5604              :         pub(crate) async fn do_try_load(
    5605              :             &self,
    5606              :             ctx: &RequestContext,
    5607              :         ) -> anyhow::Result<Arc<Tenant>> {
    5608              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5609              : 
    5610              :             let tenant = Arc::new(Tenant::new(
    5611              :                 TenantState::Attaching,
    5612              :                 self.conf,
    5613              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5614              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5615              :                     self.generation,
    5616              :                     &ShardParameters::default(),
    5617              :                 ))
    5618              :                 .unwrap(),
    5619              :                 // This is a legacy/test code path: sharding isn't supported here.
    5620              :                 ShardIdentity::unsharded(),
    5621              :                 Some(walredo_mgr),
    5622              :                 self.tenant_shard_id,
    5623              :                 self.remote_storage.clone(),
    5624              :                 self.deletion_queue.new_client(),
    5625              :                 // TODO: ideally we should run all unit tests with both configs
    5626              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5627              :             ));
    5628              : 
    5629              :             let preload = tenant
    5630              :                 .preload(&self.remote_storage, CancellationToken::new())
    5631              :                 .await?;
    5632              :             tenant.attach(Some(preload), ctx).await?;
    5633              : 
    5634              :             tenant.state.send_replace(TenantState::Active);
    5635              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5636              :                 timeline.set_state(TimelineState::Active);
    5637              :             }
    5638              :             Ok(tenant)
    5639              :         }
    5640              : 
    5641            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5642            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5643            4 :         }
    5644              :     }
    5645              : 
    5646              :     // Mock WAL redo manager that doesn't do much
    5647              :     pub(crate) struct TestRedoManager;
    5648              : 
    5649              :     impl TestRedoManager {
    5650              :         /// # Cancel-Safety
    5651              :         ///
    5652              :         /// This method is cancellation-safe.
    5653         1636 :         pub async fn request_redo(
    5654         1636 :             &self,
    5655         1636 :             key: Key,
    5656         1636 :             lsn: Lsn,
    5657         1636 :             base_img: Option<(Lsn, Bytes)>,
    5658         1636 :             records: Vec<(Lsn, NeonWalRecord)>,
    5659         1636 :             _pg_version: u32,
    5660         1636 :         ) -> Result<Bytes, walredo::Error> {
    5661         2392 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5662         1636 :             if records_neon {
    5663              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5664         1636 :                 let mut page = match (base_img, records.first()) {
    5665         1504 :                     (Some((_lsn, img)), _) => {
    5666         1504 :                         let mut page = BytesMut::new();
    5667         1504 :                         page.extend_from_slice(&img);
    5668         1504 :                         page
    5669              :                     }
    5670          132 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5671              :                     _ => {
    5672            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5673              :                     }
    5674              :                 };
    5675              : 
    5676         4028 :                 for (record_lsn, record) in records {
    5677         2392 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5678              :                 }
    5679         1636 :                 Ok(page.freeze())
    5680              :             } else {
    5681              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5682            0 :                 let s = format!(
    5683            0 :                     "redo for {} to get to {}, with {} and {} records",
    5684            0 :                     key,
    5685            0 :                     lsn,
    5686            0 :                     if base_img.is_some() {
    5687            0 :                         "base image"
    5688              :                     } else {
    5689            0 :                         "no base image"
    5690              :                     },
    5691            0 :                     records.len()
    5692            0 :                 );
    5693            0 :                 println!("{s}");
    5694            0 : 
    5695            0 :                 Ok(test_img(&s))
    5696              :             }
    5697         1636 :         }
    5698              :     }
    5699              : }
    5700              : 
    5701              : #[cfg(test)]
    5702              : mod tests {
    5703              :     use std::collections::{BTreeMap, BTreeSet};
    5704              : 
    5705              :     use super::*;
    5706              :     use crate::keyspace::KeySpaceAccum;
    5707              :     use crate::tenant::harness::*;
    5708              :     use crate::tenant::timeline::CompactFlags;
    5709              :     use crate::DEFAULT_PG_VERSION;
    5710              :     use bytes::{Bytes, BytesMut};
    5711              :     use hex_literal::hex;
    5712              :     use itertools::Itertools;
    5713              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5714              :     use pageserver_api::keyspace::KeySpace;
    5715              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5716              :     use pageserver_api::value::Value;
    5717              :     use pageserver_compaction::helpers::overlaps_with;
    5718              :     use rand::{thread_rng, Rng};
    5719              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5720              :     use tests::storage_layer::ValuesReconstructState;
    5721              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5722              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5723              :     use utils::id::TenantId;
    5724              : 
    5725              :     #[cfg(feature = "testing")]
    5726              :     use models::CompactLsnRange;
    5727              :     #[cfg(feature = "testing")]
    5728              :     use pageserver_api::record::NeonWalRecord;
    5729              :     #[cfg(feature = "testing")]
    5730              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5731              :     #[cfg(feature = "testing")]
    5732              :     use timeline::GcInfo;
    5733              : 
    5734              :     static TEST_KEY: Lazy<Key> =
    5735           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5736              : 
    5737              :     #[tokio::test]
    5738            4 :     async fn test_basic() -> anyhow::Result<()> {
    5739            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5740            4 :         let tline = tenant
    5741            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5742            4 :             .await?;
    5743            4 : 
    5744            4 :         let mut writer = tline.writer().await;
    5745            4 :         writer
    5746            4 :             .put(
    5747            4 :                 *TEST_KEY,
    5748            4 :                 Lsn(0x10),
    5749            4 :                 &Value::Image(test_img("foo at 0x10")),
    5750            4 :                 &ctx,
    5751            4 :             )
    5752            4 :             .await?;
    5753            4 :         writer.finish_write(Lsn(0x10));
    5754            4 :         drop(writer);
    5755            4 : 
    5756            4 :         let mut writer = tline.writer().await;
    5757            4 :         writer
    5758            4 :             .put(
    5759            4 :                 *TEST_KEY,
    5760            4 :                 Lsn(0x20),
    5761            4 :                 &Value::Image(test_img("foo at 0x20")),
    5762            4 :                 &ctx,
    5763            4 :             )
    5764            4 :             .await?;
    5765            4 :         writer.finish_write(Lsn(0x20));
    5766            4 :         drop(writer);
    5767            4 : 
    5768            4 :         assert_eq!(
    5769            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5770            4 :             test_img("foo at 0x10")
    5771            4 :         );
    5772            4 :         assert_eq!(
    5773            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5774            4 :             test_img("foo at 0x10")
    5775            4 :         );
    5776            4 :         assert_eq!(
    5777            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5778            4 :             test_img("foo at 0x20")
    5779            4 :         );
    5780            4 : 
    5781            4 :         Ok(())
    5782            4 :     }
    5783              : 
    5784              :     #[tokio::test]
    5785            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5786            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5787            4 :             .await?
    5788            4 :             .load()
    5789            4 :             .await;
    5790            4 :         let _ = tenant
    5791            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5792            4 :             .await?;
    5793            4 : 
    5794            4 :         match tenant
    5795            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5796            4 :             .await
    5797            4 :         {
    5798            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5799            4 :             Err(e) => assert_eq!(
    5800            4 :                 e.to_string(),
    5801            4 :                 "timeline already exists with different parameters".to_string()
    5802            4 :             ),
    5803            4 :         }
    5804            4 : 
    5805            4 :         Ok(())
    5806            4 :     }
    5807              : 
    5808              :     /// Convenience function to create a page image with given string as the only content
    5809           20 :     pub fn test_value(s: &str) -> Value {
    5810           20 :         let mut buf = BytesMut::new();
    5811           20 :         buf.extend_from_slice(s.as_bytes());
    5812           20 :         Value::Image(buf.freeze())
    5813           20 :     }
    5814              : 
    5815              :     ///
    5816              :     /// Test branch creation
    5817              :     ///
    5818              :     #[tokio::test]
    5819            4 :     async fn test_branch() -> anyhow::Result<()> {
    5820            4 :         use std::str::from_utf8;
    5821            4 : 
    5822            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5823            4 :         let tline = tenant
    5824            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5825            4 :             .await?;
    5826            4 :         let mut writer = tline.writer().await;
    5827            4 : 
    5828            4 :         #[allow(non_snake_case)]
    5829            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5830            4 :         #[allow(non_snake_case)]
    5831            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5832            4 : 
    5833            4 :         // Insert a value on the timeline
    5834            4 :         writer
    5835            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5836            4 :             .await?;
    5837            4 :         writer
    5838            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5839            4 :             .await?;
    5840            4 :         writer.finish_write(Lsn(0x20));
    5841            4 : 
    5842            4 :         writer
    5843            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5844            4 :             .await?;
    5845            4 :         writer.finish_write(Lsn(0x30));
    5846            4 :         writer
    5847            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5848            4 :             .await?;
    5849            4 :         writer.finish_write(Lsn(0x40));
    5850            4 : 
    5851            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5852            4 : 
    5853            4 :         // Branch the history, modify relation differently on the new timeline
    5854            4 :         tenant
    5855            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5856            4 :             .await?;
    5857            4 :         let newtline = tenant
    5858            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    5859            4 :             .expect("Should have a local timeline");
    5860            4 :         let mut new_writer = newtline.writer().await;
    5861            4 :         new_writer
    5862            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5863            4 :             .await?;
    5864            4 :         new_writer.finish_write(Lsn(0x40));
    5865            4 : 
    5866            4 :         // Check page contents on both branches
    5867            4 :         assert_eq!(
    5868            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5869            4 :             "foo at 0x40"
    5870            4 :         );
    5871            4 :         assert_eq!(
    5872            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5873            4 :             "bar at 0x40"
    5874            4 :         );
    5875            4 :         assert_eq!(
    5876            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5877            4 :             "foobar at 0x20"
    5878            4 :         );
    5879            4 : 
    5880            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5881            4 : 
    5882            4 :         Ok(())
    5883            4 :     }
    5884              : 
    5885           40 :     async fn make_some_layers(
    5886           40 :         tline: &Timeline,
    5887           40 :         start_lsn: Lsn,
    5888           40 :         ctx: &RequestContext,
    5889           40 :     ) -> anyhow::Result<()> {
    5890           40 :         let mut lsn = start_lsn;
    5891              :         {
    5892           40 :             let mut writer = tline.writer().await;
    5893              :             // Create a relation on the timeline
    5894           40 :             writer
    5895           40 :                 .put(
    5896           40 :                     *TEST_KEY,
    5897           40 :                     lsn,
    5898           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5899           40 :                     ctx,
    5900           40 :                 )
    5901           40 :                 .await?;
    5902           40 :             writer.finish_write(lsn);
    5903           40 :             lsn += 0x10;
    5904           40 :             writer
    5905           40 :                 .put(
    5906           40 :                     *TEST_KEY,
    5907           40 :                     lsn,
    5908           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5909           40 :                     ctx,
    5910           40 :                 )
    5911           40 :                 .await?;
    5912           40 :             writer.finish_write(lsn);
    5913           40 :             lsn += 0x10;
    5914           40 :         }
    5915           40 :         tline.freeze_and_flush().await?;
    5916              :         {
    5917           40 :             let mut writer = tline.writer().await;
    5918           40 :             writer
    5919           40 :                 .put(
    5920           40 :                     *TEST_KEY,
    5921           40 :                     lsn,
    5922           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5923           40 :                     ctx,
    5924           40 :                 )
    5925           40 :                 .await?;
    5926           40 :             writer.finish_write(lsn);
    5927           40 :             lsn += 0x10;
    5928           40 :             writer
    5929           40 :                 .put(
    5930           40 :                     *TEST_KEY,
    5931           40 :                     lsn,
    5932           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5933           40 :                     ctx,
    5934           40 :                 )
    5935           40 :                 .await?;
    5936           40 :             writer.finish_write(lsn);
    5937           40 :         }
    5938           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5939           40 :     }
    5940              : 
    5941              :     #[tokio::test(start_paused = true)]
    5942            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5943            4 :         let (tenant, ctx) =
    5944            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5945            4 :                 .await?
    5946            4 :                 .load()
    5947            4 :                 .await;
    5948            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5949            4 :         // initial transition into AttachedSingle.
    5950            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5951            4 :         tokio::time::resume();
    5952            4 :         let tline = tenant
    5953            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5954            4 :             .await?;
    5955            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5956            4 : 
    5957            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5958            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5959            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5960            4 :         // below should fail.
    5961            4 :         tenant
    5962            4 :             .gc_iteration(
    5963            4 :                 Some(TIMELINE_ID),
    5964            4 :                 0x10,
    5965            4 :                 Duration::ZERO,
    5966            4 :                 &CancellationToken::new(),
    5967            4 :                 &ctx,
    5968            4 :             )
    5969            4 :             .await?;
    5970            4 : 
    5971            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5972            4 :         match tenant
    5973            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5974            4 :             .await
    5975            4 :         {
    5976            4 :             Ok(_) => panic!("branching should have failed"),
    5977            4 :             Err(err) => {
    5978            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5979            4 :                     panic!("wrong error type")
    5980            4 :                 };
    5981            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    5982            4 :                 assert!(err
    5983            4 :                     .source()
    5984            4 :                     .unwrap()
    5985            4 :                     .to_string()
    5986            4 :                     .contains("we might've already garbage collected needed data"))
    5987            4 :             }
    5988            4 :         }
    5989            4 : 
    5990            4 :         Ok(())
    5991            4 :     }
    5992              : 
    5993              :     #[tokio::test]
    5994            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    5995            4 :         let (tenant, ctx) =
    5996            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    5997            4 :                 .await?
    5998            4 :                 .load()
    5999            4 :                 .await;
    6000            4 : 
    6001            4 :         let tline = tenant
    6002            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6003            4 :             .await?;
    6004            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6005            4 :         match tenant
    6006            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6007            4 :             .await
    6008            4 :         {
    6009            4 :             Ok(_) => panic!("branching should have failed"),
    6010            4 :             Err(err) => {
    6011            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6012            4 :                     panic!("wrong error type");
    6013            4 :                 };
    6014            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6015            4 :                 assert!(&err
    6016            4 :                     .source()
    6017            4 :                     .unwrap()
    6018            4 :                     .to_string()
    6019            4 :                     .contains("is earlier than latest GC cutoff"));
    6020            4 :             }
    6021            4 :         }
    6022            4 : 
    6023            4 :         Ok(())
    6024            4 :     }
    6025              : 
    6026              :     /*
    6027              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6028              :     // remove the old value, we'd need to work a little harder
    6029              :     #[tokio::test]
    6030              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6031              :         let repo =
    6032              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6033              :             .load();
    6034              : 
    6035              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6036              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6037              : 
    6038              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6039              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    6040              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    6041              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6042              :             Ok(_) => panic!("request for page should have failed"),
    6043              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6044              :         }
    6045              :         Ok(())
    6046              :     }
    6047              :      */
    6048              : 
    6049              :     #[tokio::test]
    6050            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6051            4 :         let (tenant, ctx) =
    6052            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6053            4 :                 .await?
    6054            4 :                 .load()
    6055            4 :                 .await;
    6056            4 :         let tline = tenant
    6057            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6058            4 :             .await?;
    6059            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6060            4 : 
    6061            4 :         tenant
    6062            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6063            4 :             .await?;
    6064            4 :         let newtline = tenant
    6065            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6066            4 :             .expect("Should have a local timeline");
    6067            4 : 
    6068            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6069            4 : 
    6070            4 :         tline.set_broken("test".to_owned());
    6071            4 : 
    6072            4 :         tenant
    6073            4 :             .gc_iteration(
    6074            4 :                 Some(TIMELINE_ID),
    6075            4 :                 0x10,
    6076            4 :                 Duration::ZERO,
    6077            4 :                 &CancellationToken::new(),
    6078            4 :                 &ctx,
    6079            4 :             )
    6080            4 :             .await?;
    6081            4 : 
    6082            4 :         // The branchpoints should contain all timelines, even ones marked
    6083            4 :         // as Broken.
    6084            4 :         {
    6085            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6086            4 :             assert_eq!(branchpoints.len(), 1);
    6087            4 :             assert_eq!(
    6088            4 :                 branchpoints[0],
    6089            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6090            4 :             );
    6091            4 :         }
    6092            4 : 
    6093            4 :         // You can read the key from the child branch even though the parent is
    6094            4 :         // Broken, as long as you don't need to access data from the parent.
    6095            4 :         assert_eq!(
    6096            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6097            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6098            4 :         );
    6099            4 : 
    6100            4 :         // This needs to traverse to the parent, and fails.
    6101            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6102            4 :         assert!(
    6103            4 :             err.to_string().starts_with(&format!(
    6104            4 :                 "bad state on timeline {}: Broken",
    6105            4 :                 tline.timeline_id
    6106            4 :             )),
    6107            4 :             "{err}"
    6108            4 :         );
    6109            4 : 
    6110            4 :         Ok(())
    6111            4 :     }
    6112              : 
    6113              :     #[tokio::test]
    6114            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6115            4 :         let (tenant, ctx) =
    6116            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6117            4 :                 .await?
    6118            4 :                 .load()
    6119            4 :                 .await;
    6120            4 :         let tline = tenant
    6121            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6122            4 :             .await?;
    6123            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6124            4 : 
    6125            4 :         tenant
    6126            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6127            4 :             .await?;
    6128            4 :         let newtline = tenant
    6129            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6130            4 :             .expect("Should have a local timeline");
    6131            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6132            4 :         tenant
    6133            4 :             .gc_iteration(
    6134            4 :                 Some(TIMELINE_ID),
    6135            4 :                 0x10,
    6136            4 :                 Duration::ZERO,
    6137            4 :                 &CancellationToken::new(),
    6138            4 :                 &ctx,
    6139            4 :             )
    6140            4 :             .await?;
    6141            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6142            4 : 
    6143            4 :         Ok(())
    6144            4 :     }
    6145              :     #[tokio::test]
    6146            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6147            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6148            4 :             .await?
    6149            4 :             .load()
    6150            4 :             .await;
    6151            4 :         let tline = tenant
    6152            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6153            4 :             .await?;
    6154            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6155            4 : 
    6156            4 :         tenant
    6157            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6158            4 :             .await?;
    6159            4 :         let newtline = tenant
    6160            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6161            4 :             .expect("Should have a local timeline");
    6162            4 : 
    6163            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6164            4 : 
    6165            4 :         // run gc on parent
    6166            4 :         tenant
    6167            4 :             .gc_iteration(
    6168            4 :                 Some(TIMELINE_ID),
    6169            4 :                 0x10,
    6170            4 :                 Duration::ZERO,
    6171            4 :                 &CancellationToken::new(),
    6172            4 :                 &ctx,
    6173            4 :             )
    6174            4 :             .await?;
    6175            4 : 
    6176            4 :         // Check that the data is still accessible on the branch.
    6177            4 :         assert_eq!(
    6178            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6179            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6180            4 :         );
    6181            4 : 
    6182            4 :         Ok(())
    6183            4 :     }
    6184              : 
    6185              :     #[tokio::test]
    6186            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6187            4 :         const TEST_NAME: &str = "timeline_load";
    6188            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6189            4 :         {
    6190            4 :             let (tenant, ctx) = harness.load().await;
    6191            4 :             let tline = tenant
    6192            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6193            4 :                 .await?;
    6194            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6195            4 :             // so that all uploads finish & we can call harness.load() below again
    6196            4 :             tenant
    6197            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6198            4 :                 .instrument(harness.span())
    6199            4 :                 .await
    6200            4 :                 .ok()
    6201            4 :                 .unwrap();
    6202            4 :         }
    6203            4 : 
    6204            4 :         let (tenant, _ctx) = harness.load().await;
    6205            4 :         tenant
    6206            4 :             .get_timeline(TIMELINE_ID, true)
    6207            4 :             .expect("cannot load timeline");
    6208            4 : 
    6209            4 :         Ok(())
    6210            4 :     }
    6211              : 
    6212              :     #[tokio::test]
    6213            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6214            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6215            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6216            4 :         // create two timelines
    6217            4 :         {
    6218            4 :             let (tenant, ctx) = harness.load().await;
    6219            4 :             let tline = tenant
    6220            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6221            4 :                 .await?;
    6222            4 : 
    6223            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6224            4 : 
    6225            4 :             let child_tline = tenant
    6226            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6227            4 :                 .await?;
    6228            4 :             child_tline.set_state(TimelineState::Active);
    6229            4 : 
    6230            4 :             let newtline = tenant
    6231            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6232            4 :                 .expect("Should have a local timeline");
    6233            4 : 
    6234            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6235            4 : 
    6236            4 :             // so that all uploads finish & we can call harness.load() below again
    6237            4 :             tenant
    6238            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6239            4 :                 .instrument(harness.span())
    6240            4 :                 .await
    6241            4 :                 .ok()
    6242            4 :                 .unwrap();
    6243            4 :         }
    6244            4 : 
    6245            4 :         // check that both of them are initially unloaded
    6246            4 :         let (tenant, _ctx) = harness.load().await;
    6247            4 : 
    6248            4 :         // check that both, child and ancestor are loaded
    6249            4 :         let _child_tline = tenant
    6250            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6251            4 :             .expect("cannot get child timeline loaded");
    6252            4 : 
    6253            4 :         let _ancestor_tline = tenant
    6254            4 :             .get_timeline(TIMELINE_ID, true)
    6255            4 :             .expect("cannot get ancestor timeline loaded");
    6256            4 : 
    6257            4 :         Ok(())
    6258            4 :     }
    6259              : 
    6260              :     #[tokio::test]
    6261            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6262            4 :         use storage_layer::AsLayerDesc;
    6263            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6264            4 :             .await?
    6265            4 :             .load()
    6266            4 :             .await;
    6267            4 :         let tline = tenant
    6268            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6269            4 :             .await?;
    6270            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6271            4 : 
    6272            4 :         let layer_map = tline.layers.read().await;
    6273            4 :         let level0_deltas = layer_map
    6274            4 :             .layer_map()?
    6275            4 :             .level0_deltas()
    6276            4 :             .iter()
    6277            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6278            4 :             .collect::<Vec<_>>();
    6279            4 : 
    6280            4 :         assert!(!level0_deltas.is_empty());
    6281            4 : 
    6282           12 :         for delta in level0_deltas {
    6283            4 :             // Ensure we are dumping a delta layer here
    6284            8 :             assert!(delta.layer_desc().is_delta);
    6285            8 :             delta.dump(true, &ctx).await.unwrap();
    6286            4 :         }
    6287            4 : 
    6288            4 :         Ok(())
    6289            4 :     }
    6290              : 
    6291              :     #[tokio::test]
    6292            4 :     async fn test_images() -> anyhow::Result<()> {
    6293            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6294            4 :         let tline = tenant
    6295            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6296            4 :             .await?;
    6297            4 : 
    6298            4 :         let mut writer = tline.writer().await;
    6299            4 :         writer
    6300            4 :             .put(
    6301            4 :                 *TEST_KEY,
    6302            4 :                 Lsn(0x10),
    6303            4 :                 &Value::Image(test_img("foo at 0x10")),
    6304            4 :                 &ctx,
    6305            4 :             )
    6306            4 :             .await?;
    6307            4 :         writer.finish_write(Lsn(0x10));
    6308            4 :         drop(writer);
    6309            4 : 
    6310            4 :         tline.freeze_and_flush().await?;
    6311            4 :         tline
    6312            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6313            4 :             .await?;
    6314            4 : 
    6315            4 :         let mut writer = tline.writer().await;
    6316            4 :         writer
    6317            4 :             .put(
    6318            4 :                 *TEST_KEY,
    6319            4 :                 Lsn(0x20),
    6320            4 :                 &Value::Image(test_img("foo at 0x20")),
    6321            4 :                 &ctx,
    6322            4 :             )
    6323            4 :             .await?;
    6324            4 :         writer.finish_write(Lsn(0x20));
    6325            4 :         drop(writer);
    6326            4 : 
    6327            4 :         tline.freeze_and_flush().await?;
    6328            4 :         tline
    6329            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6330            4 :             .await?;
    6331            4 : 
    6332            4 :         let mut writer = tline.writer().await;
    6333            4 :         writer
    6334            4 :             .put(
    6335            4 :                 *TEST_KEY,
    6336            4 :                 Lsn(0x30),
    6337            4 :                 &Value::Image(test_img("foo at 0x30")),
    6338            4 :                 &ctx,
    6339            4 :             )
    6340            4 :             .await?;
    6341            4 :         writer.finish_write(Lsn(0x30));
    6342            4 :         drop(writer);
    6343            4 : 
    6344            4 :         tline.freeze_and_flush().await?;
    6345            4 :         tline
    6346            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6347            4 :             .await?;
    6348            4 : 
    6349            4 :         let mut writer = tline.writer().await;
    6350            4 :         writer
    6351            4 :             .put(
    6352            4 :                 *TEST_KEY,
    6353            4 :                 Lsn(0x40),
    6354            4 :                 &Value::Image(test_img("foo at 0x40")),
    6355            4 :                 &ctx,
    6356            4 :             )
    6357            4 :             .await?;
    6358            4 :         writer.finish_write(Lsn(0x40));
    6359            4 :         drop(writer);
    6360            4 : 
    6361            4 :         tline.freeze_and_flush().await?;
    6362            4 :         tline
    6363            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6364            4 :             .await?;
    6365            4 : 
    6366            4 :         assert_eq!(
    6367            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6368            4 :             test_img("foo at 0x10")
    6369            4 :         );
    6370            4 :         assert_eq!(
    6371            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6372            4 :             test_img("foo at 0x10")
    6373            4 :         );
    6374            4 :         assert_eq!(
    6375            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6376            4 :             test_img("foo at 0x20")
    6377            4 :         );
    6378            4 :         assert_eq!(
    6379            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6380            4 :             test_img("foo at 0x30")
    6381            4 :         );
    6382            4 :         assert_eq!(
    6383            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6384            4 :             test_img("foo at 0x40")
    6385            4 :         );
    6386            4 : 
    6387            4 :         Ok(())
    6388            4 :     }
    6389              : 
    6390            8 :     async fn bulk_insert_compact_gc(
    6391            8 :         tenant: &Tenant,
    6392            8 :         timeline: &Arc<Timeline>,
    6393            8 :         ctx: &RequestContext,
    6394            8 :         lsn: Lsn,
    6395            8 :         repeat: usize,
    6396            8 :         key_count: usize,
    6397            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6398            8 :         let compact = true;
    6399            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6400            8 :     }
    6401              : 
    6402           16 :     async fn bulk_insert_maybe_compact_gc(
    6403           16 :         tenant: &Tenant,
    6404           16 :         timeline: &Arc<Timeline>,
    6405           16 :         ctx: &RequestContext,
    6406           16 :         mut lsn: Lsn,
    6407           16 :         repeat: usize,
    6408           16 :         key_count: usize,
    6409           16 :         compact: bool,
    6410           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6411           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6412           16 : 
    6413           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6414           16 :         let mut blknum = 0;
    6415           16 : 
    6416           16 :         // Enforce that key range is monotonously increasing
    6417           16 :         let mut keyspace = KeySpaceAccum::new();
    6418           16 : 
    6419           16 :         let cancel = CancellationToken::new();
    6420           16 : 
    6421           16 :         for _ in 0..repeat {
    6422          800 :             for _ in 0..key_count {
    6423      8000000 :                 test_key.field6 = blknum;
    6424      8000000 :                 let mut writer = timeline.writer().await;
    6425      8000000 :                 writer
    6426      8000000 :                     .put(
    6427      8000000 :                         test_key,
    6428      8000000 :                         lsn,
    6429      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6430      8000000 :                         ctx,
    6431      8000000 :                     )
    6432      8000000 :                     .await?;
    6433      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6434      8000000 :                 writer.finish_write(lsn);
    6435      8000000 :                 drop(writer);
    6436      8000000 : 
    6437      8000000 :                 keyspace.add_key(test_key);
    6438      8000000 : 
    6439      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6440      8000000 :                 blknum += 1;
    6441              :             }
    6442              : 
    6443          800 :             timeline.freeze_and_flush().await?;
    6444          800 :             if compact {
    6445              :                 // this requires timeline to be &Arc<Timeline>
    6446          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6447          400 :             }
    6448              : 
    6449              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6450              :             // originally was.
    6451          800 :             let res = tenant
    6452          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6453          800 :                 .await?;
    6454              : 
    6455          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6456              :         }
    6457              : 
    6458           16 :         Ok(inserted)
    6459           16 :     }
    6460              : 
    6461              :     //
    6462              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6463              :     // Repeat 50 times.
    6464              :     //
    6465              :     #[tokio::test]
    6466            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6467            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6468            4 :         let (tenant, ctx) = harness.load().await;
    6469            4 :         let tline = tenant
    6470            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6471            4 :             .await?;
    6472            4 : 
    6473            4 :         let lsn = Lsn(0x10);
    6474            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6475            4 : 
    6476            4 :         Ok(())
    6477            4 :     }
    6478              : 
    6479              :     // Test the vectored get real implementation against a simple sequential implementation.
    6480              :     //
    6481              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6482              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6483              :     // grow to the right on the X axis.
    6484              :     //                       [Delta]
    6485              :     //                 [Delta]
    6486              :     //           [Delta]
    6487              :     //    [Delta]
    6488              :     // ------------ Image ---------------
    6489              :     //
    6490              :     // After layer generation we pick the ranges to query as follows:
    6491              :     // 1. The beginning of each delta layer
    6492              :     // 2. At the seam between two adjacent delta layers
    6493              :     //
    6494              :     // There's one major downside to this test: delta layers only contains images,
    6495              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6496              :     #[tokio::test]
    6497            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6498            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6499            4 :         let (tenant, ctx) = harness.load().await;
    6500            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6501            4 :         let tline = tenant
    6502            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6503            4 :             .await?;
    6504            4 : 
    6505            4 :         let lsn = Lsn(0x10);
    6506            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6507            4 : 
    6508            4 :         let guard = tline.layers.read().await;
    6509            4 :         let lm = guard.layer_map()?;
    6510            4 : 
    6511            4 :         lm.dump(true, &ctx).await?;
    6512            4 : 
    6513            4 :         let mut reads = Vec::new();
    6514            4 :         let mut prev = None;
    6515           24 :         lm.iter_historic_layers().for_each(|desc| {
    6516           24 :             if !desc.is_delta() {
    6517            4 :                 prev = Some(desc.clone());
    6518            4 :                 return;
    6519           20 :             }
    6520           20 : 
    6521           20 :             let start = desc.key_range.start;
    6522           20 :             let end = desc
    6523           20 :                 .key_range
    6524           20 :                 .start
    6525           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6526           20 :             reads.push(KeySpace {
    6527           20 :                 ranges: vec![start..end],
    6528           20 :             });
    6529            4 : 
    6530           20 :             if let Some(prev) = &prev {
    6531           20 :                 if !prev.is_delta() {
    6532           20 :                     return;
    6533            4 :                 }
    6534            0 : 
    6535            0 :                 let first_range = Key {
    6536            0 :                     field6: prev.key_range.end.field6 - 4,
    6537            0 :                     ..prev.key_range.end
    6538            0 :                 }..prev.key_range.end;
    6539            0 : 
    6540            0 :                 let second_range = desc.key_range.start..Key {
    6541            0 :                     field6: desc.key_range.start.field6 + 4,
    6542            0 :                     ..desc.key_range.start
    6543            0 :                 };
    6544            0 : 
    6545            0 :                 reads.push(KeySpace {
    6546            0 :                     ranges: vec![first_range, second_range],
    6547            0 :                 });
    6548            4 :             };
    6549            4 : 
    6550            4 :             prev = Some(desc.clone());
    6551           24 :         });
    6552            4 : 
    6553            4 :         drop(guard);
    6554            4 : 
    6555            4 :         // Pick a big LSN such that we query over all the changes.
    6556            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6557            4 : 
    6558           24 :         for read in reads {
    6559           20 :             info!("Doing vectored read on {:?}", read);
    6560            4 : 
    6561           20 :             let vectored_res = tline
    6562           20 :                 .get_vectored_impl(
    6563           20 :                     read.clone(),
    6564           20 :                     reads_lsn,
    6565           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6566           20 :                     &ctx,
    6567           20 :                 )
    6568           20 :                 .await;
    6569            4 : 
    6570           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6571           20 :             let mut expect_missing = false;
    6572           20 :             let mut key = read.start().unwrap();
    6573          660 :             while key != read.end().unwrap() {
    6574          640 :                 if let Some(lsns) = inserted.get(&key) {
    6575          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6576          640 :                     match expected_lsn {
    6577          640 :                         Some(lsn) => {
    6578          640 :                             expected_lsns.insert(key, *lsn);
    6579          640 :                         }
    6580            4 :                         None => {
    6581            4 :                             expect_missing = true;
    6582            0 :                             break;
    6583            4 :                         }
    6584            4 :                     }
    6585            4 :                 } else {
    6586            4 :                     expect_missing = true;
    6587            0 :                     break;
    6588            4 :                 }
    6589            4 : 
    6590          640 :                 key = key.next();
    6591            4 :             }
    6592            4 : 
    6593           20 :             if expect_missing {
    6594            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6595            4 :             } else {
    6596          640 :                 for (key, image) in vectored_res? {
    6597          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6598          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6599          640 :                     assert_eq!(image?, expected_image);
    6600            4 :                 }
    6601            4 :             }
    6602            4 :         }
    6603            4 : 
    6604            4 :         Ok(())
    6605            4 :     }
    6606              : 
    6607              :     #[tokio::test]
    6608            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6609            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6610            4 : 
    6611            4 :         let (tenant, ctx) = harness.load().await;
    6612            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6613            4 :         let tline = tenant
    6614            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6615            4 :             .await?;
    6616            4 :         let tline = tline.raw_timeline().unwrap();
    6617            4 : 
    6618            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6619            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6620            4 :         modification.set_lsn(Lsn(0x1008))?;
    6621            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6622            4 :         modification.commit(&ctx).await?;
    6623            4 : 
    6624            4 :         let child_timeline_id = TimelineId::generate();
    6625            4 :         tenant
    6626            4 :             .branch_timeline_test(
    6627            4 :                 tline,
    6628            4 :                 child_timeline_id,
    6629            4 :                 Some(tline.get_last_record_lsn()),
    6630            4 :                 &ctx,
    6631            4 :             )
    6632            4 :             .await?;
    6633            4 : 
    6634            4 :         let child_timeline = tenant
    6635            4 :             .get_timeline(child_timeline_id, true)
    6636            4 :             .expect("Should have the branched timeline");
    6637            4 : 
    6638            4 :         let aux_keyspace = KeySpace {
    6639            4 :             ranges: vec![NON_INHERITED_RANGE],
    6640            4 :         };
    6641            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6642            4 : 
    6643            4 :         let vectored_res = child_timeline
    6644            4 :             .get_vectored_impl(
    6645            4 :                 aux_keyspace.clone(),
    6646            4 :                 read_lsn,
    6647            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6648            4 :                 &ctx,
    6649            4 :             )
    6650            4 :             .await;
    6651            4 : 
    6652            4 :         let images = vectored_res?;
    6653            4 :         assert!(images.is_empty());
    6654            4 :         Ok(())
    6655            4 :     }
    6656              : 
    6657              :     // Test that vectored get handles layer gaps correctly
    6658              :     // by advancing into the next ancestor timeline if required.
    6659              :     //
    6660              :     // The test generates timelines that look like the diagram below.
    6661              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6662              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6663              :     //
    6664              :     // ```
    6665              :     //-------------------------------+
    6666              :     //                          ...  |
    6667              :     //               [   L1   ]      |
    6668              :     //     [ / L1   ]                | Child Timeline
    6669              :     // ...                           |
    6670              :     // ------------------------------+
    6671              :     //     [ X L1   ]                | Parent Timeline
    6672              :     // ------------------------------+
    6673              :     // ```
    6674              :     #[tokio::test]
    6675            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6676            4 :         let tenant_conf = TenantConf {
    6677            4 :             // Make compaction deterministic
    6678            4 :             gc_period: Duration::ZERO,
    6679            4 :             compaction_period: Duration::ZERO,
    6680            4 :             // Encourage creation of L1 layers
    6681            4 :             checkpoint_distance: 16 * 1024,
    6682            4 :             compaction_target_size: 8 * 1024,
    6683            4 :             ..TenantConf::default()
    6684            4 :         };
    6685            4 : 
    6686            4 :         let harness = TenantHarness::create_custom(
    6687            4 :             "test_get_vectored_key_gap",
    6688            4 :             tenant_conf,
    6689            4 :             TenantId::generate(),
    6690            4 :             ShardIdentity::unsharded(),
    6691            4 :             Generation::new(0xdeadbeef),
    6692            4 :         )
    6693            4 :         .await?;
    6694            4 :         let (tenant, ctx) = harness.load().await;
    6695            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6696            4 : 
    6697            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6698            4 :         let gap_at_key = current_key.add(100);
    6699            4 :         let mut current_lsn = Lsn(0x10);
    6700            4 : 
    6701            4 :         const KEY_COUNT: usize = 10_000;
    6702            4 : 
    6703            4 :         let timeline_id = TimelineId::generate();
    6704            4 :         let current_timeline = tenant
    6705            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6706            4 :             .await?;
    6707            4 : 
    6708            4 :         current_lsn += 0x100;
    6709            4 : 
    6710            4 :         let mut writer = current_timeline.writer().await;
    6711            4 :         writer
    6712            4 :             .put(
    6713            4 :                 gap_at_key,
    6714            4 :                 current_lsn,
    6715            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6716            4 :                 &ctx,
    6717            4 :             )
    6718            4 :             .await?;
    6719            4 :         writer.finish_write(current_lsn);
    6720            4 :         drop(writer);
    6721            4 : 
    6722            4 :         let mut latest_lsns = HashMap::new();
    6723            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6724            4 : 
    6725            4 :         current_timeline.freeze_and_flush().await?;
    6726            4 : 
    6727            4 :         let child_timeline_id = TimelineId::generate();
    6728            4 : 
    6729            4 :         tenant
    6730            4 :             .branch_timeline_test(
    6731            4 :                 &current_timeline,
    6732            4 :                 child_timeline_id,
    6733            4 :                 Some(current_lsn),
    6734            4 :                 &ctx,
    6735            4 :             )
    6736            4 :             .await?;
    6737            4 :         let child_timeline = tenant
    6738            4 :             .get_timeline(child_timeline_id, true)
    6739            4 :             .expect("Should have the branched timeline");
    6740            4 : 
    6741        40004 :         for i in 0..KEY_COUNT {
    6742        40000 :             if current_key == gap_at_key {
    6743            4 :                 current_key = current_key.next();
    6744            4 :                 continue;
    6745        39996 :             }
    6746        39996 : 
    6747        39996 :             current_lsn += 0x10;
    6748            4 : 
    6749        39996 :             let mut writer = child_timeline.writer().await;
    6750        39996 :             writer
    6751        39996 :                 .put(
    6752        39996 :                     current_key,
    6753        39996 :                     current_lsn,
    6754        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6755        39996 :                     &ctx,
    6756        39996 :                 )
    6757        39996 :                 .await?;
    6758        39996 :             writer.finish_write(current_lsn);
    6759        39996 :             drop(writer);
    6760        39996 : 
    6761        39996 :             latest_lsns.insert(current_key, current_lsn);
    6762        39996 :             current_key = current_key.next();
    6763        39996 : 
    6764        39996 :             // Flush every now and then to encourage layer file creation.
    6765        39996 :             if i % 500 == 0 {
    6766           80 :                 child_timeline.freeze_and_flush().await?;
    6767        39916 :             }
    6768            4 :         }
    6769            4 : 
    6770            4 :         child_timeline.freeze_and_flush().await?;
    6771            4 :         let mut flags = EnumSet::new();
    6772            4 :         flags.insert(CompactFlags::ForceRepartition);
    6773            4 :         child_timeline
    6774            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    6775            4 :             .await?;
    6776            4 : 
    6777            4 :         let key_near_end = {
    6778            4 :             let mut tmp = current_key;
    6779            4 :             tmp.field6 -= 10;
    6780            4 :             tmp
    6781            4 :         };
    6782            4 : 
    6783            4 :         let key_near_gap = {
    6784            4 :             let mut tmp = gap_at_key;
    6785            4 :             tmp.field6 -= 10;
    6786            4 :             tmp
    6787            4 :         };
    6788            4 : 
    6789            4 :         let read = KeySpace {
    6790            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6791            4 :         };
    6792            4 :         let results = child_timeline
    6793            4 :             .get_vectored_impl(
    6794            4 :                 read.clone(),
    6795            4 :                 current_lsn,
    6796            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6797            4 :                 &ctx,
    6798            4 :             )
    6799            4 :             .await?;
    6800            4 : 
    6801           88 :         for (key, img_res) in results {
    6802           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6803           84 :             assert_eq!(img_res?, expected);
    6804            4 :         }
    6805            4 : 
    6806            4 :         Ok(())
    6807            4 :     }
    6808              : 
    6809              :     // Test that vectored get descends into ancestor timelines correctly and
    6810              :     // does not return an image that's newer than requested.
    6811              :     //
    6812              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6813              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6814              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6815              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6816              :     // order to avoid returning an image that's too new. The test below constructs such
    6817              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6818              :     // ```
    6819              :     //    LSN
    6820              :     //     ^
    6821              :     //     |
    6822              :     //     |
    6823              :     // 500 | --------------------------------------> branch point
    6824              :     // 400 |        X
    6825              :     // 300 |        X
    6826              :     // 200 | --------------------------------------> requested lsn
    6827              :     // 100 |        X
    6828              :     //     |---------------------------------------> Key
    6829              :     //              |
    6830              :     //              ------> requested key
    6831              :     //
    6832              :     // Legend:
    6833              :     // * X - page images
    6834              :     // ```
    6835              :     #[tokio::test]
    6836            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6837            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6838            4 :         let (tenant, ctx) = harness.load().await;
    6839            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6840            4 : 
    6841            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6842            4 :         let end_key = start_key.add(1000);
    6843            4 :         let child_gap_at_key = start_key.add(500);
    6844            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6845            4 : 
    6846            4 :         let mut current_lsn = Lsn(0x10);
    6847            4 : 
    6848            4 :         let timeline_id = TimelineId::generate();
    6849            4 :         let parent_timeline = tenant
    6850            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6851            4 :             .await?;
    6852            4 : 
    6853            4 :         current_lsn += 0x100;
    6854            4 : 
    6855           16 :         for _ in 0..3 {
    6856           12 :             let mut key = start_key;
    6857        12012 :             while key < end_key {
    6858        12000 :                 current_lsn += 0x10;
    6859        12000 : 
    6860        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6861            4 : 
    6862        12000 :                 let mut writer = parent_timeline.writer().await;
    6863        12000 :                 writer
    6864        12000 :                     .put(
    6865        12000 :                         key,
    6866        12000 :                         current_lsn,
    6867        12000 :                         &Value::Image(test_img(&image_value)),
    6868        12000 :                         &ctx,
    6869        12000 :                     )
    6870        12000 :                     .await?;
    6871        12000 :                 writer.finish_write(current_lsn);
    6872        12000 : 
    6873        12000 :                 if key == child_gap_at_key {
    6874           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6875        11988 :                 }
    6876            4 : 
    6877        12000 :                 key = key.next();
    6878            4 :             }
    6879            4 : 
    6880           12 :             parent_timeline.freeze_and_flush().await?;
    6881            4 :         }
    6882            4 : 
    6883            4 :         let child_timeline_id = TimelineId::generate();
    6884            4 : 
    6885            4 :         let child_timeline = tenant
    6886            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6887            4 :             .await?;
    6888            4 : 
    6889            4 :         let mut key = start_key;
    6890         4004 :         while key < end_key {
    6891         4000 :             if key == child_gap_at_key {
    6892            4 :                 key = key.next();
    6893            4 :                 continue;
    6894         3996 :             }
    6895         3996 : 
    6896         3996 :             current_lsn += 0x10;
    6897            4 : 
    6898         3996 :             let mut writer = child_timeline.writer().await;
    6899         3996 :             writer
    6900         3996 :                 .put(
    6901         3996 :                     key,
    6902         3996 :                     current_lsn,
    6903         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6904         3996 :                     &ctx,
    6905         3996 :                 )
    6906         3996 :                 .await?;
    6907         3996 :             writer.finish_write(current_lsn);
    6908         3996 : 
    6909         3996 :             key = key.next();
    6910            4 :         }
    6911            4 : 
    6912            4 :         child_timeline.freeze_and_flush().await?;
    6913            4 : 
    6914            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6915            4 :         let mut query_lsns = Vec::new();
    6916           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6917           72 :             for offset in lsn_offsets {
    6918           60 :                 query_lsns.push(Lsn(image_lsn
    6919           60 :                     .0
    6920           60 :                     .checked_add_signed(offset)
    6921           60 :                     .expect("Shouldn't overflow")));
    6922           60 :             }
    6923            4 :         }
    6924            4 : 
    6925           64 :         for query_lsn in query_lsns {
    6926           60 :             let results = child_timeline
    6927           60 :                 .get_vectored_impl(
    6928           60 :                     KeySpace {
    6929           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6930           60 :                     },
    6931           60 :                     query_lsn,
    6932           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6933           60 :                     &ctx,
    6934           60 :                 )
    6935           60 :                 .await;
    6936            4 : 
    6937           60 :             let expected_item = parent_gap_lsns
    6938           60 :                 .iter()
    6939           60 :                 .rev()
    6940          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6941           60 : 
    6942           60 :             info!(
    6943            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6944            4 :                 query_lsn, expected_item
    6945            4 :             );
    6946            4 : 
    6947           60 :             match expected_item {
    6948           52 :                 Some((_, img_value)) => {
    6949           52 :                     let key_results = results.expect("No vectored get error expected");
    6950           52 :                     let key_result = &key_results[&child_gap_at_key];
    6951           52 :                     let returned_img = key_result
    6952           52 :                         .as_ref()
    6953           52 :                         .expect("No page reconstruct error expected");
    6954           52 : 
    6955           52 :                     info!(
    6956            4 :                         "Vectored read at LSN {} returned image {}",
    6957            0 :                         query_lsn,
    6958            0 :                         std::str::from_utf8(returned_img)?
    6959            4 :                     );
    6960           52 :                     assert_eq!(*returned_img, test_img(img_value));
    6961            4 :                 }
    6962            4 :                 None => {
    6963            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6964            4 :                 }
    6965            4 :             }
    6966            4 :         }
    6967            4 : 
    6968            4 :         Ok(())
    6969            4 :     }
    6970              : 
    6971              :     #[tokio::test]
    6972            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    6973            4 :         let names_algorithms = [
    6974            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    6975            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    6976            4 :         ];
    6977           12 :         for (name, algorithm) in names_algorithms {
    6978            8 :             test_random_updates_algorithm(name, algorithm).await?;
    6979            4 :         }
    6980            4 :         Ok(())
    6981            4 :     }
    6982              : 
    6983            8 :     async fn test_random_updates_algorithm(
    6984            8 :         name: &'static str,
    6985            8 :         compaction_algorithm: CompactionAlgorithm,
    6986            8 :     ) -> anyhow::Result<()> {
    6987            8 :         let mut harness = TenantHarness::create(name).await?;
    6988            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6989            8 :             kind: compaction_algorithm,
    6990            8 :         };
    6991            8 :         let (tenant, ctx) = harness.load().await;
    6992            8 :         let tline = tenant
    6993            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6994            8 :             .await?;
    6995              : 
    6996              :         const NUM_KEYS: usize = 1000;
    6997            8 :         let cancel = CancellationToken::new();
    6998            8 : 
    6999            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7000            8 :         let mut test_key_end = test_key;
    7001            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7002            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7003            8 : 
    7004            8 :         let mut keyspace = KeySpaceAccum::new();
    7005            8 : 
    7006            8 :         // Track when each page was last modified. Used to assert that
    7007            8 :         // a read sees the latest page version.
    7008            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7009            8 : 
    7010            8 :         let mut lsn = Lsn(0x10);
    7011              :         #[allow(clippy::needless_range_loop)]
    7012         8008 :         for blknum in 0..NUM_KEYS {
    7013         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7014         8000 :             test_key.field6 = blknum as u32;
    7015         8000 :             let mut writer = tline.writer().await;
    7016         8000 :             writer
    7017         8000 :                 .put(
    7018         8000 :                     test_key,
    7019         8000 :                     lsn,
    7020         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7021         8000 :                     &ctx,
    7022         8000 :                 )
    7023         8000 :                 .await?;
    7024         8000 :             writer.finish_write(lsn);
    7025         8000 :             updated[blknum] = lsn;
    7026         8000 :             drop(writer);
    7027         8000 : 
    7028         8000 :             keyspace.add_key(test_key);
    7029              :         }
    7030              : 
    7031          408 :         for _ in 0..50 {
    7032       400400 :             for _ in 0..NUM_KEYS {
    7033       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7034       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7035       400000 :                 test_key.field6 = blknum as u32;
    7036       400000 :                 let mut writer = tline.writer().await;
    7037       400000 :                 writer
    7038       400000 :                     .put(
    7039       400000 :                         test_key,
    7040       400000 :                         lsn,
    7041       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7042       400000 :                         &ctx,
    7043       400000 :                     )
    7044       400000 :                     .await?;
    7045       400000 :                 writer.finish_write(lsn);
    7046       400000 :                 drop(writer);
    7047       400000 :                 updated[blknum] = lsn;
    7048              :             }
    7049              : 
    7050              :             // Read all the blocks
    7051       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7052       400000 :                 test_key.field6 = blknum as u32;
    7053       400000 :                 assert_eq!(
    7054       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7055       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7056              :                 );
    7057              :             }
    7058              : 
    7059              :             // Perform a cycle of flush, and GC
    7060          400 :             tline.freeze_and_flush().await?;
    7061          400 :             tenant
    7062          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7063          400 :                 .await?;
    7064              :         }
    7065              : 
    7066            8 :         Ok(())
    7067            8 :     }
    7068              : 
    7069              :     #[tokio::test]
    7070            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7071            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7072            4 :             .await?
    7073            4 :             .load()
    7074            4 :             .await;
    7075            4 :         let mut tline = tenant
    7076            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7077            4 :             .await?;
    7078            4 : 
    7079            4 :         const NUM_KEYS: usize = 1000;
    7080            4 : 
    7081            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7082            4 : 
    7083            4 :         let mut keyspace = KeySpaceAccum::new();
    7084            4 : 
    7085            4 :         let cancel = CancellationToken::new();
    7086            4 : 
    7087            4 :         // Track when each page was last modified. Used to assert that
    7088            4 :         // a read sees the latest page version.
    7089            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7090            4 : 
    7091            4 :         let mut lsn = Lsn(0x10);
    7092            4 :         #[allow(clippy::needless_range_loop)]
    7093         4004 :         for blknum in 0..NUM_KEYS {
    7094         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7095         4000 :             test_key.field6 = blknum as u32;
    7096         4000 :             let mut writer = tline.writer().await;
    7097         4000 :             writer
    7098         4000 :                 .put(
    7099         4000 :                     test_key,
    7100         4000 :                     lsn,
    7101         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7102         4000 :                     &ctx,
    7103         4000 :                 )
    7104         4000 :                 .await?;
    7105         4000 :             writer.finish_write(lsn);
    7106         4000 :             updated[blknum] = lsn;
    7107         4000 :             drop(writer);
    7108         4000 : 
    7109         4000 :             keyspace.add_key(test_key);
    7110            4 :         }
    7111            4 : 
    7112          204 :         for _ in 0..50 {
    7113          200 :             let new_tline_id = TimelineId::generate();
    7114          200 :             tenant
    7115          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7116          200 :                 .await?;
    7117          200 :             tline = tenant
    7118          200 :                 .get_timeline(new_tline_id, true)
    7119          200 :                 .expect("Should have the branched timeline");
    7120            4 : 
    7121       200200 :             for _ in 0..NUM_KEYS {
    7122       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7123       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7124       200000 :                 test_key.field6 = blknum as u32;
    7125       200000 :                 let mut writer = tline.writer().await;
    7126       200000 :                 writer
    7127       200000 :                     .put(
    7128       200000 :                         test_key,
    7129       200000 :                         lsn,
    7130       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7131       200000 :                         &ctx,
    7132       200000 :                     )
    7133       200000 :                     .await?;
    7134       200000 :                 println!("updating {} at {}", blknum, lsn);
    7135       200000 :                 writer.finish_write(lsn);
    7136       200000 :                 drop(writer);
    7137       200000 :                 updated[blknum] = lsn;
    7138            4 :             }
    7139            4 : 
    7140            4 :             // Read all the blocks
    7141       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7142       200000 :                 test_key.field6 = blknum as u32;
    7143       200000 :                 assert_eq!(
    7144       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7145       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7146            4 :                 );
    7147            4 :             }
    7148            4 : 
    7149            4 :             // Perform a cycle of flush, compact, and GC
    7150          200 :             tline.freeze_and_flush().await?;
    7151          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7152          200 :             tenant
    7153          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7154          200 :                 .await?;
    7155            4 :         }
    7156            4 : 
    7157            4 :         Ok(())
    7158            4 :     }
    7159              : 
    7160              :     #[tokio::test]
    7161            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7162            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7163            4 :             .await?
    7164            4 :             .load()
    7165            4 :             .await;
    7166            4 :         let mut tline = tenant
    7167            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7168            4 :             .await?;
    7169            4 : 
    7170            4 :         const NUM_KEYS: usize = 100;
    7171            4 :         const NUM_TLINES: usize = 50;
    7172            4 : 
    7173            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7174            4 :         // Track page mutation lsns across different timelines.
    7175            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7176            4 : 
    7177            4 :         let mut lsn = Lsn(0x10);
    7178            4 : 
    7179            4 :         #[allow(clippy::needless_range_loop)]
    7180          204 :         for idx in 0..NUM_TLINES {
    7181          200 :             let new_tline_id = TimelineId::generate();
    7182          200 :             tenant
    7183          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7184          200 :                 .await?;
    7185          200 :             tline = tenant
    7186          200 :                 .get_timeline(new_tline_id, true)
    7187          200 :                 .expect("Should have the branched timeline");
    7188            4 : 
    7189        20200 :             for _ in 0..NUM_KEYS {
    7190        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7191        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7192        20000 :                 test_key.field6 = blknum as u32;
    7193        20000 :                 let mut writer = tline.writer().await;
    7194        20000 :                 writer
    7195        20000 :                     .put(
    7196        20000 :                         test_key,
    7197        20000 :                         lsn,
    7198        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7199        20000 :                         &ctx,
    7200        20000 :                     )
    7201        20000 :                     .await?;
    7202        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7203        20000 :                 writer.finish_write(lsn);
    7204        20000 :                 drop(writer);
    7205        20000 :                 updated[idx][blknum] = lsn;
    7206            4 :             }
    7207            4 :         }
    7208            4 : 
    7209            4 :         // Read pages from leaf timeline across all ancestors.
    7210          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7211        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7212            4 :                 // Skip empty mutations.
    7213        20000 :                 if lsn.0 == 0 {
    7214         7315 :                     continue;
    7215        12685 :                 }
    7216        12685 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7217        12685 :                 test_key.field6 = blknum as u32;
    7218        12685 :                 assert_eq!(
    7219        12685 :                     tline.get(test_key, *lsn, &ctx).await?,
    7220        12685 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7221            4 :                 );
    7222            4 :             }
    7223            4 :         }
    7224            4 :         Ok(())
    7225            4 :     }
    7226              : 
    7227              :     #[tokio::test]
    7228            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7229            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7230            4 :             .await?
    7231            4 :             .load()
    7232            4 :             .await;
    7233            4 : 
    7234            4 :         let initdb_lsn = Lsn(0x20);
    7235            4 :         let utline = tenant
    7236            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7237            4 :             .await?;
    7238            4 :         let tline = utline.raw_timeline().unwrap();
    7239            4 : 
    7240            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7241            4 :         tline.maybe_spawn_flush_loop();
    7242            4 : 
    7243            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7244            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7245            4 :         // Except if you `put` at `initdb_lsn`.
    7246            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7247            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7248            4 :         // Let's make sure the test timeline can handle that case.
    7249            4 :         {
    7250            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7251            4 :             assert_eq!(
    7252            4 :                 timeline::FlushLoopState::Running {
    7253            4 :                     expect_initdb_optimization: false,
    7254            4 :                     initdb_optimization_count: 0,
    7255            4 :                 },
    7256            4 :                 *state
    7257            4 :             );
    7258            4 :             *state = timeline::FlushLoopState::Running {
    7259            4 :                 expect_initdb_optimization: true,
    7260            4 :                 initdb_optimization_count: 0,
    7261            4 :             };
    7262            4 :         }
    7263            4 : 
    7264            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7265            4 :         // As explained above, the optimization requires some keys to be present.
    7266            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7267            4 :         // This is what `create_test_timeline` does, by the way.
    7268            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7269            4 :         modification
    7270            4 :             .init_empty_test_timeline()
    7271            4 :             .context("init_empty_test_timeline")?;
    7272            4 :         modification
    7273            4 :             .commit(&ctx)
    7274            4 :             .await
    7275            4 :             .context("commit init_empty_test_timeline modification")?;
    7276            4 : 
    7277            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7278            4 :         tline.freeze_and_flush().await?;
    7279            4 : 
    7280            4 :         // assert freeze_and_flush exercised the initdb optimization
    7281            4 :         {
    7282            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7283            4 :             let timeline::FlushLoopState::Running {
    7284            4 :                 expect_initdb_optimization,
    7285            4 :                 initdb_optimization_count,
    7286            4 :             } = *state
    7287            4 :             else {
    7288            4 :                 panic!("unexpected state: {:?}", *state);
    7289            4 :             };
    7290            4 :             assert!(expect_initdb_optimization);
    7291            4 :             assert!(initdb_optimization_count > 0);
    7292            4 :         }
    7293            4 :         Ok(())
    7294            4 :     }
    7295              : 
    7296              :     #[tokio::test]
    7297            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7298            4 :         let name = "test_create_guard_crash";
    7299            4 :         let harness = TenantHarness::create(name).await?;
    7300            4 :         {
    7301            4 :             let (tenant, ctx) = harness.load().await;
    7302            4 :             let tline = tenant
    7303            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7304            4 :                 .await?;
    7305            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7306            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7307            4 :             raw_tline
    7308            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7309            4 :                 .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))
    7310            4 :                 .await;
    7311            4 :             std::mem::forget(tline);
    7312            4 :         }
    7313            4 : 
    7314            4 :         let (tenant, _) = harness.load().await;
    7315            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7316            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7317            4 :             Err(e) => {
    7318            4 :                 assert_eq!(
    7319            4 :                     e,
    7320            4 :                     GetTimelineError::NotFound {
    7321            4 :                         tenant_id: tenant.tenant_shard_id,
    7322            4 :                         timeline_id: TIMELINE_ID,
    7323            4 :                     }
    7324            4 :                 )
    7325            4 :             }
    7326            4 :         }
    7327            4 : 
    7328            4 :         assert!(!harness
    7329            4 :             .conf
    7330            4 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7331            4 :             .exists());
    7332            4 : 
    7333            4 :         Ok(())
    7334            4 :     }
    7335              : 
    7336              :     #[tokio::test]
    7337            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7338            4 :         let names_algorithms = [
    7339            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7340            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7341            4 :         ];
    7342           12 :         for (name, algorithm) in names_algorithms {
    7343            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7344            4 :         }
    7345            4 :         Ok(())
    7346            4 :     }
    7347              : 
    7348            8 :     async fn test_read_at_max_lsn_algorithm(
    7349            8 :         name: &'static str,
    7350            8 :         compaction_algorithm: CompactionAlgorithm,
    7351            8 :     ) -> anyhow::Result<()> {
    7352            8 :         let mut harness = TenantHarness::create(name).await?;
    7353            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7354            8 :             kind: compaction_algorithm,
    7355            8 :         };
    7356            8 :         let (tenant, ctx) = harness.load().await;
    7357            8 :         let tline = tenant
    7358            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7359            8 :             .await?;
    7360              : 
    7361            8 :         let lsn = Lsn(0x10);
    7362            8 :         let compact = false;
    7363            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7364              : 
    7365            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7366            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7367              : 
    7368            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7369            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7370              : 
    7371            8 :         Ok(())
    7372            8 :     }
    7373              : 
    7374              :     #[tokio::test]
    7375            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7376            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7377            4 :         let (tenant, ctx) = harness.load().await;
    7378            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7379            4 :         let tline = tenant
    7380            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7381            4 :             .await?;
    7382            4 : 
    7383            4 :         const NUM_KEYS: usize = 1000;
    7384            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7385            4 : 
    7386            4 :         let cancel = CancellationToken::new();
    7387            4 : 
    7388            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7389            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7390            4 :         let mut test_key = base_key;
    7391            4 : 
    7392            4 :         // Track when each page was last modified. Used to assert that
    7393            4 :         // a read sees the latest page version.
    7394            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7395            4 : 
    7396            4 :         let mut lsn = Lsn(0x10);
    7397            4 :         #[allow(clippy::needless_range_loop)]
    7398         4004 :         for blknum in 0..NUM_KEYS {
    7399         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7400         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7401         4000 :             let mut writer = tline.writer().await;
    7402         4000 :             writer
    7403         4000 :                 .put(
    7404         4000 :                     test_key,
    7405         4000 :                     lsn,
    7406         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7407         4000 :                     &ctx,
    7408         4000 :                 )
    7409         4000 :                 .await?;
    7410         4000 :             writer.finish_write(lsn);
    7411         4000 :             updated[blknum] = lsn;
    7412         4000 :             drop(writer);
    7413            4 :         }
    7414            4 : 
    7415            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7416            4 : 
    7417           48 :         for iter in 0..=10 {
    7418            4 :             // Read all the blocks
    7419        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7420        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7421        44000 :                 assert_eq!(
    7422        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7423        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7424            4 :                 );
    7425            4 :             }
    7426            4 : 
    7427           44 :             let mut cnt = 0;
    7428        44000 :             for (key, value) in tline
    7429           44 :                 .get_vectored_impl(
    7430           44 :                     keyspace.clone(),
    7431           44 :                     lsn,
    7432           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7433           44 :                     &ctx,
    7434           44 :                 )
    7435           44 :                 .await?
    7436            4 :             {
    7437        44000 :                 let blknum = key.field6 as usize;
    7438        44000 :                 let value = value?;
    7439        44000 :                 assert!(blknum % STEP == 0);
    7440        44000 :                 let blknum = blknum / STEP;
    7441        44000 :                 assert_eq!(
    7442        44000 :                     value,
    7443        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7444        44000 :                 );
    7445        44000 :                 cnt += 1;
    7446            4 :             }
    7447            4 : 
    7448           44 :             assert_eq!(cnt, NUM_KEYS);
    7449            4 : 
    7450        44044 :             for _ in 0..NUM_KEYS {
    7451        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7452        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7453        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7454        44000 :                 let mut writer = tline.writer().await;
    7455        44000 :                 writer
    7456        44000 :                     .put(
    7457        44000 :                         test_key,
    7458        44000 :                         lsn,
    7459        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7460        44000 :                         &ctx,
    7461        44000 :                     )
    7462        44000 :                     .await?;
    7463        44000 :                 writer.finish_write(lsn);
    7464        44000 :                 drop(writer);
    7465        44000 :                 updated[blknum] = lsn;
    7466            4 :             }
    7467            4 : 
    7468            4 :             // Perform two cycles of flush, compact, and GC
    7469          132 :             for round in 0..2 {
    7470           88 :                 tline.freeze_and_flush().await?;
    7471           88 :                 tline
    7472           88 :                     .compact(
    7473           88 :                         &cancel,
    7474           88 :                         if iter % 5 == 0 && round == 0 {
    7475           12 :                             let mut flags = EnumSet::new();
    7476           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7477           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7478           12 :                             flags
    7479            4 :                         } else {
    7480           76 :                             EnumSet::empty()
    7481            4 :                         },
    7482           88 :                         &ctx,
    7483           88 :                     )
    7484           88 :                     .await?;
    7485           88 :                 tenant
    7486           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7487           88 :                     .await?;
    7488            4 :             }
    7489            4 :         }
    7490            4 : 
    7491            4 :         Ok(())
    7492            4 :     }
    7493              : 
    7494              :     #[tokio::test]
    7495            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7496            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7497            4 :         let (tenant, ctx) = harness.load().await;
    7498            4 :         let tline = tenant
    7499            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7500            4 :             .await?;
    7501            4 : 
    7502            4 :         let cancel = CancellationToken::new();
    7503            4 : 
    7504            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7505            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7506            4 :         let test_key = base_key;
    7507            4 :         let mut lsn = Lsn(0x10);
    7508            4 : 
    7509           84 :         for _ in 0..20 {
    7510           80 :             lsn = Lsn(lsn.0 + 0x10);
    7511           80 :             let mut writer = tline.writer().await;
    7512           80 :             writer
    7513           80 :                 .put(
    7514           80 :                     test_key,
    7515           80 :                     lsn,
    7516           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7517           80 :                     &ctx,
    7518           80 :                 )
    7519           80 :                 .await?;
    7520           80 :             writer.finish_write(lsn);
    7521           80 :             drop(writer);
    7522           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7523            4 :         }
    7524            4 : 
    7525            4 :         let before_num_l0_delta_files =
    7526            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7527            4 : 
    7528            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7529            4 : 
    7530            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7531            4 : 
    7532            4 :         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}");
    7533            4 : 
    7534            4 :         assert_eq!(
    7535            4 :             tline.get(test_key, lsn, &ctx).await?,
    7536            4 :             test_img(&format!("{} at {}", 0, lsn))
    7537            4 :         );
    7538            4 : 
    7539            4 :         Ok(())
    7540            4 :     }
    7541              : 
    7542              :     #[tokio::test]
    7543            4 :     async fn test_aux_file_e2e() {
    7544            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7545            4 : 
    7546            4 :         let (tenant, ctx) = harness.load().await;
    7547            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7548            4 : 
    7549            4 :         let mut lsn = Lsn(0x08);
    7550            4 : 
    7551            4 :         let tline: Arc<Timeline> = tenant
    7552            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7553            4 :             .await
    7554            4 :             .unwrap();
    7555            4 : 
    7556            4 :         {
    7557            4 :             lsn += 8;
    7558            4 :             let mut modification = tline.begin_modification(lsn);
    7559            4 :             modification
    7560            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7561            4 :                 .await
    7562            4 :                 .unwrap();
    7563            4 :             modification.commit(&ctx).await.unwrap();
    7564            4 :         }
    7565            4 : 
    7566            4 :         // we can read everything from the storage
    7567            4 :         let files = tline
    7568            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7569            4 :             .await
    7570            4 :             .unwrap();
    7571            4 :         assert_eq!(
    7572            4 :             files.get("pg_logical/mappings/test1"),
    7573            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7574            4 :         );
    7575            4 : 
    7576            4 :         {
    7577            4 :             lsn += 8;
    7578            4 :             let mut modification = tline.begin_modification(lsn);
    7579            4 :             modification
    7580            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7581            4 :                 .await
    7582            4 :                 .unwrap();
    7583            4 :             modification.commit(&ctx).await.unwrap();
    7584            4 :         }
    7585            4 : 
    7586            4 :         let files = tline
    7587            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7588            4 :             .await
    7589            4 :             .unwrap();
    7590            4 :         assert_eq!(
    7591            4 :             files.get("pg_logical/mappings/test2"),
    7592            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7593            4 :         );
    7594            4 : 
    7595            4 :         let child = tenant
    7596            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7597            4 :             .await
    7598            4 :             .unwrap();
    7599            4 : 
    7600            4 :         let files = child
    7601            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7602            4 :             .await
    7603            4 :             .unwrap();
    7604            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7605            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7606            4 :     }
    7607              : 
    7608              :     #[tokio::test]
    7609            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7610            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7611            4 :         let (tenant, ctx) = harness.load().await;
    7612            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7613            4 :         let tline = tenant
    7614            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7615            4 :             .await?;
    7616            4 : 
    7617            4 :         const NUM_KEYS: usize = 1000;
    7618            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7619            4 : 
    7620            4 :         let cancel = CancellationToken::new();
    7621            4 : 
    7622            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7623            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7624            4 :         let mut test_key = base_key;
    7625            4 :         let mut lsn = Lsn(0x10);
    7626            4 : 
    7627           16 :         async fn scan_with_statistics(
    7628           16 :             tline: &Timeline,
    7629           16 :             keyspace: &KeySpace,
    7630           16 :             lsn: Lsn,
    7631           16 :             ctx: &RequestContext,
    7632           16 :             io_concurrency: IoConcurrency,
    7633           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7634           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7635           16 :             let res = tline
    7636           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7637           16 :                 .await?;
    7638           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7639           16 :         }
    7640            4 : 
    7641            4 :         #[allow(clippy::needless_range_loop)]
    7642         4004 :         for blknum in 0..NUM_KEYS {
    7643         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7644         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7645         4000 :             let mut writer = tline.writer().await;
    7646         4000 :             writer
    7647         4000 :                 .put(
    7648         4000 :                     test_key,
    7649         4000 :                     lsn,
    7650         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7651         4000 :                     &ctx,
    7652         4000 :                 )
    7653         4000 :                 .await?;
    7654         4000 :             writer.finish_write(lsn);
    7655         4000 :             drop(writer);
    7656            4 :         }
    7657            4 : 
    7658            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7659            4 : 
    7660           44 :         for iter in 1..=10 {
    7661        40040 :             for _ in 0..NUM_KEYS {
    7662        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7663        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7664        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7665        40000 :                 let mut writer = tline.writer().await;
    7666        40000 :                 writer
    7667        40000 :                     .put(
    7668        40000 :                         test_key,
    7669        40000 :                         lsn,
    7670        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7671        40000 :                         &ctx,
    7672        40000 :                     )
    7673        40000 :                     .await?;
    7674        40000 :                 writer.finish_write(lsn);
    7675        40000 :                 drop(writer);
    7676            4 :             }
    7677            4 : 
    7678           40 :             tline.freeze_and_flush().await?;
    7679            4 : 
    7680           40 :             if iter % 5 == 0 {
    7681            8 :                 let (_, before_delta_file_accessed) =
    7682            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7683            8 :                         .await?;
    7684            8 :                 tline
    7685            8 :                     .compact(
    7686            8 :                         &cancel,
    7687            8 :                         {
    7688            8 :                             let mut flags = EnumSet::new();
    7689            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7690            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7691            8 :                             flags
    7692            8 :                         },
    7693            8 :                         &ctx,
    7694            8 :                     )
    7695            8 :                     .await?;
    7696            8 :                 let (_, after_delta_file_accessed) =
    7697            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7698            8 :                         .await?;
    7699            8 :                 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}");
    7700            4 :                 // 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.
    7701            8 :                 assert!(
    7702            8 :                     after_delta_file_accessed <= 2,
    7703            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7704            4 :                 );
    7705           32 :             }
    7706            4 :         }
    7707            4 : 
    7708            4 :         Ok(())
    7709            4 :     }
    7710              : 
    7711              :     #[tokio::test]
    7712            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7713            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7714            4 :         let (tenant, ctx) = harness.load().await;
    7715            4 : 
    7716            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7717            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7718            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7719            4 : 
    7720            4 :         let tline = tenant
    7721            4 :             .create_test_timeline_with_layers(
    7722            4 :                 TIMELINE_ID,
    7723            4 :                 Lsn(0x10),
    7724            4 :                 DEFAULT_PG_VERSION,
    7725            4 :                 &ctx,
    7726            4 :                 Vec::new(), // delta layers
    7727            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7728            4 :                 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
    7729            4 :             )
    7730            4 :             .await?;
    7731            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7732            4 : 
    7733            4 :         let child = tenant
    7734            4 :             .branch_timeline_test_with_layers(
    7735            4 :                 &tline,
    7736            4 :                 NEW_TIMELINE_ID,
    7737            4 :                 Some(Lsn(0x20)),
    7738            4 :                 &ctx,
    7739            4 :                 Vec::new(), // delta layers
    7740            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7741            4 :                 Lsn(0x30),
    7742            4 :             )
    7743            4 :             .await
    7744            4 :             .unwrap();
    7745            4 : 
    7746            4 :         let lsn = Lsn(0x30);
    7747            4 : 
    7748            4 :         // test vectored get on parent timeline
    7749            4 :         assert_eq!(
    7750            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7751            4 :             Some(test_img("data key 1"))
    7752            4 :         );
    7753            4 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7754            4 :             .await
    7755            4 :             .unwrap_err()
    7756            4 :             .is_missing_key_error());
    7757            4 :         assert!(
    7758            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7759            4 :                 .await
    7760            4 :                 .unwrap_err()
    7761            4 :                 .is_missing_key_error()
    7762            4 :         );
    7763            4 : 
    7764            4 :         // test vectored get on child timeline
    7765            4 :         assert_eq!(
    7766            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7767            4 :             Some(test_img("data key 1"))
    7768            4 :         );
    7769            4 :         assert_eq!(
    7770            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7771            4 :             Some(test_img("data key 2"))
    7772            4 :         );
    7773            4 :         assert!(
    7774            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7775            4 :                 .await
    7776            4 :                 .unwrap_err()
    7777            4 :                 .is_missing_key_error()
    7778            4 :         );
    7779            4 : 
    7780            4 :         Ok(())
    7781            4 :     }
    7782              : 
    7783              :     #[tokio::test]
    7784            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7785            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7786            4 :         let (tenant, ctx) = harness.load().await;
    7787            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7788            4 : 
    7789            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7790            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7791            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7792            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7793            4 : 
    7794            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    7795            4 :         let base_inherited_key_child =
    7796            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    7797            4 :         let base_inherited_key_nonexist =
    7798            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    7799            4 :         let base_inherited_key_overwrite =
    7800            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    7801            4 : 
    7802            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7803            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    7804            4 : 
    7805            4 :         let tline = tenant
    7806            4 :             .create_test_timeline_with_layers(
    7807            4 :                 TIMELINE_ID,
    7808            4 :                 Lsn(0x10),
    7809            4 :                 DEFAULT_PG_VERSION,
    7810            4 :                 &ctx,
    7811            4 :                 Vec::new(), // delta layers
    7812            4 :                 vec![(
    7813            4 :                     Lsn(0x20),
    7814            4 :                     vec![
    7815            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    7816            4 :                         (
    7817            4 :                             base_inherited_key_overwrite,
    7818            4 :                             test_img("metadata key overwrite 1a"),
    7819            4 :                         ),
    7820            4 :                         (base_key, test_img("metadata key 1")),
    7821            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7822            4 :                     ],
    7823            4 :                 )], // image layers
    7824            4 :                 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
    7825            4 :             )
    7826            4 :             .await?;
    7827            4 : 
    7828            4 :         let child = tenant
    7829            4 :             .branch_timeline_test_with_layers(
    7830            4 :                 &tline,
    7831            4 :                 NEW_TIMELINE_ID,
    7832            4 :                 Some(Lsn(0x20)),
    7833            4 :                 &ctx,
    7834            4 :                 Vec::new(), // delta layers
    7835            4 :                 vec![(
    7836            4 :                     Lsn(0x30),
    7837            4 :                     vec![
    7838            4 :                         (
    7839            4 :                             base_inherited_key_child,
    7840            4 :                             test_img("metadata inherited key 2"),
    7841            4 :                         ),
    7842            4 :                         (
    7843            4 :                             base_inherited_key_overwrite,
    7844            4 :                             test_img("metadata key overwrite 2a"),
    7845            4 :                         ),
    7846            4 :                         (base_key_child, test_img("metadata key 2")),
    7847            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    7848            4 :                     ],
    7849            4 :                 )], // image layers
    7850            4 :                 Lsn(0x30),
    7851            4 :             )
    7852            4 :             .await
    7853            4 :             .unwrap();
    7854            4 : 
    7855            4 :         let lsn = Lsn(0x30);
    7856            4 : 
    7857            4 :         // test vectored get on parent timeline
    7858            4 :         assert_eq!(
    7859            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7860            4 :             Some(test_img("metadata key 1"))
    7861            4 :         );
    7862            4 :         assert_eq!(
    7863            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7864            4 :             None
    7865            4 :         );
    7866            4 :         assert_eq!(
    7867            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7868            4 :             None
    7869            4 :         );
    7870            4 :         assert_eq!(
    7871            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    7872            4 :             Some(test_img("metadata key overwrite 1b"))
    7873            4 :         );
    7874            4 :         assert_eq!(
    7875            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    7876            4 :             Some(test_img("metadata inherited key 1"))
    7877            4 :         );
    7878            4 :         assert_eq!(
    7879            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    7880            4 :             None
    7881            4 :         );
    7882            4 :         assert_eq!(
    7883            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    7884            4 :             None
    7885            4 :         );
    7886            4 :         assert_eq!(
    7887            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    7888            4 :             Some(test_img("metadata key overwrite 1a"))
    7889            4 :         );
    7890            4 : 
    7891            4 :         // test vectored get on child timeline
    7892            4 :         assert_eq!(
    7893            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7894            4 :             None
    7895            4 :         );
    7896            4 :         assert_eq!(
    7897            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7898            4 :             Some(test_img("metadata key 2"))
    7899            4 :         );
    7900            4 :         assert_eq!(
    7901            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7902            4 :             None
    7903            4 :         );
    7904            4 :         assert_eq!(
    7905            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    7906            4 :             Some(test_img("metadata inherited key 1"))
    7907            4 :         );
    7908            4 :         assert_eq!(
    7909            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    7910            4 :             Some(test_img("metadata inherited key 2"))
    7911            4 :         );
    7912            4 :         assert_eq!(
    7913            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    7914            4 :             None
    7915            4 :         );
    7916            4 :         assert_eq!(
    7917            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    7918            4 :             Some(test_img("metadata key overwrite 2b"))
    7919            4 :         );
    7920            4 :         assert_eq!(
    7921            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    7922            4 :             Some(test_img("metadata key overwrite 2a"))
    7923            4 :         );
    7924            4 : 
    7925            4 :         // test vectored scan on parent timeline
    7926            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    7927            4 :         let res = tline
    7928            4 :             .get_vectored_impl(
    7929            4 :                 KeySpace::single(Key::metadata_key_range()),
    7930            4 :                 lsn,
    7931            4 :                 &mut reconstruct_state,
    7932            4 :                 &ctx,
    7933            4 :             )
    7934            4 :             .await?;
    7935            4 : 
    7936            4 :         assert_eq!(
    7937            4 :             res.into_iter()
    7938           16 :                 .map(|(k, v)| (k, v.unwrap()))
    7939            4 :                 .collect::<Vec<_>>(),
    7940            4 :             vec![
    7941            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    7942            4 :                 (
    7943            4 :                     base_inherited_key_overwrite,
    7944            4 :                     test_img("metadata key overwrite 1a")
    7945            4 :                 ),
    7946            4 :                 (base_key, test_img("metadata key 1")),
    7947            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7948            4 :             ]
    7949            4 :         );
    7950            4 : 
    7951            4 :         // test vectored scan on child timeline
    7952            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    7953            4 :         let res = child
    7954            4 :             .get_vectored_impl(
    7955            4 :                 KeySpace::single(Key::metadata_key_range()),
    7956            4 :                 lsn,
    7957            4 :                 &mut reconstruct_state,
    7958            4 :                 &ctx,
    7959            4 :             )
    7960            4 :             .await?;
    7961            4 : 
    7962            4 :         assert_eq!(
    7963            4 :             res.into_iter()
    7964           20 :                 .map(|(k, v)| (k, v.unwrap()))
    7965            4 :                 .collect::<Vec<_>>(),
    7966            4 :             vec![
    7967            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    7968            4 :                 (
    7969            4 :                     base_inherited_key_child,
    7970            4 :                     test_img("metadata inherited key 2")
    7971            4 :                 ),
    7972            4 :                 (
    7973            4 :                     base_inherited_key_overwrite,
    7974            4 :                     test_img("metadata key overwrite 2a")
    7975            4 :                 ),
    7976            4 :                 (base_key_child, test_img("metadata key 2")),
    7977            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    7978            4 :             ]
    7979            4 :         );
    7980            4 : 
    7981            4 :         Ok(())
    7982            4 :     }
    7983              : 
    7984          112 :     async fn get_vectored_impl_wrapper(
    7985          112 :         tline: &Arc<Timeline>,
    7986          112 :         key: Key,
    7987          112 :         lsn: Lsn,
    7988          112 :         ctx: &RequestContext,
    7989          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7990          112 :         let io_concurrency =
    7991          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    7992          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7993          112 :         let mut res = tline
    7994          112 :             .get_vectored_impl(
    7995          112 :                 KeySpace::single(key..key.next()),
    7996          112 :                 lsn,
    7997          112 :                 &mut reconstruct_state,
    7998          112 :                 ctx,
    7999          112 :             )
    8000          112 :             .await?;
    8001          100 :         Ok(res.pop_last().map(|(k, v)| {
    8002           64 :             assert_eq!(k, key);
    8003           64 :             v.unwrap()
    8004          100 :         }))
    8005          112 :     }
    8006              : 
    8007              :     #[tokio::test]
    8008            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8009            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8010            4 :         let (tenant, ctx) = harness.load().await;
    8011            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8012            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8013            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8014            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8015            4 : 
    8016            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8017            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8018            4 :         // Lsn 0x20 key1+key2 tomestones
    8019            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8020            4 :         let tline = tenant
    8021            4 :             .create_test_timeline_with_layers(
    8022            4 :                 TIMELINE_ID,
    8023            4 :                 Lsn(0x10),
    8024            4 :                 DEFAULT_PG_VERSION,
    8025            4 :                 &ctx,
    8026            4 :                 // delta layers
    8027            4 :                 vec![
    8028            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8029            4 :                         Lsn(0x10)..Lsn(0x20),
    8030            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8031            4 :                     ),
    8032            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8033            4 :                         Lsn(0x20)..Lsn(0x30),
    8034            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8035            4 :                     ),
    8036            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8037            4 :                         Lsn(0x20)..Lsn(0x30),
    8038            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8039            4 :                     ),
    8040            4 :                 ],
    8041            4 :                 // image layers
    8042            4 :                 vec![
    8043            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8044            4 :                     (
    8045            4 :                         Lsn(0x30),
    8046            4 :                         vec![
    8047            4 :                             (key0, test_img("metadata key 0")),
    8048            4 :                             (key3, test_img("metadata key 3")),
    8049            4 :                         ],
    8050            4 :                     ),
    8051            4 :                 ],
    8052            4 :                 Lsn(0x30),
    8053            4 :             )
    8054            4 :             .await?;
    8055            4 : 
    8056            4 :         let lsn = Lsn(0x30);
    8057            4 :         let old_lsn = Lsn(0x20);
    8058            4 : 
    8059            4 :         assert_eq!(
    8060            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8061            4 :             Some(test_img("metadata key 0"))
    8062            4 :         );
    8063            4 :         assert_eq!(
    8064            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8065            4 :             None,
    8066            4 :         );
    8067            4 :         assert_eq!(
    8068            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8069            4 :             None,
    8070            4 :         );
    8071            4 :         assert_eq!(
    8072            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8073            4 :             Some(Bytes::new()),
    8074            4 :         );
    8075            4 :         assert_eq!(
    8076            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8077            4 :             Some(Bytes::new()),
    8078            4 :         );
    8079            4 :         assert_eq!(
    8080            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8081            4 :             Some(test_img("metadata key 3"))
    8082            4 :         );
    8083            4 : 
    8084            4 :         Ok(())
    8085            4 :     }
    8086              : 
    8087              :     #[tokio::test]
    8088            4 :     async fn test_metadata_tombstone_image_creation() {
    8089            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8090            4 :             .await
    8091            4 :             .unwrap();
    8092            4 :         let (tenant, ctx) = harness.load().await;
    8093            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8094            4 : 
    8095            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8096            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8097            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8098            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8099            4 : 
    8100            4 :         let tline = tenant
    8101            4 :             .create_test_timeline_with_layers(
    8102            4 :                 TIMELINE_ID,
    8103            4 :                 Lsn(0x10),
    8104            4 :                 DEFAULT_PG_VERSION,
    8105            4 :                 &ctx,
    8106            4 :                 // delta layers
    8107            4 :                 vec![
    8108            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8109            4 :                         Lsn(0x10)..Lsn(0x20),
    8110            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8111            4 :                     ),
    8112            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8113            4 :                         Lsn(0x20)..Lsn(0x30),
    8114            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8115            4 :                     ),
    8116            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8117            4 :                         Lsn(0x20)..Lsn(0x30),
    8118            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8119            4 :                     ),
    8120            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8121            4 :                         Lsn(0x30)..Lsn(0x40),
    8122            4 :                         vec![
    8123            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8124            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8125            4 :                         ],
    8126            4 :                     ),
    8127            4 :                 ],
    8128            4 :                 // image layers
    8129            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8130            4 :                 Lsn(0x40),
    8131            4 :             )
    8132            4 :             .await
    8133            4 :             .unwrap();
    8134            4 : 
    8135            4 :         let cancel = CancellationToken::new();
    8136            4 : 
    8137            4 :         tline
    8138            4 :             .compact(
    8139            4 :                 &cancel,
    8140            4 :                 {
    8141            4 :                     let mut flags = EnumSet::new();
    8142            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8143            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8144            4 :                     flags
    8145            4 :                 },
    8146            4 :                 &ctx,
    8147            4 :             )
    8148            4 :             .await
    8149            4 :             .unwrap();
    8150            4 : 
    8151            4 :         // Image layers are created at last_record_lsn
    8152            4 :         let images = tline
    8153            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8154            4 :             .await
    8155            4 :             .unwrap()
    8156            4 :             .into_iter()
    8157           36 :             .filter(|(k, _)| k.is_metadata_key())
    8158            4 :             .collect::<Vec<_>>();
    8159            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8160            4 :     }
    8161              : 
    8162              :     #[tokio::test]
    8163            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8164            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8165            4 :             .await
    8166            4 :             .unwrap();
    8167            4 :         let (tenant, ctx) = harness.load().await;
    8168            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8169            4 : 
    8170            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8171            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8172            4 : 
    8173            4 :         let tline = tenant
    8174            4 :             .create_test_timeline_with_layers(
    8175            4 :                 TIMELINE_ID,
    8176            4 :                 Lsn(0x10),
    8177            4 :                 DEFAULT_PG_VERSION,
    8178            4 :                 &ctx,
    8179            4 :                 // delta layers
    8180            4 :                 vec![
    8181            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8182            4 :                         Lsn(0x10)..Lsn(0x20),
    8183            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8184            4 :                     ),
    8185            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8186            4 :                         Lsn(0x20)..Lsn(0x30),
    8187            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8188            4 :                     ),
    8189            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8190            4 :                         Lsn(0x20)..Lsn(0x30),
    8191            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8192            4 :                     ),
    8193            4 :                 ],
    8194            4 :                 // image layers
    8195            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8196            4 :                 Lsn(0x30),
    8197            4 :             )
    8198            4 :             .await
    8199            4 :             .unwrap();
    8200            4 : 
    8201            4 :         let cancel = CancellationToken::new();
    8202            4 : 
    8203            4 :         tline
    8204            4 :             .compact(
    8205            4 :                 &cancel,
    8206            4 :                 {
    8207            4 :                     let mut flags = EnumSet::new();
    8208            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8209            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8210            4 :                     flags
    8211            4 :                 },
    8212            4 :                 &ctx,
    8213            4 :             )
    8214            4 :             .await
    8215            4 :             .unwrap();
    8216            4 : 
    8217            4 :         // Image layers are created at last_record_lsn
    8218            4 :         let images = tline
    8219            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8220            4 :             .await
    8221            4 :             .unwrap()
    8222            4 :             .into_iter()
    8223           28 :             .filter(|(k, _)| k.is_metadata_key())
    8224            4 :             .collect::<Vec<_>>();
    8225            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8226            4 :     }
    8227              : 
    8228              :     #[tokio::test]
    8229            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8230            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8231            4 :         let (tenant, ctx) = harness.load().await;
    8232            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8233            4 : 
    8234          204 :         fn get_key(id: u32) -> Key {
    8235          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8236          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8237          204 :             key.field6 = id;
    8238          204 :             key
    8239          204 :         }
    8240            4 : 
    8241            4 :         // We create
    8242            4 :         // - one bottom-most image layer,
    8243            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8244            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8245            4 :         // - a delta layer D3 above the horizon.
    8246            4 :         //
    8247            4 :         //                             | D3 |
    8248            4 :         //  | D1 |
    8249            4 :         // -|    |-- gc horizon -----------------
    8250            4 :         //  |    |                | D2 |
    8251            4 :         // --------- img layer ------------------
    8252            4 :         //
    8253            4 :         // What we should expact from this compaction is:
    8254            4 :         //                             | D3 |
    8255            4 :         //  | Part of D1 |
    8256            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8257            4 : 
    8258            4 :         // img layer at 0x10
    8259            4 :         let img_layer = (0..10)
    8260           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8261            4 :             .collect_vec();
    8262            4 : 
    8263            4 :         let delta1 = vec![
    8264            4 :             (
    8265            4 :                 get_key(1),
    8266            4 :                 Lsn(0x20),
    8267            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8268            4 :             ),
    8269            4 :             (
    8270            4 :                 get_key(2),
    8271            4 :                 Lsn(0x30),
    8272            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8273            4 :             ),
    8274            4 :             (
    8275            4 :                 get_key(3),
    8276            4 :                 Lsn(0x40),
    8277            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8278            4 :             ),
    8279            4 :         ];
    8280            4 :         let delta2 = vec![
    8281            4 :             (
    8282            4 :                 get_key(5),
    8283            4 :                 Lsn(0x20),
    8284            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8285            4 :             ),
    8286            4 :             (
    8287            4 :                 get_key(6),
    8288            4 :                 Lsn(0x20),
    8289            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8290            4 :             ),
    8291            4 :         ];
    8292            4 :         let delta3 = vec![
    8293            4 :             (
    8294            4 :                 get_key(8),
    8295            4 :                 Lsn(0x48),
    8296            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8297            4 :             ),
    8298            4 :             (
    8299            4 :                 get_key(9),
    8300            4 :                 Lsn(0x48),
    8301            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8302            4 :             ),
    8303            4 :         ];
    8304            4 : 
    8305            4 :         let tline = tenant
    8306            4 :             .create_test_timeline_with_layers(
    8307            4 :                 TIMELINE_ID,
    8308            4 :                 Lsn(0x10),
    8309            4 :                 DEFAULT_PG_VERSION,
    8310            4 :                 &ctx,
    8311            4 :                 vec![
    8312            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8313            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8314            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8315            4 :                 ], // delta layers
    8316            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8317            4 :                 Lsn(0x50),
    8318            4 :             )
    8319            4 :             .await?;
    8320            4 :         {
    8321            4 :             tline
    8322            4 :                 .latest_gc_cutoff_lsn
    8323            4 :                 .lock_for_write()
    8324            4 :                 .store_and_unlock(Lsn(0x30))
    8325            4 :                 .wait()
    8326            4 :                 .await;
    8327            4 :             // Update GC info
    8328            4 :             let mut guard = tline.gc_info.write().unwrap();
    8329            4 :             guard.cutoffs.time = Lsn(0x30);
    8330            4 :             guard.cutoffs.space = Lsn(0x30);
    8331            4 :         }
    8332            4 : 
    8333            4 :         let expected_result = [
    8334            4 :             Bytes::from_static(b"value 0@0x10"),
    8335            4 :             Bytes::from_static(b"value 1@0x20"),
    8336            4 :             Bytes::from_static(b"value 2@0x30"),
    8337            4 :             Bytes::from_static(b"value 3@0x40"),
    8338            4 :             Bytes::from_static(b"value 4@0x10"),
    8339            4 :             Bytes::from_static(b"value 5@0x20"),
    8340            4 :             Bytes::from_static(b"value 6@0x20"),
    8341            4 :             Bytes::from_static(b"value 7@0x10"),
    8342            4 :             Bytes::from_static(b"value 8@0x48"),
    8343            4 :             Bytes::from_static(b"value 9@0x48"),
    8344            4 :         ];
    8345            4 : 
    8346           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8347           40 :             assert_eq!(
    8348           40 :                 tline
    8349           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8350           40 :                     .await
    8351           40 :                     .unwrap(),
    8352            4 :                 expected
    8353            4 :             );
    8354            4 :         }
    8355            4 : 
    8356            4 :         let cancel = CancellationToken::new();
    8357            4 :         tline
    8358            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8359            4 :             .await
    8360            4 :             .unwrap();
    8361            4 : 
    8362           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8363           40 :             assert_eq!(
    8364           40 :                 tline
    8365           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8366           40 :                     .await
    8367           40 :                     .unwrap(),
    8368            4 :                 expected
    8369            4 :             );
    8370            4 :         }
    8371            4 : 
    8372            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8373            4 :         let image_at_gc_horizon = tline
    8374            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8375            4 :             .await
    8376            4 :             .unwrap()
    8377            4 :             .into_iter()
    8378           68 :             .filter(|(k, _)| k.is_metadata_key())
    8379            4 :             .collect::<Vec<_>>();
    8380            4 : 
    8381            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8382            4 :         let expected_result = [
    8383            4 :             Bytes::from_static(b"value 0@0x10"),
    8384            4 :             Bytes::from_static(b"value 1@0x20"),
    8385            4 :             Bytes::from_static(b"value 2@0x30"),
    8386            4 :             Bytes::from_static(b"value 3@0x10"),
    8387            4 :             Bytes::from_static(b"value 4@0x10"),
    8388            4 :             Bytes::from_static(b"value 5@0x20"),
    8389            4 :             Bytes::from_static(b"value 6@0x20"),
    8390            4 :             Bytes::from_static(b"value 7@0x10"),
    8391            4 :             Bytes::from_static(b"value 8@0x10"),
    8392            4 :             Bytes::from_static(b"value 9@0x10"),
    8393            4 :         ];
    8394           44 :         for idx in 0..10 {
    8395           40 :             assert_eq!(
    8396           40 :                 image_at_gc_horizon[idx],
    8397           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8398           40 :             );
    8399            4 :         }
    8400            4 : 
    8401            4 :         // Check if old layers are removed / new layers have the expected LSN
    8402            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8403            4 :         assert_eq!(
    8404            4 :             all_layers,
    8405            4 :             vec![
    8406            4 :                 // Image layer at GC horizon
    8407            4 :                 PersistentLayerKey {
    8408            4 :                     key_range: Key::MIN..Key::MAX,
    8409            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8410            4 :                     is_delta: false
    8411            4 :                 },
    8412            4 :                 // The delta layer below the horizon
    8413            4 :                 PersistentLayerKey {
    8414            4 :                     key_range: get_key(3)..get_key(4),
    8415            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8416            4 :                     is_delta: true
    8417            4 :                 },
    8418            4 :                 // The delta3 layer that should not be picked for the compaction
    8419            4 :                 PersistentLayerKey {
    8420            4 :                     key_range: get_key(8)..get_key(10),
    8421            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8422            4 :                     is_delta: true
    8423            4 :                 }
    8424            4 :             ]
    8425            4 :         );
    8426            4 : 
    8427            4 :         // increase GC horizon and compact again
    8428            4 :         {
    8429            4 :             tline
    8430            4 :                 .latest_gc_cutoff_lsn
    8431            4 :                 .lock_for_write()
    8432            4 :                 .store_and_unlock(Lsn(0x40))
    8433            4 :                 .wait()
    8434            4 :                 .await;
    8435            4 :             // Update GC info
    8436            4 :             let mut guard = tline.gc_info.write().unwrap();
    8437            4 :             guard.cutoffs.time = Lsn(0x40);
    8438            4 :             guard.cutoffs.space = Lsn(0x40);
    8439            4 :         }
    8440            4 :         tline
    8441            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8442            4 :             .await
    8443            4 :             .unwrap();
    8444            4 : 
    8445            4 :         Ok(())
    8446            4 :     }
    8447              : 
    8448              :     #[cfg(feature = "testing")]
    8449              :     #[tokio::test]
    8450            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8451            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8452            4 :         let (tenant, ctx) = harness.load().await;
    8453            4 : 
    8454           48 :         fn get_key(id: u32) -> Key {
    8455           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8456           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8457           48 :             key.field6 = id;
    8458           48 :             key
    8459           48 :         }
    8460            4 : 
    8461            4 :         let delta1 = vec![
    8462            4 :             (
    8463            4 :                 get_key(1),
    8464            4 :                 Lsn(0x20),
    8465            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8466            4 :             ),
    8467            4 :             (
    8468            4 :                 get_key(1),
    8469            4 :                 Lsn(0x30),
    8470            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8471            4 :             ),
    8472            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8473            4 :             (
    8474            4 :                 get_key(2),
    8475            4 :                 Lsn(0x20),
    8476            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8477            4 :             ),
    8478            4 :             (
    8479            4 :                 get_key(2),
    8480            4 :                 Lsn(0x30),
    8481            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8482            4 :             ),
    8483            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8484            4 :             (
    8485            4 :                 get_key(3),
    8486            4 :                 Lsn(0x20),
    8487            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8488            4 :             ),
    8489            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8490            4 :             (
    8491            4 :                 get_key(4),
    8492            4 :                 Lsn(0x20),
    8493            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8494            4 :             ),
    8495            4 :         ];
    8496            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8497            4 : 
    8498            4 :         let tline = tenant
    8499            4 :             .create_test_timeline_with_layers(
    8500            4 :                 TIMELINE_ID,
    8501            4 :                 Lsn(0x10),
    8502            4 :                 DEFAULT_PG_VERSION,
    8503            4 :                 &ctx,
    8504            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8505            4 :                     Lsn(0x10)..Lsn(0x40),
    8506            4 :                     delta1,
    8507            4 :                 )], // delta layers
    8508            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8509            4 :                 Lsn(0x50),
    8510            4 :             )
    8511            4 :             .await?;
    8512            4 : 
    8513            4 :         assert_eq!(
    8514            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8515            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8516            4 :         );
    8517            4 :         assert_eq!(
    8518            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8519            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8520            4 :         );
    8521            4 : 
    8522            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8523            4 : 
    8524            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8525            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8526            4 : 
    8527            4 :         Ok(())
    8528            4 :     }
    8529              : 
    8530              :     #[tokio::test(start_paused = true)]
    8531            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8532            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8533            4 :             .await
    8534            4 :             .unwrap()
    8535            4 :             .load()
    8536            4 :             .await;
    8537            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8538            4 :         // initial transition into AttachedSingle.
    8539            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8540            4 :         tokio::time::resume();
    8541            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8542            4 : 
    8543            4 :         let end_lsn = Lsn(0x100);
    8544            4 :         let image_layers = (0x20..=0x90)
    8545            4 :             .step_by(0x10)
    8546           32 :             .map(|n| {
    8547           32 :                 (
    8548           32 :                     Lsn(n),
    8549           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8550           32 :                 )
    8551           32 :             })
    8552            4 :             .collect();
    8553            4 : 
    8554            4 :         let timeline = tenant
    8555            4 :             .create_test_timeline_with_layers(
    8556            4 :                 TIMELINE_ID,
    8557            4 :                 Lsn(0x10),
    8558            4 :                 DEFAULT_PG_VERSION,
    8559            4 :                 &ctx,
    8560            4 :                 Vec::new(),
    8561            4 :                 image_layers,
    8562            4 :                 end_lsn,
    8563            4 :             )
    8564            4 :             .await?;
    8565            4 : 
    8566            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8567            4 :         let mut leases = Vec::new();
    8568           12 :         leased_lsns.iter().for_each(|n| {
    8569           12 :             leases.push(
    8570           12 :                 timeline
    8571           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8572           12 :                     .expect("lease request should succeed"),
    8573           12 :             );
    8574           12 :         });
    8575            4 : 
    8576            4 :         let updated_lease_0 = timeline
    8577            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8578            4 :             .expect("lease renewal should succeed");
    8579            4 :         assert_eq!(
    8580            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8581            4 :             " Renewing with shorter lease should not change the lease."
    8582            4 :         );
    8583            4 : 
    8584            4 :         let updated_lease_1 = timeline
    8585            4 :             .renew_lsn_lease(
    8586            4 :                 Lsn(leased_lsns[1]),
    8587            4 :                 timeline.get_lsn_lease_length() * 2,
    8588            4 :                 &ctx,
    8589            4 :             )
    8590            4 :             .expect("lease renewal should succeed");
    8591            4 :         assert!(
    8592            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8593            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8594            4 :         );
    8595            4 : 
    8596            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8597            4 :         info!(
    8598            4 :             "latest_gc_cutoff_lsn: {}",
    8599            0 :             *timeline.get_latest_gc_cutoff_lsn()
    8600            4 :         );
    8601            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8602            4 : 
    8603            4 :         let res = tenant
    8604            4 :             .gc_iteration(
    8605            4 :                 Some(TIMELINE_ID),
    8606            4 :                 0,
    8607            4 :                 Duration::ZERO,
    8608            4 :                 &CancellationToken::new(),
    8609            4 :                 &ctx,
    8610            4 :             )
    8611            4 :             .await
    8612            4 :             .unwrap();
    8613            4 : 
    8614            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8615            4 :         // 0/10: initdb layer
    8616            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8617            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8618            4 :         // Keeping 0/90 b/c it is the latest layer.
    8619            4 :         assert_eq!(res.layers_not_updated, 1);
    8620            4 :         // Removed 0/80.
    8621            4 :         assert_eq!(res.layers_removed, 1);
    8622            4 : 
    8623            4 :         // Make lease on a already GC-ed LSN.
    8624            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8625            4 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    8626            4 :         timeline
    8627            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8628            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8629            4 : 
    8630            4 :         // Should still be able to renew a currently valid lease
    8631            4 :         // Assumption: original lease to is still valid for 0/50.
    8632            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8633            4 :         timeline
    8634            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8635            4 :             .expect("lease renewal with validation should succeed");
    8636            4 : 
    8637            4 :         Ok(())
    8638            4 :     }
    8639              : 
    8640              :     #[cfg(feature = "testing")]
    8641              :     #[tokio::test]
    8642            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8643            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8644            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8645            4 :             false,
    8646            4 :         )
    8647            4 :         .await
    8648            4 :     }
    8649              : 
    8650              :     #[cfg(feature = "testing")]
    8651              :     #[tokio::test]
    8652            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8653            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8654            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8655            4 :             true,
    8656            4 :         )
    8657            4 :         .await
    8658            4 :     }
    8659              : 
    8660              :     #[cfg(feature = "testing")]
    8661            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8662            8 :         test_name: &'static str,
    8663            8 :         use_delta_bottom_layer: bool,
    8664            8 :     ) -> anyhow::Result<()> {
    8665            8 :         let harness = TenantHarness::create(test_name).await?;
    8666            8 :         let (tenant, ctx) = harness.load().await;
    8667              : 
    8668          552 :         fn get_key(id: u32) -> Key {
    8669          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8670          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8671          552 :             key.field6 = id;
    8672          552 :             key
    8673          552 :         }
    8674              : 
    8675              :         // We create
    8676              :         // - one bottom-most image layer,
    8677              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8678              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8679              :         // - a delta layer D3 above the horizon.
    8680              :         //
    8681              :         //                             | D3 |
    8682              :         //  | D1 |
    8683              :         // -|    |-- gc horizon -----------------
    8684              :         //  |    |                | D2 |
    8685              :         // --------- img layer ------------------
    8686              :         //
    8687              :         // What we should expact from this compaction is:
    8688              :         //                             | D3 |
    8689              :         //  | Part of D1 |
    8690              :         // --------- img layer with D1+D2 at GC horizon------------------
    8691              : 
    8692              :         // img layer at 0x10
    8693            8 :         let img_layer = (0..10)
    8694           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8695            8 :             .collect_vec();
    8696            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8697            8 :         let delta4 = (0..10)
    8698           80 :             .map(|id| {
    8699           80 :                 (
    8700           80 :                     get_key(id),
    8701           80 :                     Lsn(0x08),
    8702           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8703           80 :                 )
    8704           80 :             })
    8705            8 :             .collect_vec();
    8706            8 : 
    8707            8 :         let delta1 = vec![
    8708            8 :             (
    8709            8 :                 get_key(1),
    8710            8 :                 Lsn(0x20),
    8711            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8712            8 :             ),
    8713            8 :             (
    8714            8 :                 get_key(2),
    8715            8 :                 Lsn(0x30),
    8716            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8717            8 :             ),
    8718            8 :             (
    8719            8 :                 get_key(3),
    8720            8 :                 Lsn(0x28),
    8721            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8722            8 :             ),
    8723            8 :             (
    8724            8 :                 get_key(3),
    8725            8 :                 Lsn(0x30),
    8726            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8727            8 :             ),
    8728            8 :             (
    8729            8 :                 get_key(3),
    8730            8 :                 Lsn(0x40),
    8731            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8732            8 :             ),
    8733            8 :         ];
    8734            8 :         let delta2 = vec![
    8735            8 :             (
    8736            8 :                 get_key(5),
    8737            8 :                 Lsn(0x20),
    8738            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8739            8 :             ),
    8740            8 :             (
    8741            8 :                 get_key(6),
    8742            8 :                 Lsn(0x20),
    8743            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8744            8 :             ),
    8745            8 :         ];
    8746            8 :         let delta3 = vec![
    8747            8 :             (
    8748            8 :                 get_key(8),
    8749            8 :                 Lsn(0x48),
    8750            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8751            8 :             ),
    8752            8 :             (
    8753            8 :                 get_key(9),
    8754            8 :                 Lsn(0x48),
    8755            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8756            8 :             ),
    8757            8 :         ];
    8758              : 
    8759            8 :         let tline = if use_delta_bottom_layer {
    8760            4 :             tenant
    8761            4 :                 .create_test_timeline_with_layers(
    8762            4 :                     TIMELINE_ID,
    8763            4 :                     Lsn(0x08),
    8764            4 :                     DEFAULT_PG_VERSION,
    8765            4 :                     &ctx,
    8766            4 :                     vec![
    8767            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8768            4 :                             Lsn(0x08)..Lsn(0x10),
    8769            4 :                             delta4,
    8770            4 :                         ),
    8771            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8772            4 :                             Lsn(0x20)..Lsn(0x48),
    8773            4 :                             delta1,
    8774            4 :                         ),
    8775            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8776            4 :                             Lsn(0x20)..Lsn(0x48),
    8777            4 :                             delta2,
    8778            4 :                         ),
    8779            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8780            4 :                             Lsn(0x48)..Lsn(0x50),
    8781            4 :                             delta3,
    8782            4 :                         ),
    8783            4 :                     ], // delta layers
    8784            4 :                     vec![], // image layers
    8785            4 :                     Lsn(0x50),
    8786            4 :                 )
    8787            4 :                 .await?
    8788              :         } else {
    8789            4 :             tenant
    8790            4 :                 .create_test_timeline_with_layers(
    8791            4 :                     TIMELINE_ID,
    8792            4 :                     Lsn(0x10),
    8793            4 :                     DEFAULT_PG_VERSION,
    8794            4 :                     &ctx,
    8795            4 :                     vec![
    8796            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8797            4 :                             Lsn(0x10)..Lsn(0x48),
    8798            4 :                             delta1,
    8799            4 :                         ),
    8800            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8801            4 :                             Lsn(0x10)..Lsn(0x48),
    8802            4 :                             delta2,
    8803            4 :                         ),
    8804            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8805            4 :                             Lsn(0x48)..Lsn(0x50),
    8806            4 :                             delta3,
    8807            4 :                         ),
    8808            4 :                     ], // delta layers
    8809            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8810            4 :                     Lsn(0x50),
    8811            4 :                 )
    8812            4 :                 .await?
    8813              :         };
    8814              :         {
    8815            8 :             tline
    8816            8 :                 .latest_gc_cutoff_lsn
    8817            8 :                 .lock_for_write()
    8818            8 :                 .store_and_unlock(Lsn(0x30))
    8819            8 :                 .wait()
    8820            8 :                 .await;
    8821              :             // Update GC info
    8822            8 :             let mut guard = tline.gc_info.write().unwrap();
    8823            8 :             *guard = GcInfo {
    8824            8 :                 retain_lsns: vec![],
    8825            8 :                 cutoffs: GcCutoffs {
    8826            8 :                     time: Lsn(0x30),
    8827            8 :                     space: Lsn(0x30),
    8828            8 :                 },
    8829            8 :                 leases: Default::default(),
    8830            8 :                 within_ancestor_pitr: false,
    8831            8 :             };
    8832            8 :         }
    8833            8 : 
    8834            8 :         let expected_result = [
    8835            8 :             Bytes::from_static(b"value 0@0x10"),
    8836            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8837            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8838            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8839            8 :             Bytes::from_static(b"value 4@0x10"),
    8840            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8841            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8842            8 :             Bytes::from_static(b"value 7@0x10"),
    8843            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8844            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8845            8 :         ];
    8846            8 : 
    8847            8 :         let expected_result_at_gc_horizon = [
    8848            8 :             Bytes::from_static(b"value 0@0x10"),
    8849            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8850            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8851            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8852            8 :             Bytes::from_static(b"value 4@0x10"),
    8853            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8854            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8855            8 :             Bytes::from_static(b"value 7@0x10"),
    8856            8 :             Bytes::from_static(b"value 8@0x10"),
    8857            8 :             Bytes::from_static(b"value 9@0x10"),
    8858            8 :         ];
    8859              : 
    8860           88 :         for idx in 0..10 {
    8861           80 :             assert_eq!(
    8862           80 :                 tline
    8863           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8864           80 :                     .await
    8865           80 :                     .unwrap(),
    8866           80 :                 &expected_result[idx]
    8867              :             );
    8868           80 :             assert_eq!(
    8869           80 :                 tline
    8870           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8871           80 :                     .await
    8872           80 :                     .unwrap(),
    8873           80 :                 &expected_result_at_gc_horizon[idx]
    8874              :             );
    8875              :         }
    8876              : 
    8877            8 :         let cancel = CancellationToken::new();
    8878            8 :         tline
    8879            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8880            8 :             .await
    8881            8 :             .unwrap();
    8882              : 
    8883           88 :         for idx in 0..10 {
    8884           80 :             assert_eq!(
    8885           80 :                 tline
    8886           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8887           80 :                     .await
    8888           80 :                     .unwrap(),
    8889           80 :                 &expected_result[idx]
    8890              :             );
    8891           80 :             assert_eq!(
    8892           80 :                 tline
    8893           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8894           80 :                     .await
    8895           80 :                     .unwrap(),
    8896           80 :                 &expected_result_at_gc_horizon[idx]
    8897              :             );
    8898              :         }
    8899              : 
    8900              :         // increase GC horizon and compact again
    8901              :         {
    8902            8 :             tline
    8903            8 :                 .latest_gc_cutoff_lsn
    8904            8 :                 .lock_for_write()
    8905            8 :                 .store_and_unlock(Lsn(0x40))
    8906            8 :                 .wait()
    8907            8 :                 .await;
    8908              :             // Update GC info
    8909            8 :             let mut guard = tline.gc_info.write().unwrap();
    8910            8 :             guard.cutoffs.time = Lsn(0x40);
    8911            8 :             guard.cutoffs.space = Lsn(0x40);
    8912            8 :         }
    8913            8 :         tline
    8914            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8915            8 :             .await
    8916            8 :             .unwrap();
    8917            8 : 
    8918            8 :         Ok(())
    8919            8 :     }
    8920              : 
    8921              :     #[cfg(feature = "testing")]
    8922              :     #[tokio::test]
    8923            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8924            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8925            4 :         let (tenant, ctx) = harness.load().await;
    8926            4 :         let tline = tenant
    8927            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8928            4 :             .await?;
    8929            4 :         tline.force_advance_lsn(Lsn(0x70));
    8930            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8931            4 :         let history = vec![
    8932            4 :             (
    8933            4 :                 key,
    8934            4 :                 Lsn(0x10),
    8935            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8936            4 :             ),
    8937            4 :             (
    8938            4 :                 key,
    8939            4 :                 Lsn(0x20),
    8940            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8941            4 :             ),
    8942            4 :             (
    8943            4 :                 key,
    8944            4 :                 Lsn(0x30),
    8945            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8946            4 :             ),
    8947            4 :             (
    8948            4 :                 key,
    8949            4 :                 Lsn(0x40),
    8950            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8951            4 :             ),
    8952            4 :             (
    8953            4 :                 key,
    8954            4 :                 Lsn(0x50),
    8955            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8956            4 :             ),
    8957            4 :             (
    8958            4 :                 key,
    8959            4 :                 Lsn(0x60),
    8960            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8961            4 :             ),
    8962            4 :             (
    8963            4 :                 key,
    8964            4 :                 Lsn(0x70),
    8965            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8966            4 :             ),
    8967            4 :             (
    8968            4 :                 key,
    8969            4 :                 Lsn(0x80),
    8970            4 :                 Value::Image(Bytes::copy_from_slice(
    8971            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8972            4 :                 )),
    8973            4 :             ),
    8974            4 :             (
    8975            4 :                 key,
    8976            4 :                 Lsn(0x90),
    8977            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8978            4 :             ),
    8979            4 :         ];
    8980            4 :         let res = tline
    8981            4 :             .generate_key_retention(
    8982            4 :                 key,
    8983            4 :                 &history,
    8984            4 :                 Lsn(0x60),
    8985            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8986            4 :                 3,
    8987            4 :                 None,
    8988            4 :             )
    8989            4 :             .await
    8990            4 :             .unwrap();
    8991            4 :         let expected_res = KeyHistoryRetention {
    8992            4 :             below_horizon: vec![
    8993            4 :                 (
    8994            4 :                     Lsn(0x20),
    8995            4 :                     KeyLogAtLsn(vec![(
    8996            4 :                         Lsn(0x20),
    8997            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8998            4 :                     )]),
    8999            4 :                 ),
    9000            4 :                 (
    9001            4 :                     Lsn(0x40),
    9002            4 :                     KeyLogAtLsn(vec![
    9003            4 :                         (
    9004            4 :                             Lsn(0x30),
    9005            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9006            4 :                         ),
    9007            4 :                         (
    9008            4 :                             Lsn(0x40),
    9009            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9010            4 :                         ),
    9011            4 :                     ]),
    9012            4 :                 ),
    9013            4 :                 (
    9014            4 :                     Lsn(0x50),
    9015            4 :                     KeyLogAtLsn(vec![(
    9016            4 :                         Lsn(0x50),
    9017            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9018            4 :                     )]),
    9019            4 :                 ),
    9020            4 :                 (
    9021            4 :                     Lsn(0x60),
    9022            4 :                     KeyLogAtLsn(vec![(
    9023            4 :                         Lsn(0x60),
    9024            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9025            4 :                     )]),
    9026            4 :                 ),
    9027            4 :             ],
    9028            4 :             above_horizon: KeyLogAtLsn(vec![
    9029            4 :                 (
    9030            4 :                     Lsn(0x70),
    9031            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9032            4 :                 ),
    9033            4 :                 (
    9034            4 :                     Lsn(0x80),
    9035            4 :                     Value::Image(Bytes::copy_from_slice(
    9036            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9037            4 :                     )),
    9038            4 :                 ),
    9039            4 :                 (
    9040            4 :                     Lsn(0x90),
    9041            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9042            4 :                 ),
    9043            4 :             ]),
    9044            4 :         };
    9045            4 :         assert_eq!(res, expected_res);
    9046            4 : 
    9047            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9048            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9049            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9050            4 :         // For example, we have
    9051            4 :         // ```plain
    9052            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9053            4 :         // ```
    9054            4 :         // Now the GC horizon moves up, and we have
    9055            4 :         // ```plain
    9056            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9057            4 :         // ```
    9058            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9059            4 :         // We will end up with
    9060            4 :         // ```plain
    9061            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9062            4 :         // ```
    9063            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9064            4 :         // We should be able to handle this partial history and drop everything before the
    9065            4 :         // gc_horizon image.
    9066            4 : 
    9067            4 :         let history = vec![
    9068            4 :             (
    9069            4 :                 key,
    9070            4 :                 Lsn(0x20),
    9071            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9072            4 :             ),
    9073            4 :             (
    9074            4 :                 key,
    9075            4 :                 Lsn(0x30),
    9076            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9077            4 :             ),
    9078            4 :             (
    9079            4 :                 key,
    9080            4 :                 Lsn(0x40),
    9081            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9082            4 :             ),
    9083            4 :             (
    9084            4 :                 key,
    9085            4 :                 Lsn(0x50),
    9086            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9087            4 :             ),
    9088            4 :             (
    9089            4 :                 key,
    9090            4 :                 Lsn(0x60),
    9091            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9092            4 :             ),
    9093            4 :             (
    9094            4 :                 key,
    9095            4 :                 Lsn(0x70),
    9096            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9097            4 :             ),
    9098            4 :             (
    9099            4 :                 key,
    9100            4 :                 Lsn(0x80),
    9101            4 :                 Value::Image(Bytes::copy_from_slice(
    9102            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9103            4 :                 )),
    9104            4 :             ),
    9105            4 :             (
    9106            4 :                 key,
    9107            4 :                 Lsn(0x90),
    9108            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9109            4 :             ),
    9110            4 :         ];
    9111            4 :         let res = tline
    9112            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9113            4 :             .await
    9114            4 :             .unwrap();
    9115            4 :         let expected_res = KeyHistoryRetention {
    9116            4 :             below_horizon: vec![
    9117            4 :                 (
    9118            4 :                     Lsn(0x40),
    9119            4 :                     KeyLogAtLsn(vec![(
    9120            4 :                         Lsn(0x40),
    9121            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9122            4 :                     )]),
    9123            4 :                 ),
    9124            4 :                 (
    9125            4 :                     Lsn(0x50),
    9126            4 :                     KeyLogAtLsn(vec![(
    9127            4 :                         Lsn(0x50),
    9128            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9129            4 :                     )]),
    9130            4 :                 ),
    9131            4 :                 (
    9132            4 :                     Lsn(0x60),
    9133            4 :                     KeyLogAtLsn(vec![(
    9134            4 :                         Lsn(0x60),
    9135            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9136            4 :                     )]),
    9137            4 :                 ),
    9138            4 :             ],
    9139            4 :             above_horizon: KeyLogAtLsn(vec![
    9140            4 :                 (
    9141            4 :                     Lsn(0x70),
    9142            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9143            4 :                 ),
    9144            4 :                 (
    9145            4 :                     Lsn(0x80),
    9146            4 :                     Value::Image(Bytes::copy_from_slice(
    9147            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9148            4 :                     )),
    9149            4 :                 ),
    9150            4 :                 (
    9151            4 :                     Lsn(0x90),
    9152            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9153            4 :                 ),
    9154            4 :             ]),
    9155            4 :         };
    9156            4 :         assert_eq!(res, expected_res);
    9157            4 : 
    9158            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9159            4 :         // the ancestor image in the test case.
    9160            4 : 
    9161            4 :         let history = vec![
    9162            4 :             (
    9163            4 :                 key,
    9164            4 :                 Lsn(0x20),
    9165            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9166            4 :             ),
    9167            4 :             (
    9168            4 :                 key,
    9169            4 :                 Lsn(0x30),
    9170            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9171            4 :             ),
    9172            4 :             (
    9173            4 :                 key,
    9174            4 :                 Lsn(0x40),
    9175            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9176            4 :             ),
    9177            4 :             (
    9178            4 :                 key,
    9179            4 :                 Lsn(0x70),
    9180            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9181            4 :             ),
    9182            4 :         ];
    9183            4 :         let res = tline
    9184            4 :             .generate_key_retention(
    9185            4 :                 key,
    9186            4 :                 &history,
    9187            4 :                 Lsn(0x60),
    9188            4 :                 &[],
    9189            4 :                 3,
    9190            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9191            4 :             )
    9192            4 :             .await
    9193            4 :             .unwrap();
    9194            4 :         let expected_res = KeyHistoryRetention {
    9195            4 :             below_horizon: vec![(
    9196            4 :                 Lsn(0x60),
    9197            4 :                 KeyLogAtLsn(vec![(
    9198            4 :                     Lsn(0x60),
    9199            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9200            4 :                 )]),
    9201            4 :             )],
    9202            4 :             above_horizon: KeyLogAtLsn(vec![(
    9203            4 :                 Lsn(0x70),
    9204            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9205            4 :             )]),
    9206            4 :         };
    9207            4 :         assert_eq!(res, expected_res);
    9208            4 : 
    9209            4 :         let history = vec![
    9210            4 :             (
    9211            4 :                 key,
    9212            4 :                 Lsn(0x20),
    9213            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9214            4 :             ),
    9215            4 :             (
    9216            4 :                 key,
    9217            4 :                 Lsn(0x40),
    9218            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9219            4 :             ),
    9220            4 :             (
    9221            4 :                 key,
    9222            4 :                 Lsn(0x60),
    9223            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9224            4 :             ),
    9225            4 :             (
    9226            4 :                 key,
    9227            4 :                 Lsn(0x70),
    9228            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9229            4 :             ),
    9230            4 :         ];
    9231            4 :         let res = tline
    9232            4 :             .generate_key_retention(
    9233            4 :                 key,
    9234            4 :                 &history,
    9235            4 :                 Lsn(0x60),
    9236            4 :                 &[Lsn(0x30)],
    9237            4 :                 3,
    9238            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9239            4 :             )
    9240            4 :             .await
    9241            4 :             .unwrap();
    9242            4 :         let expected_res = KeyHistoryRetention {
    9243            4 :             below_horizon: vec![
    9244            4 :                 (
    9245            4 :                     Lsn(0x30),
    9246            4 :                     KeyLogAtLsn(vec![(
    9247            4 :                         Lsn(0x20),
    9248            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9249            4 :                     )]),
    9250            4 :                 ),
    9251            4 :                 (
    9252            4 :                     Lsn(0x60),
    9253            4 :                     KeyLogAtLsn(vec![(
    9254            4 :                         Lsn(0x60),
    9255            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9256            4 :                     )]),
    9257            4 :                 ),
    9258            4 :             ],
    9259            4 :             above_horizon: KeyLogAtLsn(vec![(
    9260            4 :                 Lsn(0x70),
    9261            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9262            4 :             )]),
    9263            4 :         };
    9264            4 :         assert_eq!(res, expected_res);
    9265            4 : 
    9266            4 :         Ok(())
    9267            4 :     }
    9268              : 
    9269              :     #[cfg(feature = "testing")]
    9270              :     #[tokio::test]
    9271            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9272            4 :         let harness =
    9273            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9274            4 :         let (tenant, ctx) = harness.load().await;
    9275            4 : 
    9276         1036 :         fn get_key(id: u32) -> Key {
    9277         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9278         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9279         1036 :             key.field6 = id;
    9280         1036 :             key
    9281         1036 :         }
    9282            4 : 
    9283            4 :         let img_layer = (0..10)
    9284           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9285            4 :             .collect_vec();
    9286            4 : 
    9287            4 :         let delta1 = vec![
    9288            4 :             (
    9289            4 :                 get_key(1),
    9290            4 :                 Lsn(0x20),
    9291            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9292            4 :             ),
    9293            4 :             (
    9294            4 :                 get_key(2),
    9295            4 :                 Lsn(0x30),
    9296            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9297            4 :             ),
    9298            4 :             (
    9299            4 :                 get_key(3),
    9300            4 :                 Lsn(0x28),
    9301            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9302            4 :             ),
    9303            4 :             (
    9304            4 :                 get_key(3),
    9305            4 :                 Lsn(0x30),
    9306            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9307            4 :             ),
    9308            4 :             (
    9309            4 :                 get_key(3),
    9310            4 :                 Lsn(0x40),
    9311            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9312            4 :             ),
    9313            4 :         ];
    9314            4 :         let delta2 = vec![
    9315            4 :             (
    9316            4 :                 get_key(5),
    9317            4 :                 Lsn(0x20),
    9318            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9319            4 :             ),
    9320            4 :             (
    9321            4 :                 get_key(6),
    9322            4 :                 Lsn(0x20),
    9323            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9324            4 :             ),
    9325            4 :         ];
    9326            4 :         let delta3 = vec![
    9327            4 :             (
    9328            4 :                 get_key(8),
    9329            4 :                 Lsn(0x48),
    9330            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9331            4 :             ),
    9332            4 :             (
    9333            4 :                 get_key(9),
    9334            4 :                 Lsn(0x48),
    9335            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9336            4 :             ),
    9337            4 :         ];
    9338            4 : 
    9339            4 :         let tline = tenant
    9340            4 :             .create_test_timeline_with_layers(
    9341            4 :                 TIMELINE_ID,
    9342            4 :                 Lsn(0x10),
    9343            4 :                 DEFAULT_PG_VERSION,
    9344            4 :                 &ctx,
    9345            4 :                 vec![
    9346            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9347            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9348            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9349            4 :                 ], // delta layers
    9350            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9351            4 :                 Lsn(0x50),
    9352            4 :             )
    9353            4 :             .await?;
    9354            4 :         {
    9355            4 :             tline
    9356            4 :                 .latest_gc_cutoff_lsn
    9357            4 :                 .lock_for_write()
    9358            4 :                 .store_and_unlock(Lsn(0x30))
    9359            4 :                 .wait()
    9360            4 :                 .await;
    9361            4 :             // Update GC info
    9362            4 :             let mut guard = tline.gc_info.write().unwrap();
    9363            4 :             *guard = GcInfo {
    9364            4 :                 retain_lsns: vec![
    9365            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9366            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9367            4 :                 ],
    9368            4 :                 cutoffs: GcCutoffs {
    9369            4 :                     time: Lsn(0x30),
    9370            4 :                     space: Lsn(0x30),
    9371            4 :                 },
    9372            4 :                 leases: Default::default(),
    9373            4 :                 within_ancestor_pitr: false,
    9374            4 :             };
    9375            4 :         }
    9376            4 : 
    9377            4 :         let expected_result = [
    9378            4 :             Bytes::from_static(b"value 0@0x10"),
    9379            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9380            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9381            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9382            4 :             Bytes::from_static(b"value 4@0x10"),
    9383            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9384            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9385            4 :             Bytes::from_static(b"value 7@0x10"),
    9386            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9387            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9388            4 :         ];
    9389            4 : 
    9390            4 :         let expected_result_at_gc_horizon = [
    9391            4 :             Bytes::from_static(b"value 0@0x10"),
    9392            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9393            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9394            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9395            4 :             Bytes::from_static(b"value 4@0x10"),
    9396            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9397            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9398            4 :             Bytes::from_static(b"value 7@0x10"),
    9399            4 :             Bytes::from_static(b"value 8@0x10"),
    9400            4 :             Bytes::from_static(b"value 9@0x10"),
    9401            4 :         ];
    9402            4 : 
    9403            4 :         let expected_result_at_lsn_20 = [
    9404            4 :             Bytes::from_static(b"value 0@0x10"),
    9405            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9406            4 :             Bytes::from_static(b"value 2@0x10"),
    9407            4 :             Bytes::from_static(b"value 3@0x10"),
    9408            4 :             Bytes::from_static(b"value 4@0x10"),
    9409            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9410            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9411            4 :             Bytes::from_static(b"value 7@0x10"),
    9412            4 :             Bytes::from_static(b"value 8@0x10"),
    9413            4 :             Bytes::from_static(b"value 9@0x10"),
    9414            4 :         ];
    9415            4 : 
    9416            4 :         let expected_result_at_lsn_10 = [
    9417            4 :             Bytes::from_static(b"value 0@0x10"),
    9418            4 :             Bytes::from_static(b"value 1@0x10"),
    9419            4 :             Bytes::from_static(b"value 2@0x10"),
    9420            4 :             Bytes::from_static(b"value 3@0x10"),
    9421            4 :             Bytes::from_static(b"value 4@0x10"),
    9422            4 :             Bytes::from_static(b"value 5@0x10"),
    9423            4 :             Bytes::from_static(b"value 6@0x10"),
    9424            4 :             Bytes::from_static(b"value 7@0x10"),
    9425            4 :             Bytes::from_static(b"value 8@0x10"),
    9426            4 :             Bytes::from_static(b"value 9@0x10"),
    9427            4 :         ];
    9428            4 : 
    9429           24 :         let verify_result = || async {
    9430           24 :             let gc_horizon = {
    9431           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9432           24 :                 gc_info.cutoffs.time
    9433            4 :             };
    9434          264 :             for idx in 0..10 {
    9435          240 :                 assert_eq!(
    9436          240 :                     tline
    9437          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9438          240 :                         .await
    9439          240 :                         .unwrap(),
    9440          240 :                     &expected_result[idx]
    9441            4 :                 );
    9442          240 :                 assert_eq!(
    9443          240 :                     tline
    9444          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9445          240 :                         .await
    9446          240 :                         .unwrap(),
    9447          240 :                     &expected_result_at_gc_horizon[idx]
    9448            4 :                 );
    9449          240 :                 assert_eq!(
    9450          240 :                     tline
    9451          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9452          240 :                         .await
    9453          240 :                         .unwrap(),
    9454          240 :                     &expected_result_at_lsn_20[idx]
    9455            4 :                 );
    9456          240 :                 assert_eq!(
    9457          240 :                     tline
    9458          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9459          240 :                         .await
    9460          240 :                         .unwrap(),
    9461          240 :                     &expected_result_at_lsn_10[idx]
    9462            4 :                 );
    9463            4 :             }
    9464           48 :         };
    9465            4 : 
    9466            4 :         verify_result().await;
    9467            4 : 
    9468            4 :         let cancel = CancellationToken::new();
    9469            4 :         let mut dryrun_flags = EnumSet::new();
    9470            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9471            4 : 
    9472            4 :         tline
    9473            4 :             .compact_with_gc(
    9474            4 :                 &cancel,
    9475            4 :                 CompactOptions {
    9476            4 :                     flags: dryrun_flags,
    9477            4 :                     ..Default::default()
    9478            4 :                 },
    9479            4 :                 &ctx,
    9480            4 :             )
    9481            4 :             .await
    9482            4 :             .unwrap();
    9483            4 :         // 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
    9484            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9485            4 :         verify_result().await;
    9486            4 : 
    9487            4 :         tline
    9488            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9489            4 :             .await
    9490            4 :             .unwrap();
    9491            4 :         verify_result().await;
    9492            4 : 
    9493            4 :         // compact again
    9494            4 :         tline
    9495            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9496            4 :             .await
    9497            4 :             .unwrap();
    9498            4 :         verify_result().await;
    9499            4 : 
    9500            4 :         // increase GC horizon and compact again
    9501            4 :         {
    9502            4 :             tline
    9503            4 :                 .latest_gc_cutoff_lsn
    9504            4 :                 .lock_for_write()
    9505            4 :                 .store_and_unlock(Lsn(0x38))
    9506            4 :                 .wait()
    9507            4 :                 .await;
    9508            4 :             // Update GC info
    9509            4 :             let mut guard = tline.gc_info.write().unwrap();
    9510            4 :             guard.cutoffs.time = Lsn(0x38);
    9511            4 :             guard.cutoffs.space = Lsn(0x38);
    9512            4 :         }
    9513            4 :         tline
    9514            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9515            4 :             .await
    9516            4 :             .unwrap();
    9517            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9518            4 : 
    9519            4 :         // not increasing the GC horizon and compact again
    9520            4 :         tline
    9521            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9522            4 :             .await
    9523            4 :             .unwrap();
    9524            4 :         verify_result().await;
    9525            4 : 
    9526            4 :         Ok(())
    9527            4 :     }
    9528              : 
    9529              :     #[cfg(feature = "testing")]
    9530              :     #[tokio::test]
    9531            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9532            4 :     {
    9533            4 :         let harness =
    9534            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9535            4 :                 .await?;
    9536            4 :         let (tenant, ctx) = harness.load().await;
    9537            4 : 
    9538          704 :         fn get_key(id: u32) -> Key {
    9539          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9540          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9541          704 :             key.field6 = id;
    9542          704 :             key
    9543          704 :         }
    9544            4 : 
    9545            4 :         let img_layer = (0..10)
    9546           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9547            4 :             .collect_vec();
    9548            4 : 
    9549            4 :         let delta1 = vec![
    9550            4 :             (
    9551            4 :                 get_key(1),
    9552            4 :                 Lsn(0x20),
    9553            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9554            4 :             ),
    9555            4 :             (
    9556            4 :                 get_key(1),
    9557            4 :                 Lsn(0x28),
    9558            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9559            4 :             ),
    9560            4 :         ];
    9561            4 :         let delta2 = vec![
    9562            4 :             (
    9563            4 :                 get_key(1),
    9564            4 :                 Lsn(0x30),
    9565            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9566            4 :             ),
    9567            4 :             (
    9568            4 :                 get_key(1),
    9569            4 :                 Lsn(0x38),
    9570            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9571            4 :             ),
    9572            4 :         ];
    9573            4 :         let delta3 = vec![
    9574            4 :             (
    9575            4 :                 get_key(8),
    9576            4 :                 Lsn(0x48),
    9577            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9578            4 :             ),
    9579            4 :             (
    9580            4 :                 get_key(9),
    9581            4 :                 Lsn(0x48),
    9582            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9583            4 :             ),
    9584            4 :         ];
    9585            4 : 
    9586            4 :         let tline = tenant
    9587            4 :             .create_test_timeline_with_layers(
    9588            4 :                 TIMELINE_ID,
    9589            4 :                 Lsn(0x10),
    9590            4 :                 DEFAULT_PG_VERSION,
    9591            4 :                 &ctx,
    9592            4 :                 vec![
    9593            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9594            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9595            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9596            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9597            4 :                 ], // delta layers
    9598            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9599            4 :                 Lsn(0x50),
    9600            4 :             )
    9601            4 :             .await?;
    9602            4 :         {
    9603            4 :             tline
    9604            4 :                 .latest_gc_cutoff_lsn
    9605            4 :                 .lock_for_write()
    9606            4 :                 .store_and_unlock(Lsn(0x30))
    9607            4 :                 .wait()
    9608            4 :                 .await;
    9609            4 :             // Update GC info
    9610            4 :             let mut guard = tline.gc_info.write().unwrap();
    9611            4 :             *guard = GcInfo {
    9612            4 :                 retain_lsns: vec![
    9613            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9614            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9615            4 :                 ],
    9616            4 :                 cutoffs: GcCutoffs {
    9617            4 :                     time: Lsn(0x30),
    9618            4 :                     space: Lsn(0x30),
    9619            4 :                 },
    9620            4 :                 leases: Default::default(),
    9621            4 :                 within_ancestor_pitr: false,
    9622            4 :             };
    9623            4 :         }
    9624            4 : 
    9625            4 :         let expected_result = [
    9626            4 :             Bytes::from_static(b"value 0@0x10"),
    9627            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9628            4 :             Bytes::from_static(b"value 2@0x10"),
    9629            4 :             Bytes::from_static(b"value 3@0x10"),
    9630            4 :             Bytes::from_static(b"value 4@0x10"),
    9631            4 :             Bytes::from_static(b"value 5@0x10"),
    9632            4 :             Bytes::from_static(b"value 6@0x10"),
    9633            4 :             Bytes::from_static(b"value 7@0x10"),
    9634            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9635            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9636            4 :         ];
    9637            4 : 
    9638            4 :         let expected_result_at_gc_horizon = [
    9639            4 :             Bytes::from_static(b"value 0@0x10"),
    9640            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9641            4 :             Bytes::from_static(b"value 2@0x10"),
    9642            4 :             Bytes::from_static(b"value 3@0x10"),
    9643            4 :             Bytes::from_static(b"value 4@0x10"),
    9644            4 :             Bytes::from_static(b"value 5@0x10"),
    9645            4 :             Bytes::from_static(b"value 6@0x10"),
    9646            4 :             Bytes::from_static(b"value 7@0x10"),
    9647            4 :             Bytes::from_static(b"value 8@0x10"),
    9648            4 :             Bytes::from_static(b"value 9@0x10"),
    9649            4 :         ];
    9650            4 : 
    9651            4 :         let expected_result_at_lsn_20 = [
    9652            4 :             Bytes::from_static(b"value 0@0x10"),
    9653            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9654            4 :             Bytes::from_static(b"value 2@0x10"),
    9655            4 :             Bytes::from_static(b"value 3@0x10"),
    9656            4 :             Bytes::from_static(b"value 4@0x10"),
    9657            4 :             Bytes::from_static(b"value 5@0x10"),
    9658            4 :             Bytes::from_static(b"value 6@0x10"),
    9659            4 :             Bytes::from_static(b"value 7@0x10"),
    9660            4 :             Bytes::from_static(b"value 8@0x10"),
    9661            4 :             Bytes::from_static(b"value 9@0x10"),
    9662            4 :         ];
    9663            4 : 
    9664            4 :         let expected_result_at_lsn_10 = [
    9665            4 :             Bytes::from_static(b"value 0@0x10"),
    9666            4 :             Bytes::from_static(b"value 1@0x10"),
    9667            4 :             Bytes::from_static(b"value 2@0x10"),
    9668            4 :             Bytes::from_static(b"value 3@0x10"),
    9669            4 :             Bytes::from_static(b"value 4@0x10"),
    9670            4 :             Bytes::from_static(b"value 5@0x10"),
    9671            4 :             Bytes::from_static(b"value 6@0x10"),
    9672            4 :             Bytes::from_static(b"value 7@0x10"),
    9673            4 :             Bytes::from_static(b"value 8@0x10"),
    9674            4 :             Bytes::from_static(b"value 9@0x10"),
    9675            4 :         ];
    9676            4 : 
    9677           16 :         let verify_result = || async {
    9678           16 :             let gc_horizon = {
    9679           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9680           16 :                 gc_info.cutoffs.time
    9681            4 :             };
    9682          176 :             for idx in 0..10 {
    9683          160 :                 assert_eq!(
    9684          160 :                     tline
    9685          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9686          160 :                         .await
    9687          160 :                         .unwrap(),
    9688          160 :                     &expected_result[idx]
    9689            4 :                 );
    9690          160 :                 assert_eq!(
    9691          160 :                     tline
    9692          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9693          160 :                         .await
    9694          160 :                         .unwrap(),
    9695          160 :                     &expected_result_at_gc_horizon[idx]
    9696            4 :                 );
    9697          160 :                 assert_eq!(
    9698          160 :                     tline
    9699          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9700          160 :                         .await
    9701          160 :                         .unwrap(),
    9702          160 :                     &expected_result_at_lsn_20[idx]
    9703            4 :                 );
    9704          160 :                 assert_eq!(
    9705          160 :                     tline
    9706          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9707          160 :                         .await
    9708          160 :                         .unwrap(),
    9709          160 :                     &expected_result_at_lsn_10[idx]
    9710            4 :                 );
    9711            4 :             }
    9712           32 :         };
    9713            4 : 
    9714            4 :         verify_result().await;
    9715            4 : 
    9716            4 :         let cancel = CancellationToken::new();
    9717            4 :         let mut dryrun_flags = EnumSet::new();
    9718            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9719            4 : 
    9720            4 :         tline
    9721            4 :             .compact_with_gc(
    9722            4 :                 &cancel,
    9723            4 :                 CompactOptions {
    9724            4 :                     flags: dryrun_flags,
    9725            4 :                     ..Default::default()
    9726            4 :                 },
    9727            4 :                 &ctx,
    9728            4 :             )
    9729            4 :             .await
    9730            4 :             .unwrap();
    9731            4 :         // 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
    9732            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9733            4 :         verify_result().await;
    9734            4 : 
    9735            4 :         tline
    9736            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9737            4 :             .await
    9738            4 :             .unwrap();
    9739            4 :         verify_result().await;
    9740            4 : 
    9741            4 :         // compact again
    9742            4 :         tline
    9743            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9744            4 :             .await
    9745            4 :             .unwrap();
    9746            4 :         verify_result().await;
    9747            4 : 
    9748            4 :         Ok(())
    9749            4 :     }
    9750              : 
    9751              :     #[cfg(feature = "testing")]
    9752              :     #[tokio::test]
    9753            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9754            4 :         use models::CompactLsnRange;
    9755            4 : 
    9756            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9757            4 :         let (tenant, ctx) = harness.load().await;
    9758            4 : 
    9759          332 :         fn get_key(id: u32) -> Key {
    9760          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9761          332 :             key.field6 = id;
    9762          332 :             key
    9763          332 :         }
    9764            4 : 
    9765            4 :         let img_layer = (0..10)
    9766           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9767            4 :             .collect_vec();
    9768            4 : 
    9769            4 :         let delta1 = vec![
    9770            4 :             (
    9771            4 :                 get_key(1),
    9772            4 :                 Lsn(0x20),
    9773            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9774            4 :             ),
    9775            4 :             (
    9776            4 :                 get_key(2),
    9777            4 :                 Lsn(0x30),
    9778            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9779            4 :             ),
    9780            4 :             (
    9781            4 :                 get_key(3),
    9782            4 :                 Lsn(0x28),
    9783            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9784            4 :             ),
    9785            4 :             (
    9786            4 :                 get_key(3),
    9787            4 :                 Lsn(0x30),
    9788            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9789            4 :             ),
    9790            4 :             (
    9791            4 :                 get_key(3),
    9792            4 :                 Lsn(0x40),
    9793            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9794            4 :             ),
    9795            4 :         ];
    9796            4 :         let delta2 = vec![
    9797            4 :             (
    9798            4 :                 get_key(5),
    9799            4 :                 Lsn(0x20),
    9800            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9801            4 :             ),
    9802            4 :             (
    9803            4 :                 get_key(6),
    9804            4 :                 Lsn(0x20),
    9805            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9806            4 :             ),
    9807            4 :         ];
    9808            4 :         let delta3 = vec![
    9809            4 :             (
    9810            4 :                 get_key(8),
    9811            4 :                 Lsn(0x48),
    9812            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9813            4 :             ),
    9814            4 :             (
    9815            4 :                 get_key(9),
    9816            4 :                 Lsn(0x48),
    9817            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9818            4 :             ),
    9819            4 :         ];
    9820            4 : 
    9821            4 :         let parent_tline = tenant
    9822            4 :             .create_test_timeline_with_layers(
    9823            4 :                 TIMELINE_ID,
    9824            4 :                 Lsn(0x10),
    9825            4 :                 DEFAULT_PG_VERSION,
    9826            4 :                 &ctx,
    9827            4 :                 vec![],                       // delta layers
    9828            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9829            4 :                 Lsn(0x18),
    9830            4 :             )
    9831            4 :             .await?;
    9832            4 : 
    9833            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9834            4 : 
    9835            4 :         let branch_tline = tenant
    9836            4 :             .branch_timeline_test_with_layers(
    9837            4 :                 &parent_tline,
    9838            4 :                 NEW_TIMELINE_ID,
    9839            4 :                 Some(Lsn(0x18)),
    9840            4 :                 &ctx,
    9841            4 :                 vec![
    9842            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9843            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9844            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9845            4 :                 ], // delta layers
    9846            4 :                 vec![], // image layers
    9847            4 :                 Lsn(0x50),
    9848            4 :             )
    9849            4 :             .await?;
    9850            4 : 
    9851            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9852            4 : 
    9853            4 :         {
    9854            4 :             parent_tline
    9855            4 :                 .latest_gc_cutoff_lsn
    9856            4 :                 .lock_for_write()
    9857            4 :                 .store_and_unlock(Lsn(0x10))
    9858            4 :                 .wait()
    9859            4 :                 .await;
    9860            4 :             // Update GC info
    9861            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9862            4 :             *guard = GcInfo {
    9863            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9864            4 :                 cutoffs: GcCutoffs {
    9865            4 :                     time: Lsn(0x10),
    9866            4 :                     space: Lsn(0x10),
    9867            4 :                 },
    9868            4 :                 leases: Default::default(),
    9869            4 :                 within_ancestor_pitr: false,
    9870            4 :             };
    9871            4 :         }
    9872            4 : 
    9873            4 :         {
    9874            4 :             branch_tline
    9875            4 :                 .latest_gc_cutoff_lsn
    9876            4 :                 .lock_for_write()
    9877            4 :                 .store_and_unlock(Lsn(0x50))
    9878            4 :                 .wait()
    9879            4 :                 .await;
    9880            4 :             // Update GC info
    9881            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9882            4 :             *guard = GcInfo {
    9883            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9884            4 :                 cutoffs: GcCutoffs {
    9885            4 :                     time: Lsn(0x50),
    9886            4 :                     space: Lsn(0x50),
    9887            4 :                 },
    9888            4 :                 leases: Default::default(),
    9889            4 :                 within_ancestor_pitr: false,
    9890            4 :             };
    9891            4 :         }
    9892            4 : 
    9893            4 :         let expected_result_at_gc_horizon = [
    9894            4 :             Bytes::from_static(b"value 0@0x10"),
    9895            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9896            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9897            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9898            4 :             Bytes::from_static(b"value 4@0x10"),
    9899            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9900            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9901            4 :             Bytes::from_static(b"value 7@0x10"),
    9902            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9903            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9904            4 :         ];
    9905            4 : 
    9906            4 :         let expected_result_at_lsn_40 = [
    9907            4 :             Bytes::from_static(b"value 0@0x10"),
    9908            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9909            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9910            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9911            4 :             Bytes::from_static(b"value 4@0x10"),
    9912            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9913            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9914            4 :             Bytes::from_static(b"value 7@0x10"),
    9915            4 :             Bytes::from_static(b"value 8@0x10"),
    9916            4 :             Bytes::from_static(b"value 9@0x10"),
    9917            4 :         ];
    9918            4 : 
    9919           12 :         let verify_result = || async {
    9920          132 :             for idx in 0..10 {
    9921          120 :                 assert_eq!(
    9922          120 :                     branch_tline
    9923          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9924          120 :                         .await
    9925          120 :                         .unwrap(),
    9926          120 :                     &expected_result_at_gc_horizon[idx]
    9927            4 :                 );
    9928          120 :                 assert_eq!(
    9929          120 :                     branch_tline
    9930          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9931          120 :                         .await
    9932          120 :                         .unwrap(),
    9933          120 :                     &expected_result_at_lsn_40[idx]
    9934            4 :                 );
    9935            4 :             }
    9936           24 :         };
    9937            4 : 
    9938            4 :         verify_result().await;
    9939            4 : 
    9940            4 :         let cancel = CancellationToken::new();
    9941            4 :         branch_tline
    9942            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9943            4 :             .await
    9944            4 :             .unwrap();
    9945            4 : 
    9946            4 :         verify_result().await;
    9947            4 : 
    9948            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
    9949            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
    9950            4 :         branch_tline
    9951            4 :             .compact_with_gc(
    9952            4 :                 &cancel,
    9953            4 :                 CompactOptions {
    9954            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
    9955            4 :                     ..Default::default()
    9956            4 :                 },
    9957            4 :                 &ctx,
    9958            4 :             )
    9959            4 :             .await
    9960            4 :             .unwrap();
    9961            4 : 
    9962            4 :         verify_result().await;
    9963            4 : 
    9964            4 :         Ok(())
    9965            4 :     }
    9966              : 
    9967              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9968              :     // Create an image arrangement where we have to read at different LSN ranges
    9969              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9970              :     // a delta layer. Like so:
    9971              :     //
    9972              :     //     A      B
    9973              :     // +----------------+ -> delta_layer
    9974              :     // |                |                           ^ lsn
    9975              :     // |       =========|-> nested_image_layer      |
    9976              :     // |       C        |                           |
    9977              :     // +----------------+                           |
    9978              :     // ======== -> baseline_image_layer             +-------> key
    9979              :     //
    9980              :     //
    9981              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9982              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9983              :     #[cfg(feature = "testing")]
    9984              :     #[tokio::test]
    9985            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9986            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9987            4 :         let (tenant, ctx) = harness.load().await;
    9988            4 : 
    9989            4 :         let will_init_keys = [2, 6];
    9990           88 :         fn get_key(id: u32) -> Key {
    9991           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9992           88 :             key.field6 = id;
    9993           88 :             key
    9994           88 :         }
    9995            4 : 
    9996            4 :         let mut expected_key_values = HashMap::new();
    9997            4 : 
    9998            4 :         let baseline_image_layer_lsn = Lsn(0x10);
    9999            4 :         let mut baseline_img_layer = Vec::new();
   10000           24 :         for i in 0..5 {
   10001           20 :             let key = get_key(i);
   10002           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10003           20 : 
   10004           20 :             let removed = expected_key_values.insert(key, value.clone());
   10005           20 :             assert!(removed.is_none());
   10006            4 : 
   10007           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10008            4 :         }
   10009            4 : 
   10010            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10011            4 :         let mut nested_img_layer = Vec::new();
   10012           24 :         for i in 5..10 {
   10013           20 :             let key = get_key(i);
   10014           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10015           20 : 
   10016           20 :             let removed = expected_key_values.insert(key, value.clone());
   10017           20 :             assert!(removed.is_none());
   10018            4 : 
   10019           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10020            4 :         }
   10021            4 : 
   10022            4 :         let mut delta_layer_spec = Vec::default();
   10023            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10024            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10025            4 : 
   10026           44 :         for i in 0..10 {
   10027           40 :             let key = get_key(i);
   10028           40 :             let key_in_nested = nested_img_layer
   10029           40 :                 .iter()
   10030          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10031           40 :             let lsn = {
   10032           40 :                 if key_in_nested {
   10033           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10034            4 :                 } else {
   10035           20 :                     delta_layer_start_lsn
   10036            4 :                 }
   10037            4 :             };
   10038            4 : 
   10039           40 :             let will_init = will_init_keys.contains(&i);
   10040           40 :             if will_init {
   10041            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10042            8 : 
   10043            8 :                 expected_key_values.insert(key, "".to_string());
   10044           32 :             } else {
   10045           32 :                 let delta = format!("@{lsn}");
   10046           32 :                 delta_layer_spec.push((
   10047           32 :                     key,
   10048           32 :                     lsn,
   10049           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10050           32 :                 ));
   10051           32 : 
   10052           32 :                 expected_key_values
   10053           32 :                     .get_mut(&key)
   10054           32 :                     .expect("An image exists for each key")
   10055           32 :                     .push_str(delta.as_str());
   10056           32 :             }
   10057           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10058            4 :         }
   10059            4 : 
   10060            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10061            4 : 
   10062            4 :         assert!(
   10063            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10064            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10065            4 :         );
   10066            4 : 
   10067            4 :         let tline = tenant
   10068            4 :             .create_test_timeline_with_layers(
   10069            4 :                 TIMELINE_ID,
   10070            4 :                 baseline_image_layer_lsn,
   10071            4 :                 DEFAULT_PG_VERSION,
   10072            4 :                 &ctx,
   10073            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10074            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10075            4 :                     delta_layer_spec,
   10076            4 :                 )], // delta layers
   10077            4 :                 vec![
   10078            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10079            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10080            4 :                 ], // image layers
   10081            4 :                 delta_layer_end_lsn,
   10082            4 :             )
   10083            4 :             .await?;
   10084            4 : 
   10085            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10086            4 :         let results = tline
   10087            4 :             .get_vectored(
   10088            4 :                 keyspace,
   10089            4 :                 delta_layer_end_lsn,
   10090            4 :                 IoConcurrency::sequential(),
   10091            4 :                 &ctx,
   10092            4 :             )
   10093            4 :             .await
   10094            4 :             .expect("No vectored errors");
   10095           44 :         for (key, res) in results {
   10096           40 :             let value = res.expect("No key errors");
   10097           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10098           40 :             assert_eq!(value, Bytes::from(expected_value));
   10099            4 :         }
   10100            4 : 
   10101            4 :         Ok(())
   10102            4 :     }
   10103              : 
   10104          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10105          428 :         (
   10106          428 :             k1.is_delta,
   10107          428 :             k1.key_range.start,
   10108          428 :             k1.key_range.end,
   10109          428 :             k1.lsn_range.start,
   10110          428 :             k1.lsn_range.end,
   10111          428 :         )
   10112          428 :             .cmp(&(
   10113          428 :                 k2.is_delta,
   10114          428 :                 k2.key_range.start,
   10115          428 :                 k2.key_range.end,
   10116          428 :                 k2.lsn_range.start,
   10117          428 :                 k2.lsn_range.end,
   10118          428 :             ))
   10119          428 :     }
   10120              : 
   10121           48 :     async fn inspect_and_sort(
   10122           48 :         tline: &Arc<Timeline>,
   10123           48 :         filter: Option<std::ops::Range<Key>>,
   10124           48 :     ) -> Vec<PersistentLayerKey> {
   10125           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10126           48 :         if let Some(filter) = filter {
   10127          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10128           44 :         }
   10129           48 :         all_layers.sort_by(sort_layer_key);
   10130           48 :         all_layers
   10131           48 :     }
   10132              : 
   10133              :     #[cfg(feature = "testing")]
   10134           44 :     fn check_layer_map_key_eq(
   10135           44 :         mut left: Vec<PersistentLayerKey>,
   10136           44 :         mut right: Vec<PersistentLayerKey>,
   10137           44 :     ) {
   10138           44 :         left.sort_by(sort_layer_key);
   10139           44 :         right.sort_by(sort_layer_key);
   10140           44 :         if left != right {
   10141            0 :             eprintln!("---LEFT---");
   10142            0 :             for left in left.iter() {
   10143            0 :                 eprintln!("{}", left);
   10144            0 :             }
   10145            0 :             eprintln!("---RIGHT---");
   10146            0 :             for right in right.iter() {
   10147            0 :                 eprintln!("{}", right);
   10148            0 :             }
   10149            0 :             assert_eq!(left, right);
   10150           44 :         }
   10151           44 :     }
   10152              : 
   10153              :     #[cfg(feature = "testing")]
   10154              :     #[tokio::test]
   10155            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10156            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10157            4 :         let (tenant, ctx) = harness.load().await;
   10158            4 : 
   10159          364 :         fn get_key(id: u32) -> Key {
   10160          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10161          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10162          364 :             key.field6 = id;
   10163          364 :             key
   10164          364 :         }
   10165            4 : 
   10166            4 :         // img layer at 0x10
   10167            4 :         let img_layer = (0..10)
   10168           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10169            4 :             .collect_vec();
   10170            4 : 
   10171            4 :         let delta1 = vec![
   10172            4 :             (
   10173            4 :                 get_key(1),
   10174            4 :                 Lsn(0x20),
   10175            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10176            4 :             ),
   10177            4 :             (
   10178            4 :                 get_key(2),
   10179            4 :                 Lsn(0x30),
   10180            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10181            4 :             ),
   10182            4 :             (
   10183            4 :                 get_key(3),
   10184            4 :                 Lsn(0x40),
   10185            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10186            4 :             ),
   10187            4 :         ];
   10188            4 :         let delta2 = vec![
   10189            4 :             (
   10190            4 :                 get_key(5),
   10191            4 :                 Lsn(0x20),
   10192            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10193            4 :             ),
   10194            4 :             (
   10195            4 :                 get_key(6),
   10196            4 :                 Lsn(0x20),
   10197            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10198            4 :             ),
   10199            4 :         ];
   10200            4 :         let delta3 = vec![
   10201            4 :             (
   10202            4 :                 get_key(8),
   10203            4 :                 Lsn(0x48),
   10204            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10205            4 :             ),
   10206            4 :             (
   10207            4 :                 get_key(9),
   10208            4 :                 Lsn(0x48),
   10209            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10210            4 :             ),
   10211            4 :         ];
   10212            4 : 
   10213            4 :         let tline = tenant
   10214            4 :             .create_test_timeline_with_layers(
   10215            4 :                 TIMELINE_ID,
   10216            4 :                 Lsn(0x10),
   10217            4 :                 DEFAULT_PG_VERSION,
   10218            4 :                 &ctx,
   10219            4 :                 vec![
   10220            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10221            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10222            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10223            4 :                 ], // delta layers
   10224            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10225            4 :                 Lsn(0x50),
   10226            4 :             )
   10227            4 :             .await?;
   10228            4 : 
   10229            4 :         {
   10230            4 :             tline
   10231            4 :                 .latest_gc_cutoff_lsn
   10232            4 :                 .lock_for_write()
   10233            4 :                 .store_and_unlock(Lsn(0x30))
   10234            4 :                 .wait()
   10235            4 :                 .await;
   10236            4 :             // Update GC info
   10237            4 :             let mut guard = tline.gc_info.write().unwrap();
   10238            4 :             *guard = GcInfo {
   10239            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10240            4 :                 cutoffs: GcCutoffs {
   10241            4 :                     time: Lsn(0x30),
   10242            4 :                     space: Lsn(0x30),
   10243            4 :                 },
   10244            4 :                 leases: Default::default(),
   10245            4 :                 within_ancestor_pitr: false,
   10246            4 :             };
   10247            4 :         }
   10248            4 : 
   10249            4 :         let cancel = CancellationToken::new();
   10250            4 : 
   10251            4 :         // Do a partial compaction on key range 0..2
   10252            4 :         tline
   10253            4 :             .compact_with_gc(
   10254            4 :                 &cancel,
   10255            4 :                 CompactOptions {
   10256            4 :                     flags: EnumSet::new(),
   10257            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10258            4 :                     ..Default::default()
   10259            4 :                 },
   10260            4 :                 &ctx,
   10261            4 :             )
   10262            4 :             .await
   10263            4 :             .unwrap();
   10264            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10265            4 :         check_layer_map_key_eq(
   10266            4 :             all_layers,
   10267            4 :             vec![
   10268            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10269            4 :                 PersistentLayerKey {
   10270            4 :                     key_range: get_key(0)..get_key(2),
   10271            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10272            4 :                     is_delta: false,
   10273            4 :                 },
   10274            4 :                 PersistentLayerKey {
   10275            4 :                     key_range: get_key(0)..get_key(10),
   10276            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10277            4 :                     is_delta: false,
   10278            4 :                 },
   10279            4 :                 // delta1 is split and the second part is rewritten
   10280            4 :                 PersistentLayerKey {
   10281            4 :                     key_range: get_key(2)..get_key(4),
   10282            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10283            4 :                     is_delta: true,
   10284            4 :                 },
   10285            4 :                 PersistentLayerKey {
   10286            4 :                     key_range: get_key(5)..get_key(7),
   10287            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10288            4 :                     is_delta: true,
   10289            4 :                 },
   10290            4 :                 PersistentLayerKey {
   10291            4 :                     key_range: get_key(8)..get_key(10),
   10292            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10293            4 :                     is_delta: true,
   10294            4 :                 },
   10295            4 :             ],
   10296            4 :         );
   10297            4 : 
   10298            4 :         // Do a partial compaction on key range 2..4
   10299            4 :         tline
   10300            4 :             .compact_with_gc(
   10301            4 :                 &cancel,
   10302            4 :                 CompactOptions {
   10303            4 :                     flags: EnumSet::new(),
   10304            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10305            4 :                     ..Default::default()
   10306            4 :                 },
   10307            4 :                 &ctx,
   10308            4 :             )
   10309            4 :             .await
   10310            4 :             .unwrap();
   10311            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10312            4 :         check_layer_map_key_eq(
   10313            4 :             all_layers,
   10314            4 :             vec![
   10315            4 :                 PersistentLayerKey {
   10316            4 :                     key_range: get_key(0)..get_key(2),
   10317            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10318            4 :                     is_delta: false,
   10319            4 :                 },
   10320            4 :                 PersistentLayerKey {
   10321            4 :                     key_range: get_key(0)..get_key(10),
   10322            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10323            4 :                     is_delta: false,
   10324            4 :                 },
   10325            4 :                 // image layer generated for the compaction range 2-4
   10326            4 :                 PersistentLayerKey {
   10327            4 :                     key_range: get_key(2)..get_key(4),
   10328            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10329            4 :                     is_delta: false,
   10330            4 :                 },
   10331            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10332            4 :                 PersistentLayerKey {
   10333            4 :                     key_range: get_key(2)..get_key(4),
   10334            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10335            4 :                     is_delta: true,
   10336            4 :                 },
   10337            4 :                 PersistentLayerKey {
   10338            4 :                     key_range: get_key(5)..get_key(7),
   10339            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10340            4 :                     is_delta: true,
   10341            4 :                 },
   10342            4 :                 PersistentLayerKey {
   10343            4 :                     key_range: get_key(8)..get_key(10),
   10344            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10345            4 :                     is_delta: true,
   10346            4 :                 },
   10347            4 :             ],
   10348            4 :         );
   10349            4 : 
   10350            4 :         // Do a partial compaction on key range 4..9
   10351            4 :         tline
   10352            4 :             .compact_with_gc(
   10353            4 :                 &cancel,
   10354            4 :                 CompactOptions {
   10355            4 :                     flags: EnumSet::new(),
   10356            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10357            4 :                     ..Default::default()
   10358            4 :                 },
   10359            4 :                 &ctx,
   10360            4 :             )
   10361            4 :             .await
   10362            4 :             .unwrap();
   10363            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10364            4 :         check_layer_map_key_eq(
   10365            4 :             all_layers,
   10366            4 :             vec![
   10367            4 :                 PersistentLayerKey {
   10368            4 :                     key_range: get_key(0)..get_key(2),
   10369            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10370            4 :                     is_delta: false,
   10371            4 :                 },
   10372            4 :                 PersistentLayerKey {
   10373            4 :                     key_range: get_key(0)..get_key(10),
   10374            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10375            4 :                     is_delta: false,
   10376            4 :                 },
   10377            4 :                 PersistentLayerKey {
   10378            4 :                     key_range: get_key(2)..get_key(4),
   10379            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10380            4 :                     is_delta: false,
   10381            4 :                 },
   10382            4 :                 PersistentLayerKey {
   10383            4 :                     key_range: get_key(2)..get_key(4),
   10384            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10385            4 :                     is_delta: true,
   10386            4 :                 },
   10387            4 :                 // image layer generated for this compaction range
   10388            4 :                 PersistentLayerKey {
   10389            4 :                     key_range: get_key(4)..get_key(9),
   10390            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10391            4 :                     is_delta: false,
   10392            4 :                 },
   10393            4 :                 PersistentLayerKey {
   10394            4 :                     key_range: get_key(8)..get_key(10),
   10395            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10396            4 :                     is_delta: true,
   10397            4 :                 },
   10398            4 :             ],
   10399            4 :         );
   10400            4 : 
   10401            4 :         // Do a partial compaction on key range 9..10
   10402            4 :         tline
   10403            4 :             .compact_with_gc(
   10404            4 :                 &cancel,
   10405            4 :                 CompactOptions {
   10406            4 :                     flags: EnumSet::new(),
   10407            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10408            4 :                     ..Default::default()
   10409            4 :                 },
   10410            4 :                 &ctx,
   10411            4 :             )
   10412            4 :             .await
   10413            4 :             .unwrap();
   10414            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10415            4 :         check_layer_map_key_eq(
   10416            4 :             all_layers,
   10417            4 :             vec![
   10418            4 :                 PersistentLayerKey {
   10419            4 :                     key_range: get_key(0)..get_key(2),
   10420            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10421            4 :                     is_delta: false,
   10422            4 :                 },
   10423            4 :                 PersistentLayerKey {
   10424            4 :                     key_range: get_key(0)..get_key(10),
   10425            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10426            4 :                     is_delta: false,
   10427            4 :                 },
   10428            4 :                 PersistentLayerKey {
   10429            4 :                     key_range: get_key(2)..get_key(4),
   10430            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10431            4 :                     is_delta: false,
   10432            4 :                 },
   10433            4 :                 PersistentLayerKey {
   10434            4 :                     key_range: get_key(2)..get_key(4),
   10435            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10436            4 :                     is_delta: true,
   10437            4 :                 },
   10438            4 :                 PersistentLayerKey {
   10439            4 :                     key_range: get_key(4)..get_key(9),
   10440            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10441            4 :                     is_delta: false,
   10442            4 :                 },
   10443            4 :                 // image layer generated for the compaction range
   10444            4 :                 PersistentLayerKey {
   10445            4 :                     key_range: get_key(9)..get_key(10),
   10446            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10447            4 :                     is_delta: false,
   10448            4 :                 },
   10449            4 :                 PersistentLayerKey {
   10450            4 :                     key_range: get_key(8)..get_key(10),
   10451            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10452            4 :                     is_delta: true,
   10453            4 :                 },
   10454            4 :             ],
   10455            4 :         );
   10456            4 : 
   10457            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10458            4 :         tline
   10459            4 :             .compact_with_gc(
   10460            4 :                 &cancel,
   10461            4 :                 CompactOptions {
   10462            4 :                     flags: EnumSet::new(),
   10463            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10464            4 :                     ..Default::default()
   10465            4 :                 },
   10466            4 :                 &ctx,
   10467            4 :             )
   10468            4 :             .await
   10469            4 :             .unwrap();
   10470            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10471            4 :         check_layer_map_key_eq(
   10472            4 :             all_layers,
   10473            4 :             vec![
   10474            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10475            4 :                 PersistentLayerKey {
   10476            4 :                     key_range: get_key(0)..get_key(10),
   10477            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10478            4 :                     is_delta: false,
   10479            4 :                 },
   10480            4 :                 PersistentLayerKey {
   10481            4 :                     key_range: get_key(2)..get_key(4),
   10482            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10483            4 :                     is_delta: true,
   10484            4 :                 },
   10485            4 :                 PersistentLayerKey {
   10486            4 :                     key_range: get_key(8)..get_key(10),
   10487            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10488            4 :                     is_delta: true,
   10489            4 :                 },
   10490            4 :             ],
   10491            4 :         );
   10492            4 :         Ok(())
   10493            4 :     }
   10494              : 
   10495              :     #[cfg(feature = "testing")]
   10496              :     #[tokio::test]
   10497            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10498            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10499            4 :             .await
   10500            4 :             .unwrap();
   10501            4 :         let (tenant, ctx) = harness.load().await;
   10502            4 :         let tline_parent = tenant
   10503            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10504            4 :             .await
   10505            4 :             .unwrap();
   10506            4 :         let tline_child = tenant
   10507            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10508            4 :             .await
   10509            4 :             .unwrap();
   10510            4 :         {
   10511            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10512            4 :             assert_eq!(
   10513            4 :                 gc_info_parent.retain_lsns,
   10514            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10515            4 :             );
   10516            4 :         }
   10517            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10518            4 :         tline_child
   10519            4 :             .remote_client
   10520            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10521            4 :             .unwrap();
   10522            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10523            4 :         offload_timeline(&tenant, &tline_child)
   10524            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10525            4 :             .await.unwrap();
   10526            4 :         let child_timeline_id = tline_child.timeline_id;
   10527            4 :         Arc::try_unwrap(tline_child).unwrap();
   10528            4 : 
   10529            4 :         {
   10530            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10531            4 :             assert_eq!(
   10532            4 :                 gc_info_parent.retain_lsns,
   10533            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10534            4 :             );
   10535            4 :         }
   10536            4 : 
   10537            4 :         tenant
   10538            4 :             .get_offloaded_timeline(child_timeline_id)
   10539            4 :             .unwrap()
   10540            4 :             .defuse_for_tenant_drop();
   10541            4 : 
   10542            4 :         Ok(())
   10543            4 :     }
   10544              : 
   10545              :     #[cfg(feature = "testing")]
   10546              :     #[tokio::test]
   10547            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10548            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10549            4 :         let (tenant, ctx) = harness.load().await;
   10550            4 : 
   10551          592 :         fn get_key(id: u32) -> Key {
   10552          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10553          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10554          592 :             key.field6 = id;
   10555          592 :             key
   10556          592 :         }
   10557            4 : 
   10558            4 :         let img_layer = (0..10)
   10559           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10560            4 :             .collect_vec();
   10561            4 : 
   10562            4 :         let delta1 = vec![(
   10563            4 :             get_key(1),
   10564            4 :             Lsn(0x20),
   10565            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10566            4 :         )];
   10567            4 :         let delta4 = vec![(
   10568            4 :             get_key(1),
   10569            4 :             Lsn(0x28),
   10570            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10571            4 :         )];
   10572            4 :         let delta2 = vec![
   10573            4 :             (
   10574            4 :                 get_key(1),
   10575            4 :                 Lsn(0x30),
   10576            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10577            4 :             ),
   10578            4 :             (
   10579            4 :                 get_key(1),
   10580            4 :                 Lsn(0x38),
   10581            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10582            4 :             ),
   10583            4 :         ];
   10584            4 :         let delta3 = vec![
   10585            4 :             (
   10586            4 :                 get_key(8),
   10587            4 :                 Lsn(0x48),
   10588            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10589            4 :             ),
   10590            4 :             (
   10591            4 :                 get_key(9),
   10592            4 :                 Lsn(0x48),
   10593            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10594            4 :             ),
   10595            4 :         ];
   10596            4 : 
   10597            4 :         let tline = tenant
   10598            4 :             .create_test_timeline_with_layers(
   10599            4 :                 TIMELINE_ID,
   10600            4 :                 Lsn(0x10),
   10601            4 :                 DEFAULT_PG_VERSION,
   10602            4 :                 &ctx,
   10603            4 :                 vec![
   10604            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10605            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10606            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10607            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10608            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10609            4 :                 ], // delta layers
   10610            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10611            4 :                 Lsn(0x50),
   10612            4 :             )
   10613            4 :             .await?;
   10614            4 :         {
   10615            4 :             tline
   10616            4 :                 .latest_gc_cutoff_lsn
   10617            4 :                 .lock_for_write()
   10618            4 :                 .store_and_unlock(Lsn(0x30))
   10619            4 :                 .wait()
   10620            4 :                 .await;
   10621            4 :             // Update GC info
   10622            4 :             let mut guard = tline.gc_info.write().unwrap();
   10623            4 :             *guard = GcInfo {
   10624            4 :                 retain_lsns: vec![
   10625            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10626            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10627            4 :                 ],
   10628            4 :                 cutoffs: GcCutoffs {
   10629            4 :                     time: Lsn(0x30),
   10630            4 :                     space: Lsn(0x30),
   10631            4 :                 },
   10632            4 :                 leases: Default::default(),
   10633            4 :                 within_ancestor_pitr: false,
   10634            4 :             };
   10635            4 :         }
   10636            4 : 
   10637            4 :         let expected_result = [
   10638            4 :             Bytes::from_static(b"value 0@0x10"),
   10639            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10640            4 :             Bytes::from_static(b"value 2@0x10"),
   10641            4 :             Bytes::from_static(b"value 3@0x10"),
   10642            4 :             Bytes::from_static(b"value 4@0x10"),
   10643            4 :             Bytes::from_static(b"value 5@0x10"),
   10644            4 :             Bytes::from_static(b"value 6@0x10"),
   10645            4 :             Bytes::from_static(b"value 7@0x10"),
   10646            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10647            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10648            4 :         ];
   10649            4 : 
   10650            4 :         let expected_result_at_gc_horizon = [
   10651            4 :             Bytes::from_static(b"value 0@0x10"),
   10652            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10653            4 :             Bytes::from_static(b"value 2@0x10"),
   10654            4 :             Bytes::from_static(b"value 3@0x10"),
   10655            4 :             Bytes::from_static(b"value 4@0x10"),
   10656            4 :             Bytes::from_static(b"value 5@0x10"),
   10657            4 :             Bytes::from_static(b"value 6@0x10"),
   10658            4 :             Bytes::from_static(b"value 7@0x10"),
   10659            4 :             Bytes::from_static(b"value 8@0x10"),
   10660            4 :             Bytes::from_static(b"value 9@0x10"),
   10661            4 :         ];
   10662            4 : 
   10663            4 :         let expected_result_at_lsn_20 = [
   10664            4 :             Bytes::from_static(b"value 0@0x10"),
   10665            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10666            4 :             Bytes::from_static(b"value 2@0x10"),
   10667            4 :             Bytes::from_static(b"value 3@0x10"),
   10668            4 :             Bytes::from_static(b"value 4@0x10"),
   10669            4 :             Bytes::from_static(b"value 5@0x10"),
   10670            4 :             Bytes::from_static(b"value 6@0x10"),
   10671            4 :             Bytes::from_static(b"value 7@0x10"),
   10672            4 :             Bytes::from_static(b"value 8@0x10"),
   10673            4 :             Bytes::from_static(b"value 9@0x10"),
   10674            4 :         ];
   10675            4 : 
   10676            4 :         let expected_result_at_lsn_10 = [
   10677            4 :             Bytes::from_static(b"value 0@0x10"),
   10678            4 :             Bytes::from_static(b"value 1@0x10"),
   10679            4 :             Bytes::from_static(b"value 2@0x10"),
   10680            4 :             Bytes::from_static(b"value 3@0x10"),
   10681            4 :             Bytes::from_static(b"value 4@0x10"),
   10682            4 :             Bytes::from_static(b"value 5@0x10"),
   10683            4 :             Bytes::from_static(b"value 6@0x10"),
   10684            4 :             Bytes::from_static(b"value 7@0x10"),
   10685            4 :             Bytes::from_static(b"value 8@0x10"),
   10686            4 :             Bytes::from_static(b"value 9@0x10"),
   10687            4 :         ];
   10688            4 : 
   10689           12 :         let verify_result = || async {
   10690           12 :             let gc_horizon = {
   10691           12 :                 let gc_info = tline.gc_info.read().unwrap();
   10692           12 :                 gc_info.cutoffs.time
   10693            4 :             };
   10694          132 :             for idx in 0..10 {
   10695          120 :                 assert_eq!(
   10696          120 :                     tline
   10697          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10698          120 :                         .await
   10699          120 :                         .unwrap(),
   10700          120 :                     &expected_result[idx]
   10701            4 :                 );
   10702          120 :                 assert_eq!(
   10703          120 :                     tline
   10704          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10705          120 :                         .await
   10706          120 :                         .unwrap(),
   10707          120 :                     &expected_result_at_gc_horizon[idx]
   10708            4 :                 );
   10709          120 :                 assert_eq!(
   10710          120 :                     tline
   10711          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10712          120 :                         .await
   10713          120 :                         .unwrap(),
   10714          120 :                     &expected_result_at_lsn_20[idx]
   10715            4 :                 );
   10716          120 :                 assert_eq!(
   10717          120 :                     tline
   10718          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10719          120 :                         .await
   10720          120 :                         .unwrap(),
   10721          120 :                     &expected_result_at_lsn_10[idx]
   10722            4 :                 );
   10723            4 :             }
   10724           24 :         };
   10725            4 : 
   10726            4 :         verify_result().await;
   10727            4 : 
   10728            4 :         let cancel = CancellationToken::new();
   10729            4 :         tline
   10730            4 :             .compact_with_gc(
   10731            4 :                 &cancel,
   10732            4 :                 CompactOptions {
   10733            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10734            4 :                     ..Default::default()
   10735            4 :                 },
   10736            4 :                 &ctx,
   10737            4 :             )
   10738            4 :             .await
   10739            4 :             .unwrap();
   10740            4 :         verify_result().await;
   10741            4 : 
   10742            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10743            4 :         check_layer_map_key_eq(
   10744            4 :             all_layers,
   10745            4 :             vec![
   10746            4 :                 // The original image layer, not compacted
   10747            4 :                 PersistentLayerKey {
   10748            4 :                     key_range: get_key(0)..get_key(10),
   10749            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10750            4 :                     is_delta: false,
   10751            4 :                 },
   10752            4 :                 // Delta layer below the specified above_lsn not compacted
   10753            4 :                 PersistentLayerKey {
   10754            4 :                     key_range: get_key(1)..get_key(2),
   10755            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10756            4 :                     is_delta: true,
   10757            4 :                 },
   10758            4 :                 // Delta layer compacted above the LSN
   10759            4 :                 PersistentLayerKey {
   10760            4 :                     key_range: get_key(1)..get_key(10),
   10761            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10762            4 :                     is_delta: true,
   10763            4 :                 },
   10764            4 :             ],
   10765            4 :         );
   10766            4 : 
   10767            4 :         // compact again
   10768            4 :         tline
   10769            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10770            4 :             .await
   10771            4 :             .unwrap();
   10772            4 :         verify_result().await;
   10773            4 : 
   10774            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10775            4 :         check_layer_map_key_eq(
   10776            4 :             all_layers,
   10777            4 :             vec![
   10778            4 :                 // The compacted image layer (full key range)
   10779            4 :                 PersistentLayerKey {
   10780            4 :                     key_range: Key::MIN..Key::MAX,
   10781            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10782            4 :                     is_delta: false,
   10783            4 :                 },
   10784            4 :                 // All other data in the delta layer
   10785            4 :                 PersistentLayerKey {
   10786            4 :                     key_range: get_key(1)..get_key(10),
   10787            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10788            4 :                     is_delta: true,
   10789            4 :                 },
   10790            4 :             ],
   10791            4 :         );
   10792            4 : 
   10793            4 :         Ok(())
   10794            4 :     }
   10795              : 
   10796              :     #[cfg(feature = "testing")]
   10797              :     #[tokio::test]
   10798            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   10799            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   10800            4 :         let (tenant, ctx) = harness.load().await;
   10801            4 : 
   10802         1016 :         fn get_key(id: u32) -> Key {
   10803         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10804         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10805         1016 :             key.field6 = id;
   10806         1016 :             key
   10807         1016 :         }
   10808            4 : 
   10809            4 :         let img_layer = (0..10)
   10810           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10811            4 :             .collect_vec();
   10812            4 : 
   10813            4 :         let delta1 = vec![(
   10814            4 :             get_key(1),
   10815            4 :             Lsn(0x20),
   10816            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10817            4 :         )];
   10818            4 :         let delta4 = vec![(
   10819            4 :             get_key(1),
   10820            4 :             Lsn(0x28),
   10821            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10822            4 :         )];
   10823            4 :         let delta2 = vec![
   10824            4 :             (
   10825            4 :                 get_key(1),
   10826            4 :                 Lsn(0x30),
   10827            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10828            4 :             ),
   10829            4 :             (
   10830            4 :                 get_key(1),
   10831            4 :                 Lsn(0x38),
   10832            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10833            4 :             ),
   10834            4 :         ];
   10835            4 :         let delta3 = vec![
   10836            4 :             (
   10837            4 :                 get_key(8),
   10838            4 :                 Lsn(0x48),
   10839            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10840            4 :             ),
   10841            4 :             (
   10842            4 :                 get_key(9),
   10843            4 :                 Lsn(0x48),
   10844            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10845            4 :             ),
   10846            4 :         ];
   10847            4 : 
   10848            4 :         let tline = tenant
   10849            4 :             .create_test_timeline_with_layers(
   10850            4 :                 TIMELINE_ID,
   10851            4 :                 Lsn(0x10),
   10852            4 :                 DEFAULT_PG_VERSION,
   10853            4 :                 &ctx,
   10854            4 :                 vec![
   10855            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10856            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10857            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10858            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10859            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10860            4 :                 ], // delta layers
   10861            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10862            4 :                 Lsn(0x50),
   10863            4 :             )
   10864            4 :             .await?;
   10865            4 :         {
   10866            4 :             tline
   10867            4 :                 .latest_gc_cutoff_lsn
   10868            4 :                 .lock_for_write()
   10869            4 :                 .store_and_unlock(Lsn(0x30))
   10870            4 :                 .wait()
   10871            4 :                 .await;
   10872            4 :             // Update GC info
   10873            4 :             let mut guard = tline.gc_info.write().unwrap();
   10874            4 :             *guard = GcInfo {
   10875            4 :                 retain_lsns: vec![
   10876            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10877            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10878            4 :                 ],
   10879            4 :                 cutoffs: GcCutoffs {
   10880            4 :                     time: Lsn(0x30),
   10881            4 :                     space: Lsn(0x30),
   10882            4 :                 },
   10883            4 :                 leases: Default::default(),
   10884            4 :                 within_ancestor_pitr: false,
   10885            4 :             };
   10886            4 :         }
   10887            4 : 
   10888            4 :         let expected_result = [
   10889            4 :             Bytes::from_static(b"value 0@0x10"),
   10890            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10891            4 :             Bytes::from_static(b"value 2@0x10"),
   10892            4 :             Bytes::from_static(b"value 3@0x10"),
   10893            4 :             Bytes::from_static(b"value 4@0x10"),
   10894            4 :             Bytes::from_static(b"value 5@0x10"),
   10895            4 :             Bytes::from_static(b"value 6@0x10"),
   10896            4 :             Bytes::from_static(b"value 7@0x10"),
   10897            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10898            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10899            4 :         ];
   10900            4 : 
   10901            4 :         let expected_result_at_gc_horizon = [
   10902            4 :             Bytes::from_static(b"value 0@0x10"),
   10903            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10904            4 :             Bytes::from_static(b"value 2@0x10"),
   10905            4 :             Bytes::from_static(b"value 3@0x10"),
   10906            4 :             Bytes::from_static(b"value 4@0x10"),
   10907            4 :             Bytes::from_static(b"value 5@0x10"),
   10908            4 :             Bytes::from_static(b"value 6@0x10"),
   10909            4 :             Bytes::from_static(b"value 7@0x10"),
   10910            4 :             Bytes::from_static(b"value 8@0x10"),
   10911            4 :             Bytes::from_static(b"value 9@0x10"),
   10912            4 :         ];
   10913            4 : 
   10914            4 :         let expected_result_at_lsn_20 = [
   10915            4 :             Bytes::from_static(b"value 0@0x10"),
   10916            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10917            4 :             Bytes::from_static(b"value 2@0x10"),
   10918            4 :             Bytes::from_static(b"value 3@0x10"),
   10919            4 :             Bytes::from_static(b"value 4@0x10"),
   10920            4 :             Bytes::from_static(b"value 5@0x10"),
   10921            4 :             Bytes::from_static(b"value 6@0x10"),
   10922            4 :             Bytes::from_static(b"value 7@0x10"),
   10923            4 :             Bytes::from_static(b"value 8@0x10"),
   10924            4 :             Bytes::from_static(b"value 9@0x10"),
   10925            4 :         ];
   10926            4 : 
   10927            4 :         let expected_result_at_lsn_10 = [
   10928            4 :             Bytes::from_static(b"value 0@0x10"),
   10929            4 :             Bytes::from_static(b"value 1@0x10"),
   10930            4 :             Bytes::from_static(b"value 2@0x10"),
   10931            4 :             Bytes::from_static(b"value 3@0x10"),
   10932            4 :             Bytes::from_static(b"value 4@0x10"),
   10933            4 :             Bytes::from_static(b"value 5@0x10"),
   10934            4 :             Bytes::from_static(b"value 6@0x10"),
   10935            4 :             Bytes::from_static(b"value 7@0x10"),
   10936            4 :             Bytes::from_static(b"value 8@0x10"),
   10937            4 :             Bytes::from_static(b"value 9@0x10"),
   10938            4 :         ];
   10939            4 : 
   10940           20 :         let verify_result = || async {
   10941           20 :             let gc_horizon = {
   10942           20 :                 let gc_info = tline.gc_info.read().unwrap();
   10943           20 :                 gc_info.cutoffs.time
   10944            4 :             };
   10945          220 :             for idx in 0..10 {
   10946          200 :                 assert_eq!(
   10947          200 :                     tline
   10948          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10949          200 :                         .await
   10950          200 :                         .unwrap(),
   10951          200 :                     &expected_result[idx]
   10952            4 :                 );
   10953          200 :                 assert_eq!(
   10954          200 :                     tline
   10955          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10956          200 :                         .await
   10957          200 :                         .unwrap(),
   10958          200 :                     &expected_result_at_gc_horizon[idx]
   10959            4 :                 );
   10960          200 :                 assert_eq!(
   10961          200 :                     tline
   10962          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10963          200 :                         .await
   10964          200 :                         .unwrap(),
   10965          200 :                     &expected_result_at_lsn_20[idx]
   10966            4 :                 );
   10967          200 :                 assert_eq!(
   10968          200 :                     tline
   10969          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10970          200 :                         .await
   10971          200 :                         .unwrap(),
   10972          200 :                     &expected_result_at_lsn_10[idx]
   10973            4 :                 );
   10974            4 :             }
   10975           40 :         };
   10976            4 : 
   10977            4 :         verify_result().await;
   10978            4 : 
   10979            4 :         let cancel = CancellationToken::new();
   10980            4 : 
   10981            4 :         tline
   10982            4 :             .compact_with_gc(
   10983            4 :                 &cancel,
   10984            4 :                 CompactOptions {
   10985            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10986            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   10987            4 :                     ..Default::default()
   10988            4 :                 },
   10989            4 :                 &ctx,
   10990            4 :             )
   10991            4 :             .await
   10992            4 :             .unwrap();
   10993            4 :         verify_result().await;
   10994            4 : 
   10995            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10996            4 :         check_layer_map_key_eq(
   10997            4 :             all_layers,
   10998            4 :             vec![
   10999            4 :                 // The original image layer, not compacted
   11000            4 :                 PersistentLayerKey {
   11001            4 :                     key_range: get_key(0)..get_key(10),
   11002            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11003            4 :                     is_delta: false,
   11004            4 :                 },
   11005            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11006            4 :                 // the layer 0x28-0x30 into one.
   11007            4 :                 PersistentLayerKey {
   11008            4 :                     key_range: get_key(1)..get_key(2),
   11009            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11010            4 :                     is_delta: true,
   11011            4 :                 },
   11012            4 :                 // Above the upper bound and untouched
   11013            4 :                 PersistentLayerKey {
   11014            4 :                     key_range: get_key(1)..get_key(2),
   11015            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11016            4 :                     is_delta: true,
   11017            4 :                 },
   11018            4 :                 // This layer is untouched
   11019            4 :                 PersistentLayerKey {
   11020            4 :                     key_range: get_key(8)..get_key(10),
   11021            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11022            4 :                     is_delta: true,
   11023            4 :                 },
   11024            4 :             ],
   11025            4 :         );
   11026            4 : 
   11027            4 :         tline
   11028            4 :             .compact_with_gc(
   11029            4 :                 &cancel,
   11030            4 :                 CompactOptions {
   11031            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11032            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11033            4 :                     ..Default::default()
   11034            4 :                 },
   11035            4 :                 &ctx,
   11036            4 :             )
   11037            4 :             .await
   11038            4 :             .unwrap();
   11039            4 :         verify_result().await;
   11040            4 : 
   11041            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11042            4 :         check_layer_map_key_eq(
   11043            4 :             all_layers,
   11044            4 :             vec![
   11045            4 :                 // The original image layer, not compacted
   11046            4 :                 PersistentLayerKey {
   11047            4 :                     key_range: get_key(0)..get_key(10),
   11048            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11049            4 :                     is_delta: false,
   11050            4 :                 },
   11051            4 :                 // Not in the compaction key range, uncompacted
   11052            4 :                 PersistentLayerKey {
   11053            4 :                     key_range: get_key(1)..get_key(2),
   11054            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11055            4 :                     is_delta: true,
   11056            4 :                 },
   11057            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11058            4 :                 PersistentLayerKey {
   11059            4 :                     key_range: get_key(1)..get_key(2),
   11060            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11061            4 :                     is_delta: true,
   11062            4 :                 },
   11063            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11064            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11065            4 :                 // becomes 0x50.
   11066            4 :                 PersistentLayerKey {
   11067            4 :                     key_range: get_key(8)..get_key(10),
   11068            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11069            4 :                     is_delta: true,
   11070            4 :                 },
   11071            4 :             ],
   11072            4 :         );
   11073            4 : 
   11074            4 :         // compact again
   11075            4 :         tline
   11076            4 :             .compact_with_gc(
   11077            4 :                 &cancel,
   11078            4 :                 CompactOptions {
   11079            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11080            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11081            4 :                     ..Default::default()
   11082            4 :                 },
   11083            4 :                 &ctx,
   11084            4 :             )
   11085            4 :             .await
   11086            4 :             .unwrap();
   11087            4 :         verify_result().await;
   11088            4 : 
   11089            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11090            4 :         check_layer_map_key_eq(
   11091            4 :             all_layers,
   11092            4 :             vec![
   11093            4 :                 // The original image layer, not compacted
   11094            4 :                 PersistentLayerKey {
   11095            4 :                     key_range: get_key(0)..get_key(10),
   11096            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11097            4 :                     is_delta: false,
   11098            4 :                 },
   11099            4 :                 // The range gets compacted
   11100            4 :                 PersistentLayerKey {
   11101            4 :                     key_range: get_key(1)..get_key(2),
   11102            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11103            4 :                     is_delta: true,
   11104            4 :                 },
   11105            4 :                 // Not touched during this iteration of compaction
   11106            4 :                 PersistentLayerKey {
   11107            4 :                     key_range: get_key(8)..get_key(10),
   11108            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11109            4 :                     is_delta: true,
   11110            4 :                 },
   11111            4 :             ],
   11112            4 :         );
   11113            4 : 
   11114            4 :         // final full compaction
   11115            4 :         tline
   11116            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11117            4 :             .await
   11118            4 :             .unwrap();
   11119            4 :         verify_result().await;
   11120            4 : 
   11121            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11122            4 :         check_layer_map_key_eq(
   11123            4 :             all_layers,
   11124            4 :             vec![
   11125            4 :                 // The compacted image layer (full key range)
   11126            4 :                 PersistentLayerKey {
   11127            4 :                     key_range: Key::MIN..Key::MAX,
   11128            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11129            4 :                     is_delta: false,
   11130            4 :                 },
   11131            4 :                 // All other data in the delta layer
   11132            4 :                 PersistentLayerKey {
   11133            4 :                     key_range: get_key(1)..get_key(10),
   11134            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11135            4 :                     is_delta: true,
   11136            4 :                 },
   11137            4 :             ],
   11138            4 :         );
   11139            4 : 
   11140            4 :         Ok(())
   11141            4 :     }
   11142              : }
        

Generated by: LCOV version 2.1-beta