LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 47d527da5e8405637e322911c55c08727c2fd272.info Lines: 76.8 % 8397 6448
Test Date: 2025-01-16 17:37:50 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::TENANT;
      99              : use crate::metrics::{
     100              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
     101              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
     102              : };
     103              : use crate::task_mgr;
     104              : use crate::task_mgr::TaskKind;
     105              : use crate::tenant::config::LocationMode;
     106              : use crate::tenant::config::TenantConfOpt;
     107              : use crate::tenant::gc_result::GcResult;
     108              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     109              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     110              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     111              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     112              : use crate::tenant::storage_layer::DeltaLayer;
     113              : use crate::tenant::storage_layer::ImageLayer;
     114              : use crate::walingest::WalLagCooldown;
     115              : use crate::walredo;
     116              : use crate::InitializationOrder;
     117              : use std::collections::hash_map::Entry;
     118              : use std::collections::HashMap;
     119              : use std::collections::HashSet;
     120              : use std::fmt::Debug;
     121              : use std::fmt::Display;
     122              : use std::fs;
     123              : use std::fs::File;
     124              : use std::sync::atomic::{AtomicU64, Ordering};
     125              : use std::sync::Arc;
     126              : use std::sync::Mutex;
     127              : use std::time::{Duration, Instant};
     128              : 
     129              : use crate::span;
     130              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     131              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     132              : use crate::virtual_file::VirtualFile;
     133              : use crate::walredo::PostgresRedoManager;
     134              : use crate::TEMP_FILE_SUFFIX;
     135              : use once_cell::sync::Lazy;
     136              : pub use pageserver_api::models::TenantState;
     137              : use tokio::sync::Semaphore;
     138              : 
     139            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     140              : use utils::{
     141              :     crashsafe,
     142              :     generation::Generation,
     143              :     id::TimelineId,
     144              :     lsn::{Lsn, RecordLsn},
     145              : };
     146              : 
     147              : pub mod blob_io;
     148              : pub mod block_io;
     149              : pub mod vectored_blob_io;
     150              : 
     151              : pub mod disk_btree;
     152              : pub(crate) mod ephemeral_file;
     153              : pub mod layer_map;
     154              : 
     155              : pub mod metadata;
     156              : pub mod remote_timeline_client;
     157              : pub mod storage_layer;
     158              : 
     159              : pub mod checks;
     160              : pub mod config;
     161              : pub mod mgr;
     162              : pub mod secondary;
     163              : pub mod tasks;
     164              : pub mod upload_queue;
     165              : 
     166              : pub(crate) mod timeline;
     167              : 
     168              : pub mod size;
     169              : 
     170              : mod gc_block;
     171              : mod gc_result;
     172              : pub(crate) mod throttle;
     173              : 
     174              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     175              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     176              : 
     177              : // re-export for use in walreceiver
     178              : pub use crate::tenant::timeline::WalReceiverInfo;
     179              : 
     180              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     181              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     182              : 
     183              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     184              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     185              : 
     186              : /// References to shared objects that are passed into each tenant, such
     187              : /// as the shared remote storage client and process initialization state.
     188              : #[derive(Clone)]
     189              : pub struct TenantSharedResources {
     190              :     pub broker_client: storage_broker::BrokerClientChannel,
     191              :     pub remote_storage: GenericRemoteStorage,
     192              :     pub deletion_queue_client: DeletionQueueClient,
     193              :     pub l0_flush_global_state: L0FlushGlobalState,
     194              : }
     195              : 
     196              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     197              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     198              : /// in this struct.
     199              : #[derive(Clone)]
     200              : pub(super) struct AttachedTenantConf {
     201              :     tenant_conf: TenantConfOpt,
     202              :     location: AttachedLocationConfig,
     203              :     /// The deadline before which we are blocked from GC so that
     204              :     /// leases have a chance to be renewed.
     205              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     206              : }
     207              : 
     208              : impl AttachedTenantConf {
     209          220 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     210              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     211              :         //
     212              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     213              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     214              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     215          220 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     216          220 :             Some(
     217          220 :                 tokio::time::Instant::now()
     218          220 :                     + tenant_conf
     219          220 :                         .lsn_lease_length
     220          220 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     221          220 :             )
     222              :         } else {
     223              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     224              :             // because we don't do GC in these modes.
     225            0 :             None
     226              :         };
     227              : 
     228          220 :         Self {
     229          220 :             tenant_conf,
     230          220 :             location,
     231          220 :             lsn_lease_deadline,
     232          220 :         }
     233          220 :     }
     234              : 
     235          220 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     236          220 :         match &location_conf.mode {
     237          220 :             LocationMode::Attached(attach_conf) => {
     238          220 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     239              :             }
     240              :             LocationMode::Secondary(_) => {
     241            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     242              :             }
     243              :         }
     244          220 :     }
     245              : 
     246          762 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     247          762 :         self.lsn_lease_deadline
     248          762 :             .map(|d| tokio::time::Instant::now() < d)
     249          762 :             .unwrap_or(false)
     250          762 :     }
     251              : }
     252              : struct TimelinePreload {
     253              :     timeline_id: TimelineId,
     254              :     client: RemoteTimelineClient,
     255              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     256              : }
     257              : 
     258              : pub(crate) struct TenantPreload {
     259              :     tenant_manifest: TenantManifest,
     260              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     261              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     262              : }
     263              : 
     264              : /// When we spawn a tenant, there is a special mode for tenant creation that
     265              : /// avoids trying to read anything from remote storage.
     266              : pub(crate) enum SpawnMode {
     267              :     /// Activate as soon as possible
     268              :     Eager,
     269              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     270              :     Lazy,
     271              : }
     272              : 
     273              : ///
     274              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     275              : ///
     276              : pub struct Tenant {
     277              :     // Global pageserver config parameters
     278              :     pub conf: &'static PageServerConf,
     279              : 
     280              :     /// The value creation timestamp, used to measure activation delay, see:
     281              :     /// <https://github.com/neondatabase/neon/issues/4025>
     282              :     constructed_at: Instant,
     283              : 
     284              :     state: watch::Sender<TenantState>,
     285              : 
     286              :     // Overridden tenant-specific config parameters.
     287              :     // We keep TenantConfOpt sturct here to preserve the information
     288              :     // about parameters that are not set.
     289              :     // This is necessary to allow global config updates.
     290              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     291              : 
     292              :     tenant_shard_id: TenantShardId,
     293              : 
     294              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     295              :     shard_identity: ShardIdentity,
     296              : 
     297              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     298              :     /// Does not change over the lifetime of the [`Tenant`] object.
     299              :     ///
     300              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     301              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     302              :     generation: Generation,
     303              : 
     304              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     305              : 
     306              :     /// During timeline creation, we first insert the TimelineId to the
     307              :     /// creating map, then `timelines`, then remove it from the creating map.
     308              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     309              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     310              : 
     311              :     /// Possibly offloaded and archived timelines
     312              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     313              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     314              : 
     315              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     316              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     317              :     /// each other (this could be optimized to coalesce writes if necessary).
     318              :     ///
     319              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     320              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     321              : 
     322              :     // This mutex prevents creation of new timelines during GC.
     323              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     324              :     // `timelines` mutex during all GC iteration
     325              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     326              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     327              :     // timeout...
     328              :     gc_cs: tokio::sync::Mutex<()>,
     329              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     330              : 
     331              :     // provides access to timeline data sitting in the remote storage
     332              :     pub(crate) remote_storage: GenericRemoteStorage,
     333              : 
     334              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     335              :     deletion_queue_client: DeletionQueueClient,
     336              : 
     337              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     338              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     339              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     340              : 
     341              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     342              : 
     343              :     /// Track repeated failures to compact, so that we can back off.
     344              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     345              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     346              : 
     347              :     /// Scheduled gc-compaction tasks.
     348              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     349              : 
     350              :     /// If the tenant is in Activating state, notify this to encourage it
     351              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     352              :     /// background warmup.
     353              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     354              : 
     355              :     /// Time it took for the tenant to activate. Zero if not active yet.
     356              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     357              : 
     358              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     359              :     // Timelines' cancellation token.
     360              :     pub(crate) cancel: CancellationToken,
     361              : 
     362              :     // Users of the Tenant such as the page service must take this Gate to avoid
     363              :     // trying to use a Tenant which is shutting down.
     364              :     pub(crate) gate: Gate,
     365              : 
     366              :     /// Throttle applied at the top of [`Timeline::get`].
     367              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     368              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     369              : 
     370              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     371              : 
     372              :     /// An ongoing timeline detach concurrency limiter.
     373              :     ///
     374              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     375              :     /// to have two running at the same time. A different one can be started if an earlier one
     376              :     /// has failed for whatever reason.
     377              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     378              : 
     379              :     /// `index_part.json` based gc blocking reason tracking.
     380              :     ///
     381              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     382              :     /// proceeding.
     383              :     pub(crate) gc_block: gc_block::GcBlock,
     384              : 
     385              :     l0_flush_global_state: L0FlushGlobalState,
     386              : }
     387              : impl std::fmt::Debug for Tenant {
     388            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     389            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     390            0 :     }
     391              : }
     392              : 
     393              : pub(crate) enum WalRedoManager {
     394              :     Prod(WalredoManagerId, PostgresRedoManager),
     395              :     #[cfg(test)]
     396              :     Test(harness::TestRedoManager),
     397              : }
     398              : 
     399              : #[derive(thiserror::Error, Debug)]
     400              : #[error("pageserver is shutting down")]
     401              : pub(crate) struct GlobalShutDown;
     402              : 
     403              : impl WalRedoManager {
     404            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     405            0 :         let id = WalredoManagerId::next();
     406            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     407            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     408            0 :         match &mut *guard {
     409            0 :             Some(map) => {
     410            0 :                 map.insert(id, Arc::downgrade(&arc));
     411            0 :                 Ok(arc)
     412              :             }
     413            0 :             None => Err(GlobalShutDown),
     414              :         }
     415            0 :     }
     416              : }
     417              : 
     418              : impl Drop for WalRedoManager {
     419           10 :     fn drop(&mut self) {
     420           10 :         match self {
     421            0 :             Self::Prod(id, _) => {
     422            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     423            0 :                 if let Some(map) = &mut *guard {
     424            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     425            0 :                 }
     426              :             }
     427              :             #[cfg(test)]
     428           10 :             Self::Test(_) => {
     429           10 :                 // Not applicable to test redo manager
     430           10 :             }
     431              :         }
     432           10 :     }
     433              : }
     434              : 
     435              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     436              : /// the walredo processes outside of the regular order.
     437              : ///
     438              : /// This is necessary to work around a systemd bug where it freezes if there are
     439              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     440              : #[allow(clippy::type_complexity)]
     441              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     442              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     443            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     444              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     445              : pub(crate) struct WalredoManagerId(u64);
     446              : impl WalredoManagerId {
     447            0 :     pub fn next() -> Self {
     448              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     449            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     450            0 :         if id == 0 {
     451            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     452            0 :         }
     453            0 :         Self(id)
     454            0 :     }
     455              : }
     456              : 
     457              : #[cfg(test)]
     458              : impl From<harness::TestRedoManager> for WalRedoManager {
     459          220 :     fn from(mgr: harness::TestRedoManager) -> Self {
     460          220 :         Self::Test(mgr)
     461          220 :     }
     462              : }
     463              : 
     464              : impl WalRedoManager {
     465            6 :     pub(crate) async fn shutdown(&self) -> bool {
     466            6 :         match self {
     467            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     468              :             #[cfg(test)]
     469              :             Self::Test(_) => {
     470              :                 // Not applicable to test redo manager
     471            6 :                 true
     472              :             }
     473              :         }
     474            6 :     }
     475              : 
     476            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     477            0 :         match self {
     478            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     479            0 :             #[cfg(test)]
     480            0 :             Self::Test(_) => {
     481            0 :                 // Not applicable to test redo manager
     482            0 :             }
     483            0 :         }
     484            0 :     }
     485              : 
     486              :     /// # Cancel-Safety
     487              :     ///
     488              :     /// This method is cancellation-safe.
     489          818 :     pub async fn request_redo(
     490          818 :         &self,
     491          818 :         key: pageserver_api::key::Key,
     492          818 :         lsn: Lsn,
     493          818 :         base_img: Option<(Lsn, bytes::Bytes)>,
     494          818 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     495          818 :         pg_version: u32,
     496          818 :     ) -> Result<bytes::Bytes, walredo::Error> {
     497          818 :         match self {
     498            0 :             Self::Prod(_, mgr) => {
     499            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     500            0 :                     .await
     501              :             }
     502              :             #[cfg(test)]
     503          818 :             Self::Test(mgr) => {
     504          818 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     505          818 :                     .await
     506              :             }
     507              :         }
     508          818 :     }
     509              : 
     510            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     511            0 :         match self {
     512            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     513            0 :             #[cfg(test)]
     514            0 :             WalRedoManager::Test(_) => None,
     515            0 :         }
     516            0 :     }
     517              : }
     518              : 
     519              : /// A very lightweight memory representation of an offloaded timeline.
     520              : ///
     521              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     522              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     523              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     524              : /// more offloaded timelines than we can manage ones that aren't.
     525              : pub struct OffloadedTimeline {
     526              :     pub tenant_shard_id: TenantShardId,
     527              :     pub timeline_id: TimelineId,
     528              :     pub ancestor_timeline_id: Option<TimelineId>,
     529              :     /// Whether to retain the branch lsn at the ancestor or not
     530              :     pub ancestor_retain_lsn: Option<Lsn>,
     531              : 
     532              :     /// When the timeline was archived.
     533              :     ///
     534              :     /// Present for future flattening deliberations.
     535              :     pub archived_at: NaiveDateTime,
     536              : 
     537              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     538              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     539              :     pub delete_progress: TimelineDeleteProgress,
     540              : 
     541              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     542              :     pub deleted_from_ancestor: AtomicBool,
     543              : }
     544              : 
     545              : impl OffloadedTimeline {
     546              :     /// Obtains an offloaded timeline from a given timeline object.
     547              :     ///
     548              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     549              :     /// the timeline is not in a stopped state.
     550              :     /// Panics if the timeline is not archived.
     551            2 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     552            2 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     553            2 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     554            2 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     555            2 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     556            2 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     557            2 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     558            2 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     559              :             } else {
     560            0 :                 (None, None)
     561              :             };
     562            2 :         let archived_at = timeline
     563            2 :             .remote_client
     564            2 :             .archived_at_stopped_queue()?
     565            2 :             .expect("must be called on an archived timeline");
     566            2 :         Ok(Self {
     567            2 :             tenant_shard_id: timeline.tenant_shard_id,
     568            2 :             timeline_id: timeline.timeline_id,
     569            2 :             ancestor_timeline_id,
     570            2 :             ancestor_retain_lsn,
     571            2 :             archived_at,
     572            2 : 
     573            2 :             delete_progress: timeline.delete_progress.clone(),
     574            2 :             deleted_from_ancestor: AtomicBool::new(false),
     575            2 :         })
     576            2 :     }
     577            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     578            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     579            0 :         // by the `initialize_gc_info` function.
     580            0 :         let OffloadedTimelineManifest {
     581            0 :             timeline_id,
     582            0 :             ancestor_timeline_id,
     583            0 :             ancestor_retain_lsn,
     584            0 :             archived_at,
     585            0 :         } = *manifest;
     586            0 :         Self {
     587            0 :             tenant_shard_id,
     588            0 :             timeline_id,
     589            0 :             ancestor_timeline_id,
     590            0 :             ancestor_retain_lsn,
     591            0 :             archived_at,
     592            0 :             delete_progress: TimelineDeleteProgress::default(),
     593            0 :             deleted_from_ancestor: AtomicBool::new(false),
     594            0 :         }
     595            0 :     }
     596            2 :     fn manifest(&self) -> OffloadedTimelineManifest {
     597            2 :         let Self {
     598            2 :             timeline_id,
     599            2 :             ancestor_timeline_id,
     600            2 :             ancestor_retain_lsn,
     601            2 :             archived_at,
     602            2 :             ..
     603            2 :         } = self;
     604            2 :         OffloadedTimelineManifest {
     605            2 :             timeline_id: *timeline_id,
     606            2 :             ancestor_timeline_id: *ancestor_timeline_id,
     607            2 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     608            2 :             archived_at: *archived_at,
     609            2 :         }
     610            2 :     }
     611              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     612            0 :     fn delete_from_ancestor_with_timelines(
     613            0 :         &self,
     614            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     615            0 :     ) {
     616            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     617            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     618              :         {
     619            0 :             if let Some((_, ancestor_timeline)) = timelines
     620            0 :                 .iter()
     621            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     622              :             {
     623            0 :                 let removal_happened = ancestor_timeline
     624            0 :                     .gc_info
     625            0 :                     .write()
     626            0 :                     .unwrap()
     627            0 :                     .remove_child_offloaded(self.timeline_id);
     628            0 :                 if !removal_happened {
     629            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     630            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     631            0 :                 }
     632            0 :             }
     633            0 :         }
     634            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     635            0 :     }
     636              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     637              :     ///
     638              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     639            2 :     fn defuse_for_tenant_drop(&self) {
     640            2 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     641            2 :     }
     642              : }
     643              : 
     644              : impl fmt::Debug for OffloadedTimeline {
     645            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     646            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     647            0 :     }
     648              : }
     649              : 
     650              : impl Drop for OffloadedTimeline {
     651            2 :     fn drop(&mut self) {
     652            2 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     653            0 :             tracing::warn!(
     654            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     655              :                 self.timeline_id
     656              :             );
     657            2 :         }
     658            2 :     }
     659              : }
     660              : 
     661              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     662              : pub enum MaybeOffloaded {
     663              :     Yes,
     664              :     No,
     665              : }
     666              : 
     667              : #[derive(Clone, Debug)]
     668              : pub enum TimelineOrOffloaded {
     669              :     Timeline(Arc<Timeline>),
     670              :     Offloaded(Arc<OffloadedTimeline>),
     671              : }
     672              : 
     673              : impl TimelineOrOffloaded {
     674            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     675            0 :         match self {
     676            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     677            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     678              :             }
     679            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     680            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     681              :             }
     682              :         }
     683            0 :     }
     684            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     685            0 :         self.arc_ref().tenant_shard_id()
     686            0 :     }
     687            0 :     pub fn timeline_id(&self) -> TimelineId {
     688            0 :         self.arc_ref().timeline_id()
     689            0 :     }
     690            2 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     691            2 :         match self {
     692            2 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     693            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     694              :         }
     695            2 :     }
     696            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     697            0 :         match self {
     698            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     699            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     700              :         }
     701            0 :     }
     702              : }
     703              : 
     704              : pub enum TimelineOrOffloadedArcRef<'a> {
     705              :     Timeline(&'a Arc<Timeline>),
     706              :     Offloaded(&'a Arc<OffloadedTimeline>),
     707              : }
     708              : 
     709              : impl TimelineOrOffloadedArcRef<'_> {
     710            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     711            0 :         match self {
     712            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     713            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     714              :         }
     715            0 :     }
     716            0 :     pub fn timeline_id(&self) -> TimelineId {
     717            0 :         match self {
     718            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     719            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     720              :         }
     721            0 :     }
     722              : }
     723              : 
     724              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     725            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     726            0 :         Self::Timeline(timeline)
     727            0 :     }
     728              : }
     729              : 
     730              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     731            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     732            0 :         Self::Offloaded(timeline)
     733            0 :     }
     734              : }
     735              : 
     736              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     737              : pub enum GetTimelineError {
     738              :     #[error("Timeline is shutting down")]
     739              :     ShuttingDown,
     740              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     741              :     NotActive {
     742              :         tenant_id: TenantShardId,
     743              :         timeline_id: TimelineId,
     744              :         state: TimelineState,
     745              :     },
     746              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     747              :     NotFound {
     748              :         tenant_id: TenantShardId,
     749              :         timeline_id: TimelineId,
     750              :     },
     751              : }
     752              : 
     753              : #[derive(Debug, thiserror::Error)]
     754              : pub enum LoadLocalTimelineError {
     755              :     #[error("FailedToLoad")]
     756              :     Load(#[source] anyhow::Error),
     757              :     #[error("FailedToResumeDeletion")]
     758              :     ResumeDeletion(#[source] anyhow::Error),
     759              : }
     760              : 
     761              : #[derive(thiserror::Error)]
     762              : pub enum DeleteTimelineError {
     763              :     #[error("NotFound")]
     764              :     NotFound,
     765              : 
     766              :     #[error("HasChildren")]
     767              :     HasChildren(Vec<TimelineId>),
     768              : 
     769              :     #[error("Timeline deletion is already in progress")]
     770              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     771              : 
     772              :     #[error("Cancelled")]
     773              :     Cancelled,
     774              : 
     775              :     #[error(transparent)]
     776              :     Other(#[from] anyhow::Error),
     777              : }
     778              : 
     779              : impl Debug for DeleteTimelineError {
     780            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     781            0 :         match self {
     782            0 :             Self::NotFound => write!(f, "NotFound"),
     783            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     784            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     785            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     786            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     787              :         }
     788            0 :     }
     789              : }
     790              : 
     791              : #[derive(thiserror::Error)]
     792              : pub enum TimelineArchivalError {
     793              :     #[error("NotFound")]
     794              :     NotFound,
     795              : 
     796              :     #[error("Timeout")]
     797              :     Timeout,
     798              : 
     799              :     #[error("Cancelled")]
     800              :     Cancelled,
     801              : 
     802              :     #[error("ancestor is archived: {}", .0)]
     803              :     HasArchivedParent(TimelineId),
     804              : 
     805              :     #[error("HasUnarchivedChildren")]
     806              :     HasUnarchivedChildren(Vec<TimelineId>),
     807              : 
     808              :     #[error("Timeline archival is already in progress")]
     809              :     AlreadyInProgress,
     810              : 
     811              :     #[error(transparent)]
     812              :     Other(anyhow::Error),
     813              : }
     814              : 
     815              : #[derive(thiserror::Error, Debug)]
     816              : pub(crate) enum TenantManifestError {
     817              :     #[error("Remote storage error: {0}")]
     818              :     RemoteStorage(anyhow::Error),
     819              : 
     820              :     #[error("Cancelled")]
     821              :     Cancelled,
     822              : }
     823              : 
     824              : impl From<TenantManifestError> for TimelineArchivalError {
     825            0 :     fn from(e: TenantManifestError) -> Self {
     826            0 :         match e {
     827            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     828            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     829              :         }
     830            0 :     }
     831              : }
     832              : 
     833              : impl Debug for TimelineArchivalError {
     834            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     835            0 :         match self {
     836            0 :             Self::NotFound => write!(f, "NotFound"),
     837            0 :             Self::Timeout => write!(f, "Timeout"),
     838            0 :             Self::Cancelled => write!(f, "Cancelled"),
     839            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     840            0 :             Self::HasUnarchivedChildren(c) => {
     841            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     842              :             }
     843            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     844            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     845              :         }
     846            0 :     }
     847              : }
     848              : 
     849              : pub enum SetStoppingError {
     850              :     AlreadyStopping(completion::Barrier),
     851              :     Broken,
     852              : }
     853              : 
     854              : impl Debug for SetStoppingError {
     855            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     856            0 :         match self {
     857            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     858            0 :             Self::Broken => write!(f, "Broken"),
     859              :         }
     860            0 :     }
     861              : }
     862              : 
     863              : /// Arguments to [`Tenant::create_timeline`].
     864              : ///
     865              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     866              : /// is `None`, the result of the timeline create call is not deterministic.
     867              : ///
     868              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     869              : #[derive(Debug)]
     870              : pub(crate) enum CreateTimelineParams {
     871              :     Bootstrap(CreateTimelineParamsBootstrap),
     872              :     Branch(CreateTimelineParamsBranch),
     873              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     874              : }
     875              : 
     876              : #[derive(Debug)]
     877              : pub(crate) struct CreateTimelineParamsBootstrap {
     878              :     pub(crate) new_timeline_id: TimelineId,
     879              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     880              :     pub(crate) pg_version: u32,
     881              : }
     882              : 
     883              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     884              : #[derive(Debug)]
     885              : pub(crate) struct CreateTimelineParamsBranch {
     886              :     pub(crate) new_timeline_id: TimelineId,
     887              :     pub(crate) ancestor_timeline_id: TimelineId,
     888              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     889              : }
     890              : 
     891              : #[derive(Debug)]
     892              : pub(crate) struct CreateTimelineParamsImportPgdata {
     893              :     pub(crate) new_timeline_id: TimelineId,
     894              :     pub(crate) location: import_pgdata::index_part_format::Location,
     895              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     896              : }
     897              : 
     898              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     899              : ///
     900              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     901              : ///
     902              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     903              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     904              : ///
     905              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     906              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     907              : ///
     908              : /// Notes:
     909              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     910              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     911              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     912              : ///
     913              : #[derive(Debug, Clone, PartialEq, Eq)]
     914              : pub(crate) enum CreateTimelineIdempotency {
     915              :     /// NB: special treatment, see comment in [`Self`].
     916              :     FailWithConflict,
     917              :     Bootstrap {
     918              :         pg_version: u32,
     919              :     },
     920              :     /// NB: branches always have the same `pg_version` as their ancestor.
     921              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     922              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     923              :     /// determining the child branch pg_version.
     924              :     Branch {
     925              :         ancestor_timeline_id: TimelineId,
     926              :         ancestor_start_lsn: Lsn,
     927              :     },
     928              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     929              : }
     930              : 
     931              : #[derive(Debug, Clone, PartialEq, Eq)]
     932              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     933              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     934              : }
     935              : 
     936              : /// What is returned by [`Tenant::start_creating_timeline`].
     937              : #[must_use]
     938              : enum StartCreatingTimelineResult {
     939              :     CreateGuard(TimelineCreateGuard),
     940              :     Idempotent(Arc<Timeline>),
     941              : }
     942              : 
     943              : enum TimelineInitAndSyncResult {
     944              :     ReadyToActivate(Arc<Timeline>),
     945              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     946              : }
     947              : 
     948              : impl TimelineInitAndSyncResult {
     949            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     950            0 :         match self {
     951            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     952            0 :             _ => None,
     953              :         }
     954            0 :     }
     955              : }
     956              : 
     957              : #[must_use]
     958              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     959              :     timeline: Arc<Timeline>,
     960              :     import_pgdata: import_pgdata::index_part_format::Root,
     961              :     guard: TimelineCreateGuard,
     962              : }
     963              : 
     964              : /// What is returned by [`Tenant::create_timeline`].
     965              : enum CreateTimelineResult {
     966              :     Created(Arc<Timeline>),
     967              :     Idempotent(Arc<Timeline>),
     968              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     969              :     /// we return this result, nor will this concrete object ever be added there.
     970              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     971              :     ImportSpawned(Arc<Timeline>),
     972              : }
     973              : 
     974              : impl CreateTimelineResult {
     975            0 :     fn discriminant(&self) -> &'static str {
     976            0 :         match self {
     977            0 :             Self::Created(_) => "Created",
     978            0 :             Self::Idempotent(_) => "Idempotent",
     979            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     980              :         }
     981            0 :     }
     982            0 :     fn timeline(&self) -> &Arc<Timeline> {
     983            0 :         match self {
     984            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     985            0 :         }
     986            0 :     }
     987              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     988              :     #[cfg(test)]
     989          230 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     990          230 :         match self {
     991          230 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     992          230 :         }
     993          230 :     }
     994              : }
     995              : 
     996              : #[derive(thiserror::Error, Debug)]
     997              : pub enum CreateTimelineError {
     998              :     #[error("creation of timeline with the given ID is in progress")]
     999              :     AlreadyCreating,
    1000              :     #[error("timeline already exists with different parameters")]
    1001              :     Conflict,
    1002              :     #[error(transparent)]
    1003              :     AncestorLsn(anyhow::Error),
    1004              :     #[error("ancestor timeline is not active")]
    1005              :     AncestorNotActive,
    1006              :     #[error("ancestor timeline is archived")]
    1007              :     AncestorArchived,
    1008              :     #[error("tenant shutting down")]
    1009              :     ShuttingDown,
    1010              :     #[error(transparent)]
    1011              :     Other(#[from] anyhow::Error),
    1012              : }
    1013              : 
    1014              : #[derive(thiserror::Error, Debug)]
    1015              : pub enum InitdbError {
    1016              :     #[error("Operation was cancelled")]
    1017              :     Cancelled,
    1018              :     #[error(transparent)]
    1019              :     Other(anyhow::Error),
    1020              :     #[error(transparent)]
    1021              :     Inner(postgres_initdb::Error),
    1022              : }
    1023              : 
    1024              : enum CreateTimelineCause {
    1025              :     Load,
    1026              :     Delete,
    1027              : }
    1028              : 
    1029              : enum LoadTimelineCause {
    1030              :     Attach,
    1031              :     Unoffload,
    1032              :     ImportPgdata {
    1033              :         create_guard: TimelineCreateGuard,
    1034              :         activate: ActivateTimelineArgs,
    1035              :     },
    1036              : }
    1037              : 
    1038              : #[derive(thiserror::Error, Debug)]
    1039              : pub(crate) enum GcError {
    1040              :     // The tenant is shutting down
    1041              :     #[error("tenant shutting down")]
    1042              :     TenantCancelled,
    1043              : 
    1044              :     // The tenant is shutting down
    1045              :     #[error("timeline shutting down")]
    1046              :     TimelineCancelled,
    1047              : 
    1048              :     // The tenant is in a state inelegible to run GC
    1049              :     #[error("not active")]
    1050              :     NotActive,
    1051              : 
    1052              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1053              :     #[error("not active")]
    1054              :     BadLsn { why: String },
    1055              : 
    1056              :     // A remote storage error while scheduling updates after compaction
    1057              :     #[error(transparent)]
    1058              :     Remote(anyhow::Error),
    1059              : 
    1060              :     // An error reading while calculating GC cutoffs
    1061              :     #[error(transparent)]
    1062              :     GcCutoffs(PageReconstructError),
    1063              : 
    1064              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1065              :     #[error("timeline not found")]
    1066              :     TimelineNotFound,
    1067              : }
    1068              : 
    1069              : impl From<PageReconstructError> for GcError {
    1070            0 :     fn from(value: PageReconstructError) -> Self {
    1071            0 :         match value {
    1072            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1073            0 :             other => Self::GcCutoffs(other),
    1074              :         }
    1075            0 :     }
    1076              : }
    1077              : 
    1078              : impl From<NotInitialized> for GcError {
    1079            0 :     fn from(value: NotInitialized) -> Self {
    1080            0 :         match value {
    1081            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1082            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1083              :         }
    1084            0 :     }
    1085              : }
    1086              : 
    1087              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1088            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1089            0 :         GcError::TimelineCancelled
    1090            0 :     }
    1091              : }
    1092              : 
    1093              : #[derive(thiserror::Error, Debug)]
    1094              : pub(crate) enum LoadConfigError {
    1095              :     #[error("TOML deserialization error: '{0}'")]
    1096              :     DeserializeToml(#[from] toml_edit::de::Error),
    1097              : 
    1098              :     #[error("Config not found at {0}")]
    1099              :     NotFound(Utf8PathBuf),
    1100              : }
    1101              : 
    1102              : impl Tenant {
    1103              :     /// Yet another helper for timeline initialization.
    1104              :     ///
    1105              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1106              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1107              :     /// - Downloads remote index file and adds remote files to the layer map
    1108              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1109              :     ///
    1110              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1111              :     /// it is marked as Active.
    1112              :     #[allow(clippy::too_many_arguments)]
    1113            6 :     async fn timeline_init_and_sync(
    1114            6 :         self: &Arc<Self>,
    1115            6 :         timeline_id: TimelineId,
    1116            6 :         resources: TimelineResources,
    1117            6 :         mut index_part: IndexPart,
    1118            6 :         metadata: TimelineMetadata,
    1119            6 :         ancestor: Option<Arc<Timeline>>,
    1120            6 :         cause: LoadTimelineCause,
    1121            6 :         ctx: &RequestContext,
    1122            6 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1123            6 :         let tenant_id = self.tenant_shard_id;
    1124            6 : 
    1125            6 :         let import_pgdata = index_part.import_pgdata.take();
    1126            6 :         let idempotency = match &import_pgdata {
    1127            0 :             Some(import_pgdata) => {
    1128            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1129            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1130            0 :                 })
    1131              :             }
    1132              :             None => {
    1133            6 :                 if metadata.ancestor_timeline().is_none() {
    1134            4 :                     CreateTimelineIdempotency::Bootstrap {
    1135            4 :                         pg_version: metadata.pg_version(),
    1136            4 :                     }
    1137              :                 } else {
    1138            2 :                     CreateTimelineIdempotency::Branch {
    1139            2 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1140            2 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1141            2 :                     }
    1142              :                 }
    1143              :             }
    1144              :         };
    1145              : 
    1146            6 :         let timeline = self.create_timeline_struct(
    1147            6 :             timeline_id,
    1148            6 :             &metadata,
    1149            6 :             ancestor.clone(),
    1150            6 :             resources,
    1151            6 :             CreateTimelineCause::Load,
    1152            6 :             idempotency.clone(),
    1153            6 :         )?;
    1154            6 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1155            6 :         anyhow::ensure!(
    1156            6 :             disk_consistent_lsn.is_valid(),
    1157            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1158              :         );
    1159            6 :         assert_eq!(
    1160            6 :             disk_consistent_lsn,
    1161            6 :             metadata.disk_consistent_lsn(),
    1162            0 :             "these are used interchangeably"
    1163              :         );
    1164              : 
    1165            6 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1166              : 
    1167            6 :         timeline
    1168            6 :             .load_layer_map(disk_consistent_lsn, index_part)
    1169            6 :             .await
    1170            6 :             .with_context(|| {
    1171            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1172            6 :             })?;
    1173              : 
    1174            0 :         match import_pgdata {
    1175            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1176            0 :                 match cause {
    1177            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1178              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1179            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1180              :                     }
    1181              :                 }
    1182            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1183            0 :                 if !guard.insert(timeline_id) {
    1184              :                     // We should never try and load the same timeline twice during startup
    1185            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1186            0 :                 }
    1187            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1188            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1189            0 :                     owning_tenant: self.clone(),
    1190            0 :                     timeline_id,
    1191            0 :                     idempotency,
    1192            0 :                     // The users of this specific return value don't need the timline_path in there.
    1193            0 :                     timeline_path: timeline
    1194            0 :                         .conf
    1195            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1196            0 :                 };
    1197            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1198            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1199            0 :                         timeline,
    1200            0 :                         import_pgdata,
    1201            0 :                         guard: timeline_create_guard,
    1202            0 :                     },
    1203            0 :                 ))
    1204              :             }
    1205              :             Some(_) | None => {
    1206              :                 {
    1207            6 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1208            6 :                     match timelines_accessor.entry(timeline_id) {
    1209              :                         // We should never try and load the same timeline twice during startup
    1210              :                         Entry::Occupied(_) => {
    1211            0 :                             unreachable!(
    1212            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1213            0 :                         );
    1214              :                         }
    1215            6 :                         Entry::Vacant(v) => {
    1216            6 :                             v.insert(Arc::clone(&timeline));
    1217            6 :                             timeline.maybe_spawn_flush_loop();
    1218            6 :                         }
    1219              :                     }
    1220              :                 }
    1221              : 
    1222              :                 // Sanity check: a timeline should have some content.
    1223            6 :                 anyhow::ensure!(
    1224            6 :                     ancestor.is_some()
    1225            4 :                         || timeline
    1226            4 :                             .layers
    1227            4 :                             .read()
    1228            4 :                             .await
    1229            4 :                             .layer_map()
    1230            4 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1231            4 :                             .iter_historic_layers()
    1232            4 :                             .next()
    1233            4 :                             .is_some(),
    1234            0 :                     "Timeline has no ancestor and no layer files"
    1235              :                 );
    1236              : 
    1237            6 :                 match cause {
    1238            6 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1239              :                     LoadTimelineCause::ImportPgdata {
    1240            0 :                         create_guard,
    1241            0 :                         activate,
    1242            0 :                     } => {
    1243            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1244            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1245            0 :                         match activate {
    1246            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1247            0 :                                 info!("activating timeline after reload from pgdata import task");
    1248            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1249              :                             }
    1250            0 :                             ActivateTimelineArgs::No => (),
    1251              :                         }
    1252            0 :                         drop(create_guard);
    1253              :                     }
    1254              :                 }
    1255              : 
    1256            6 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1257              :             }
    1258              :         }
    1259            6 :     }
    1260              : 
    1261              :     /// Attach a tenant that's available in cloud storage.
    1262              :     ///
    1263              :     /// This returns quickly, after just creating the in-memory object
    1264              :     /// Tenant struct and launching a background task to download
    1265              :     /// the remote index files.  On return, the tenant is most likely still in
    1266              :     /// Attaching state, and it will become Active once the background task
    1267              :     /// finishes. You can use wait_until_active() to wait for the task to
    1268              :     /// complete.
    1269              :     ///
    1270              :     #[allow(clippy::too_many_arguments)]
    1271            0 :     pub(crate) fn spawn(
    1272            0 :         conf: &'static PageServerConf,
    1273            0 :         tenant_shard_id: TenantShardId,
    1274            0 :         resources: TenantSharedResources,
    1275            0 :         attached_conf: AttachedTenantConf,
    1276            0 :         shard_identity: ShardIdentity,
    1277            0 :         init_order: Option<InitializationOrder>,
    1278            0 :         mode: SpawnMode,
    1279            0 :         ctx: &RequestContext,
    1280            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1281            0 :         let wal_redo_manager =
    1282            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1283              : 
    1284              :         let TenantSharedResources {
    1285            0 :             broker_client,
    1286            0 :             remote_storage,
    1287            0 :             deletion_queue_client,
    1288            0 :             l0_flush_global_state,
    1289            0 :         } = resources;
    1290            0 : 
    1291            0 :         let attach_mode = attached_conf.location.attach_mode;
    1292            0 :         let generation = attached_conf.location.generation;
    1293            0 : 
    1294            0 :         let tenant = Arc::new(Tenant::new(
    1295            0 :             TenantState::Attaching,
    1296            0 :             conf,
    1297            0 :             attached_conf,
    1298            0 :             shard_identity,
    1299            0 :             Some(wal_redo_manager),
    1300            0 :             tenant_shard_id,
    1301            0 :             remote_storage.clone(),
    1302            0 :             deletion_queue_client,
    1303            0 :             l0_flush_global_state,
    1304            0 :         ));
    1305            0 : 
    1306            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1307            0 :         // we shut down while attaching.
    1308            0 :         let attach_gate_guard = tenant
    1309            0 :             .gate
    1310            0 :             .enter()
    1311            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1312            0 : 
    1313            0 :         // Do all the hard work in the background
    1314            0 :         let tenant_clone = Arc::clone(&tenant);
    1315            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1316            0 :         task_mgr::spawn(
    1317            0 :             &tokio::runtime::Handle::current(),
    1318            0 :             TaskKind::Attach,
    1319            0 :             tenant_shard_id,
    1320            0 :             None,
    1321            0 :             "attach tenant",
    1322            0 :             async move {
    1323            0 : 
    1324            0 :                 info!(
    1325              :                     ?attach_mode,
    1326            0 :                     "Attaching tenant"
    1327              :                 );
    1328              : 
    1329            0 :                 let _gate_guard = attach_gate_guard;
    1330            0 : 
    1331            0 :                 // Is this tenant being spawned as part of process startup?
    1332            0 :                 let starting_up = init_order.is_some();
    1333            0 :                 scopeguard::defer! {
    1334            0 :                     if starting_up {
    1335            0 :                         TENANT.startup_complete.inc();
    1336            0 :                     }
    1337            0 :                 }
    1338              : 
    1339              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1340              :                 enum BrokenVerbosity {
    1341              :                     Error,
    1342              :                     Info
    1343              :                 }
    1344            0 :                 let make_broken =
    1345            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1346            0 :                         match verbosity {
    1347              :                             BrokenVerbosity::Info => {
    1348            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1349              :                             },
    1350              :                             BrokenVerbosity::Error => {
    1351            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1352              :                             }
    1353              :                         }
    1354            0 :                         t.state.send_modify(|state| {
    1355            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1356            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1357            0 :                             assert!(
    1358            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1359            0 :                                 "the attach task owns the tenant state until activation is complete"
    1360              :                             );
    1361              : 
    1362            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1363            0 :                         });
    1364            0 :                     };
    1365              : 
    1366              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1367            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1368            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1369            0 :                     return Ok(());
    1370            0 :                 }
    1371            0 : 
    1372            0 :                 let mut init_order = init_order;
    1373            0 :                 // take the completion because initial tenant loading will complete when all of
    1374            0 :                 // these tasks complete.
    1375            0 :                 let _completion = init_order
    1376            0 :                     .as_mut()
    1377            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1378            0 :                 let remote_load_completion = init_order
    1379            0 :                     .as_mut()
    1380            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1381              : 
    1382              :                 enum AttachType<'a> {
    1383              :                     /// We are attaching this tenant lazily in the background.
    1384              :                     Warmup {
    1385              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1386              :                         during_startup: bool
    1387              :                     },
    1388              :                     /// We are attaching this tenant as soon as we can, because for example an
    1389              :                     /// endpoint tried to access it.
    1390              :                     OnDemand,
    1391              :                     /// During normal operations after startup, we are attaching a tenant, and
    1392              :                     /// eager attach was requested.
    1393              :                     Normal,
    1394              :                 }
    1395              : 
    1396            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1397              :                     // Before doing any I/O, wait for at least one of:
    1398              :                     // - A client attempting to access to this tenant (on-demand loading)
    1399              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1400              : 
    1401            0 :                     tokio::select!(
    1402            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1403            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1404            0 :                             tracing::info!("Activating tenant (on-demand)");
    1405            0 :                             AttachType::OnDemand
    1406              :                         },
    1407            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1408            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1409            0 :                             tracing::info!("Activating tenant (warmup)");
    1410            0 :                             AttachType::Warmup {
    1411            0 :                                 _permit,
    1412            0 :                                 during_startup: init_order.is_some()
    1413            0 :                             }
    1414              :                         }
    1415            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1416              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1417              :                             // stayed in Activating for such a long time that shutdown found it in
    1418              :                             // that state.
    1419            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1420              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1421              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1422              :                             // just shutting down), but ensures progress.
    1423            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1424            0 :                             return Ok(());
    1425              :                         },
    1426              :                     )
    1427              :                 } else {
    1428              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1429              :                     // concurrent_tenant_warmup queue
    1430            0 :                     AttachType::Normal
    1431              :                 };
    1432              : 
    1433            0 :                 let preload = match &mode {
    1434              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1435            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1436            0 :                         let res = tenant_clone
    1437            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1438            0 :                             .await;
    1439            0 :                         match res {
    1440            0 :                             Ok(p) => Some(p),
    1441            0 :                             Err(e) => {
    1442            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1443            0 :                                 return Ok(());
    1444              :                             }
    1445              :                         }
    1446              :                     }
    1447              : 
    1448              :                 };
    1449              : 
    1450              :                 // Remote preload is complete.
    1451            0 :                 drop(remote_load_completion);
    1452            0 : 
    1453            0 : 
    1454            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1455            0 :                 let attach_start = std::time::Instant::now();
    1456            0 :                 let attached = {
    1457            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1458            0 :                     tenant_clone.attach(preload, &ctx).await
    1459              :                 };
    1460            0 :                 let attach_duration = attach_start.elapsed();
    1461            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1462            0 : 
    1463            0 :                 match attached {
    1464              :                     Ok(()) => {
    1465            0 :                         info!("attach finished, activating");
    1466            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1467              :                     }
    1468            0 :                     Err(e) => {
    1469            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1470            0 :                     }
    1471              :                 }
    1472              : 
    1473              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1474              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1475              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1476              :                 //
    1477              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1478              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1479              :                 // then warmup will wait for that before proceeding to the next tenant.
    1480            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1481            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1482            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1483            0 :                     while futs.next().await.is_some() {}
    1484            0 :                     tracing::info!("Warm-up complete");
    1485            0 :                 }
    1486              : 
    1487            0 :                 Ok(())
    1488            0 :             }
    1489            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1490              :         );
    1491            0 :         Ok(tenant)
    1492            0 :     }
    1493              : 
    1494              :     #[instrument(skip_all)]
    1495              :     pub(crate) async fn preload(
    1496              :         self: &Arc<Self>,
    1497              :         remote_storage: &GenericRemoteStorage,
    1498              :         cancel: CancellationToken,
    1499              :     ) -> anyhow::Result<TenantPreload> {
    1500              :         span::debug_assert_current_span_has_tenant_id();
    1501              :         // Get list of remote timelines
    1502              :         // download index files for every tenant timeline
    1503              :         info!("listing remote timelines");
    1504              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1505              :             remote_storage,
    1506              :             self.tenant_shard_id,
    1507              :             cancel.clone(),
    1508              :         )
    1509              :         .await?;
    1510              :         let (offloaded_add, tenant_manifest) =
    1511              :             match remote_timeline_client::download_tenant_manifest(
    1512              :                 remote_storage,
    1513              :                 &self.tenant_shard_id,
    1514              :                 self.generation,
    1515              :                 &cancel,
    1516              :             )
    1517              :             .await
    1518              :             {
    1519              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1520              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1521              :                     tenant_manifest,
    1522              :                 ),
    1523              :                 Err(DownloadError::NotFound) => {
    1524              :                     ("no manifest".to_string(), TenantManifest::empty())
    1525              :                 }
    1526              :                 Err(e) => Err(e)?,
    1527              :             };
    1528              : 
    1529              :         info!(
    1530              :             "found {} timelines, and {offloaded_add}",
    1531              :             remote_timeline_ids.len()
    1532              :         );
    1533              : 
    1534              :         for k in other_keys {
    1535              :             warn!("Unexpected non timeline key {k}");
    1536              :         }
    1537              : 
    1538              :         // Avoid downloading IndexPart of offloaded timelines.
    1539              :         let mut offloaded_with_prefix = HashSet::new();
    1540              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1541              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1542              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1543              :             } else {
    1544              :                 // We'll take care later of timelines in the manifest without a prefix
    1545              :             }
    1546              :         }
    1547              : 
    1548              :         let timelines = self
    1549              :             .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1550              :             .await?;
    1551              : 
    1552              :         Ok(TenantPreload {
    1553              :             tenant_manifest,
    1554              :             timelines: timelines
    1555              :                 .into_iter()
    1556            6 :                 .map(|(id, tl)| (id, Some(tl)))
    1557            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1558              :                 .collect(),
    1559              :         })
    1560              :     }
    1561              : 
    1562              :     ///
    1563              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1564              :     ///
    1565              :     /// No background tasks are started as part of this routine.
    1566              :     ///
    1567          220 :     async fn attach(
    1568          220 :         self: &Arc<Tenant>,
    1569          220 :         preload: Option<TenantPreload>,
    1570          220 :         ctx: &RequestContext,
    1571          220 :     ) -> anyhow::Result<()> {
    1572          220 :         span::debug_assert_current_span_has_tenant_id();
    1573          220 : 
    1574          220 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1575              : 
    1576          220 :         let Some(preload) = preload else {
    1577            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1578              :         };
    1579              : 
    1580          220 :         let mut offloaded_timeline_ids = HashSet::new();
    1581          220 :         let mut offloaded_timelines_list = Vec::new();
    1582          220 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1583            0 :             let timeline_id = timeline_manifest.timeline_id;
    1584            0 :             let offloaded_timeline =
    1585            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1586            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1587            0 :             offloaded_timeline_ids.insert(timeline_id);
    1588            0 :         }
    1589              :         // Complete deletions for offloaded timeline id's from manifest.
    1590              :         // The manifest will be uploaded later in this function.
    1591          220 :         offloaded_timelines_list
    1592          220 :             .retain(|(offloaded_id, offloaded)| {
    1593            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1594            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1595            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1596            0 :                 if delete {
    1597            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1598            0 :                     offloaded.defuse_for_tenant_drop();
    1599            0 :                 }
    1600            0 :                 !delete
    1601          220 :         });
    1602          220 : 
    1603          220 :         let mut timelines_to_resume_deletions = vec![];
    1604          220 : 
    1605          220 :         let mut remote_index_and_client = HashMap::new();
    1606          220 :         let mut timeline_ancestors = HashMap::new();
    1607          220 :         let mut existent_timelines = HashSet::new();
    1608          226 :         for (timeline_id, preload) in preload.timelines {
    1609            6 :             let Some(preload) = preload else { continue };
    1610              :             // This is an invariant of the `preload` function's API
    1611            6 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1612            6 :             let index_part = match preload.index_part {
    1613            6 :                 Ok(i) => {
    1614            6 :                     debug!("remote index part exists for timeline {timeline_id}");
    1615              :                     // We found index_part on the remote, this is the standard case.
    1616            6 :                     existent_timelines.insert(timeline_id);
    1617            6 :                     i
    1618              :                 }
    1619              :                 Err(DownloadError::NotFound) => {
    1620              :                     // There is no index_part on the remote. We only get here
    1621              :                     // if there is some prefix for the timeline in the remote storage.
    1622              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1623              :                     // remnant from a prior incomplete creation or deletion attempt.
    1624              :                     // Delete the local directory as the deciding criterion for a
    1625              :                     // timeline's existence is presence of index_part.
    1626            0 :                     info!(%timeline_id, "index_part not found on remote");
    1627            0 :                     continue;
    1628              :                 }
    1629            0 :                 Err(DownloadError::Fatal(why)) => {
    1630            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1631            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1632            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1633            0 :                     anyhow::bail!(why.to_string());
    1634              :                 }
    1635            0 :                 Err(e) => {
    1636            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1637            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1638            0 :                     // as it might be a temporary issue and we don't want to re-download
    1639            0 :                     // everything after it resolves.
    1640            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1641              : 
    1642            0 :                     existent_timelines.insert(timeline_id);
    1643            0 :                     continue;
    1644              :                 }
    1645              :             };
    1646            6 :             match index_part {
    1647            6 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1648            6 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1649            6 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1650            6 :                 }
    1651            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1652            0 :                     info!(
    1653            0 :                         "timeline {} is deleted, picking to resume deletion",
    1654              :                         timeline_id
    1655              :                     );
    1656            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1657              :                 }
    1658              :             }
    1659              :         }
    1660              : 
    1661          220 :         let mut gc_blocks = HashMap::new();
    1662              : 
    1663              :         // For every timeline, download the metadata file, scan the local directory,
    1664              :         // and build a layer map that contains an entry for each remote and local
    1665              :         // layer file.
    1666          220 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1667          226 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1668            6 :             let (index_part, remote_client) = remote_index_and_client
    1669            6 :                 .remove(&timeline_id)
    1670            6 :                 .expect("just put it in above");
    1671              : 
    1672            6 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1673              :                 // could just filter these away, but it helps while testing
    1674            0 :                 anyhow::ensure!(
    1675            0 :                     !blocking.reasons.is_empty(),
    1676            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1677              :                 );
    1678            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1679            0 :                 assert!(prev.is_none());
    1680            6 :             }
    1681              : 
    1682              :             // TODO again handle early failure
    1683            6 :             let effect = self
    1684            6 :                 .load_remote_timeline(
    1685            6 :                     timeline_id,
    1686            6 :                     index_part,
    1687            6 :                     remote_metadata,
    1688            6 :                     TimelineResources {
    1689            6 :                         remote_client,
    1690            6 :                         pagestream_throttle: self.pagestream_throttle.clone(),
    1691            6 :                         pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    1692            6 :                         l0_flush_global_state: self.l0_flush_global_state.clone(),
    1693            6 :                     },
    1694            6 :                     LoadTimelineCause::Attach,
    1695            6 :                     ctx,
    1696            6 :                 )
    1697            6 :                 .await
    1698            6 :                 .with_context(|| {
    1699            0 :                     format!(
    1700            0 :                         "failed to load remote timeline {} for tenant {}",
    1701            0 :                         timeline_id, self.tenant_shard_id
    1702            0 :                     )
    1703            6 :                 })?;
    1704              : 
    1705            6 :             match effect {
    1706            6 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1707            6 :                     // activation happens later, on Tenant::activate
    1708            6 :                 }
    1709              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1710              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1711            0 :                         timeline,
    1712            0 :                         import_pgdata,
    1713            0 :                         guard,
    1714            0 :                     },
    1715            0 :                 ) => {
    1716            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1717            0 :                         timeline,
    1718            0 :                         import_pgdata,
    1719            0 :                         ActivateTimelineArgs::No,
    1720            0 :                         guard,
    1721            0 :                     ));
    1722            0 :                 }
    1723              :             }
    1724              :         }
    1725              : 
    1726              :         // Walk through deleted timelines, resume deletion
    1727          220 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1728            0 :             remote_timeline_client
    1729            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1730            0 :                 .context("init queue stopped")
    1731            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1732              : 
    1733            0 :             DeleteTimelineFlow::resume_deletion(
    1734            0 :                 Arc::clone(self),
    1735            0 :                 timeline_id,
    1736            0 :                 &index_part.metadata,
    1737            0 :                 remote_timeline_client,
    1738            0 :             )
    1739            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1740            0 :             .await
    1741            0 :             .context("resume_deletion")
    1742            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1743              :         }
    1744          220 :         let needs_manifest_upload =
    1745          220 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1746          220 :         {
    1747          220 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1748          220 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1749          220 :         }
    1750          220 :         if needs_manifest_upload {
    1751            0 :             self.store_tenant_manifest().await?;
    1752          220 :         }
    1753              : 
    1754              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1755              :         // IndexPart is the source of truth.
    1756          220 :         self.clean_up_timelines(&existent_timelines)?;
    1757              : 
    1758          220 :         self.gc_block.set_scanned(gc_blocks);
    1759          220 : 
    1760          220 :         fail::fail_point!("attach-before-activate", |_| {
    1761            0 :             anyhow::bail!("attach-before-activate");
    1762          220 :         });
    1763          220 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1764              : 
    1765          220 :         info!("Done");
    1766              : 
    1767          220 :         Ok(())
    1768          220 :     }
    1769              : 
    1770              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1771              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1772              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1773          220 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1774          220 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1775              : 
    1776          220 :         let entries = match timelines_dir.read_dir_utf8() {
    1777          220 :             Ok(d) => d,
    1778            0 :             Err(e) => {
    1779            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1780            0 :                     return Ok(());
    1781              :                 } else {
    1782            0 :                     return Err(e).context("list timelines directory for tenant");
    1783              :                 }
    1784              :             }
    1785              :         };
    1786              : 
    1787          228 :         for entry in entries {
    1788            8 :             let entry = entry.context("read timeline dir entry")?;
    1789            8 :             let entry_path = entry.path();
    1790              : 
    1791            8 :             let purge = if crate::is_temporary(entry_path)
    1792              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1793            8 :                 || is_uninit_mark(entry_path)
    1794            8 :                 || crate::is_delete_mark(entry_path)
    1795              :             {
    1796            0 :                 true
    1797              :             } else {
    1798            8 :                 match TimelineId::try_from(entry_path.file_name()) {
    1799            8 :                     Ok(i) => {
    1800            8 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1801            8 :                         !existent_timelines.contains(&i)
    1802              :                     }
    1803            0 :                     Err(e) => {
    1804            0 :                         tracing::warn!(
    1805            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1806              :                         );
    1807              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1808            0 :                         false
    1809              :                     }
    1810              :                 }
    1811              :             };
    1812              : 
    1813            8 :             if purge {
    1814            2 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1815            2 :                 if let Err(e) = match entry.file_type() {
    1816            2 :                     Ok(t) => if t.is_dir() {
    1817            2 :                         std::fs::remove_dir_all(entry_path)
    1818              :                     } else {
    1819            0 :                         std::fs::remove_file(entry_path)
    1820              :                     }
    1821            2 :                     .or_else(fs_ext::ignore_not_found),
    1822            0 :                     Err(e) => Err(e),
    1823              :                 } {
    1824            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1825            2 :                 }
    1826            6 :             }
    1827              :         }
    1828              : 
    1829          220 :         Ok(())
    1830          220 :     }
    1831              : 
    1832              :     /// Get sum of all remote timelines sizes
    1833              :     ///
    1834              :     /// This function relies on the index_part instead of listing the remote storage
    1835            0 :     pub fn remote_size(&self) -> u64 {
    1836            0 :         let mut size = 0;
    1837              : 
    1838            0 :         for timeline in self.list_timelines() {
    1839            0 :             size += timeline.remote_client.get_remote_physical_size();
    1840            0 :         }
    1841              : 
    1842            0 :         size
    1843            0 :     }
    1844              : 
    1845              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1846              :     async fn load_remote_timeline(
    1847              :         self: &Arc<Self>,
    1848              :         timeline_id: TimelineId,
    1849              :         index_part: IndexPart,
    1850              :         remote_metadata: TimelineMetadata,
    1851              :         resources: TimelineResources,
    1852              :         cause: LoadTimelineCause,
    1853              :         ctx: &RequestContext,
    1854              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1855              :         span::debug_assert_current_span_has_tenant_id();
    1856              : 
    1857              :         info!("downloading index file for timeline {}", timeline_id);
    1858              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1859              :             .await
    1860              :             .context("Failed to create new timeline directory")?;
    1861              : 
    1862              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1863              :             let timelines = self.timelines.lock().unwrap();
    1864              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1865            0 :                 || {
    1866            0 :                     anyhow::anyhow!(
    1867            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1868            0 :                     )
    1869            0 :                 },
    1870              :             )?))
    1871              :         } else {
    1872              :             None
    1873              :         };
    1874              : 
    1875              :         self.timeline_init_and_sync(
    1876              :             timeline_id,
    1877              :             resources,
    1878              :             index_part,
    1879              :             remote_metadata,
    1880              :             ancestor,
    1881              :             cause,
    1882              :             ctx,
    1883              :         )
    1884              :         .await
    1885              :     }
    1886              : 
    1887          220 :     async fn load_timelines_metadata(
    1888          220 :         self: &Arc<Tenant>,
    1889          220 :         timeline_ids: HashSet<TimelineId>,
    1890          220 :         remote_storage: &GenericRemoteStorage,
    1891          220 :         cancel: CancellationToken,
    1892          220 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1893          220 :         let mut part_downloads = JoinSet::new();
    1894          226 :         for timeline_id in timeline_ids {
    1895            6 :             let cancel_clone = cancel.clone();
    1896            6 :             part_downloads.spawn(
    1897            6 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1898            6 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1899              :             );
    1900              :         }
    1901              : 
    1902          220 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1903              : 
    1904              :         loop {
    1905          226 :             tokio::select!(
    1906          226 :                 next = part_downloads.join_next() => {
    1907          226 :                     match next {
    1908            6 :                         Some(result) => {
    1909            6 :                             let preload = result.context("join preload task")?;
    1910            6 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1911              :                         },
    1912              :                         None => {
    1913          220 :                             break;
    1914              :                         }
    1915              :                     }
    1916              :                 },
    1917          226 :                 _ = cancel.cancelled() => {
    1918            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1919              :                 }
    1920              :             )
    1921              :         }
    1922              : 
    1923          220 :         Ok(timeline_preloads)
    1924          220 :     }
    1925              : 
    1926            6 :     fn build_timeline_client(
    1927            6 :         &self,
    1928            6 :         timeline_id: TimelineId,
    1929            6 :         remote_storage: GenericRemoteStorage,
    1930            6 :     ) -> RemoteTimelineClient {
    1931            6 :         RemoteTimelineClient::new(
    1932            6 :             remote_storage.clone(),
    1933            6 :             self.deletion_queue_client.clone(),
    1934            6 :             self.conf,
    1935            6 :             self.tenant_shard_id,
    1936            6 :             timeline_id,
    1937            6 :             self.generation,
    1938            6 :             &self.tenant_conf.load().location,
    1939            6 :         )
    1940            6 :     }
    1941              : 
    1942            6 :     fn load_timeline_metadata(
    1943            6 :         self: &Arc<Tenant>,
    1944            6 :         timeline_id: TimelineId,
    1945            6 :         remote_storage: GenericRemoteStorage,
    1946            6 :         cancel: CancellationToken,
    1947            6 :     ) -> impl Future<Output = TimelinePreload> {
    1948            6 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1949            6 :         async move {
    1950            6 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1951            6 :             debug!("starting index part download");
    1952              : 
    1953            6 :             let index_part = client.download_index_file(&cancel).await;
    1954              : 
    1955            6 :             debug!("finished index part download");
    1956              : 
    1957            6 :             TimelinePreload {
    1958            6 :                 client,
    1959            6 :                 timeline_id,
    1960            6 :                 index_part,
    1961            6 :             }
    1962            6 :         }
    1963            6 :     }
    1964              : 
    1965            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1966            0 :         timeline_id: TimelineId,
    1967            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1968            0 :     ) -> Result<(), TimelineArchivalError> {
    1969            0 :         let children: Vec<TimelineId> = timelines
    1970            0 :             .iter()
    1971            0 :             .filter_map(|(id, entry)| {
    1972            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1973            0 :                     return None;
    1974            0 :                 }
    1975            0 :                 if entry.is_archived() == Some(true) {
    1976            0 :                     return None;
    1977            0 :                 }
    1978            0 :                 Some(*id)
    1979            0 :             })
    1980            0 :             .collect();
    1981            0 : 
    1982            0 :         if !children.is_empty() {
    1983            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1984            0 :         }
    1985            0 :         Ok(())
    1986            0 :     }
    1987              : 
    1988            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1989            0 :         ancestor_timeline_id: TimelineId,
    1990            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1991            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1992            0 :             '_,
    1993            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1994            0 :         >,
    1995            0 :     ) -> Result<(), TimelineArchivalError> {
    1996            0 :         let has_archived_parent =
    1997            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    1998            0 :                 ancestor_timeline.is_archived() == Some(true)
    1999            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2000            0 :                 true
    2001              :             } else {
    2002            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2003            0 :                 if cfg!(debug_assertions) {
    2004            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2005            0 :                 }
    2006            0 :                 return Err(TimelineArchivalError::NotFound);
    2007              :             };
    2008            0 :         if has_archived_parent {
    2009            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2010            0 :                 ancestor_timeline_id,
    2011            0 :             ));
    2012            0 :         }
    2013            0 :         Ok(())
    2014            0 :     }
    2015              : 
    2016            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2017            0 :         timeline: &Arc<Timeline>,
    2018            0 :     ) -> Result<(), TimelineArchivalError> {
    2019            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2020            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2021            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2022            0 :                     ancestor_timeline.timeline_id,
    2023            0 :                 ));
    2024            0 :             }
    2025            0 :         }
    2026            0 :         Ok(())
    2027            0 :     }
    2028              : 
    2029              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2030              :     ///
    2031              :     /// Counterpart to [`offload_timeline`].
    2032            0 :     async fn unoffload_timeline(
    2033            0 :         self: &Arc<Self>,
    2034            0 :         timeline_id: TimelineId,
    2035            0 :         broker_client: storage_broker::BrokerClientChannel,
    2036            0 :         ctx: RequestContext,
    2037            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2038            0 :         info!("unoffloading timeline");
    2039              : 
    2040              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2041              :         // We expect callers of this function to ensure this.
    2042            0 :         match self.current_state() {
    2043              :             TenantState::Activating { .. }
    2044              :             | TenantState::Attaching
    2045              :             | TenantState::Broken { .. } => {
    2046            0 :                 panic!("Timeline expected to be active")
    2047              :             }
    2048            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2049            0 :             TenantState::Active => {}
    2050            0 :         }
    2051            0 :         let cancel = self.cancel.clone();
    2052            0 : 
    2053            0 :         // Protect against concurrent attempts to use this TimelineId
    2054            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2055            0 :         let allow_offloaded = true;
    2056            0 :         let _create_guard = self
    2057            0 :             .create_timeline_create_guard(
    2058            0 :                 timeline_id,
    2059            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2060            0 :                 allow_offloaded,
    2061            0 :             )
    2062            0 :             .map_err(|err| match err {
    2063            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2064              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2065            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2066              :                 }
    2067            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2068            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2069            0 :             })?;
    2070              : 
    2071            0 :         let timeline_preload = self
    2072            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    2073            0 :             .await;
    2074              : 
    2075            0 :         let index_part = match timeline_preload.index_part {
    2076            0 :             Ok(index_part) => {
    2077            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2078            0 :                 index_part
    2079              :             }
    2080              :             Err(DownloadError::NotFound) => {
    2081            0 :                 error!(%timeline_id, "index_part not found on remote");
    2082            0 :                 return Err(TimelineArchivalError::NotFound);
    2083              :             }
    2084            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2085            0 :             Err(e) => {
    2086            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2087            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2088            0 :                 return Err(TimelineArchivalError::Other(
    2089            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2090            0 :                 ));
    2091              :             }
    2092              :         };
    2093            0 :         let index_part = match index_part {
    2094            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2095            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2096            0 :                 info!("timeline is deleted according to index_part.json");
    2097            0 :                 return Err(TimelineArchivalError::NotFound);
    2098              :             }
    2099              :         };
    2100            0 :         let remote_metadata = index_part.metadata.clone();
    2101            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2102            0 :         self.load_remote_timeline(
    2103            0 :             timeline_id,
    2104            0 :             index_part,
    2105            0 :             remote_metadata,
    2106            0 :             timeline_resources,
    2107            0 :             LoadTimelineCause::Unoffload,
    2108            0 :             &ctx,
    2109            0 :         )
    2110            0 :         .await
    2111            0 :         .with_context(|| {
    2112            0 :             format!(
    2113            0 :                 "failed to load remote timeline {} for tenant {}",
    2114            0 :                 timeline_id, self.tenant_shard_id
    2115            0 :             )
    2116            0 :         })
    2117            0 :         .map_err(TimelineArchivalError::Other)?;
    2118              : 
    2119            0 :         let timeline = {
    2120            0 :             let timelines = self.timelines.lock().unwrap();
    2121            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2122            0 :                 warn!("timeline not available directly after attach");
    2123              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2124              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2125            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2126            0 :                     "timeline not available directly after attach"
    2127            0 :                 )));
    2128              :             };
    2129            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2130            0 :             match offloaded_timelines.remove(&timeline_id) {
    2131            0 :                 Some(offloaded) => {
    2132            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2133            0 :                 }
    2134            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2135              :             }
    2136              : 
    2137            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2138            0 : 
    2139            0 :             Arc::clone(timeline)
    2140            0 :         };
    2141            0 : 
    2142            0 :         // Upload new list of offloaded timelines to S3
    2143            0 :         self.store_tenant_manifest().await?;
    2144              : 
    2145              :         // Activate the timeline (if it makes sense)
    2146            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2147            0 :             let background_jobs_can_start = None;
    2148            0 :             timeline.activate(
    2149            0 :                 self.clone(),
    2150            0 :                 broker_client.clone(),
    2151            0 :                 background_jobs_can_start,
    2152            0 :                 &ctx,
    2153            0 :             );
    2154            0 :         }
    2155              : 
    2156            0 :         info!("timeline unoffloading complete");
    2157            0 :         Ok(timeline)
    2158            0 :     }
    2159              : 
    2160            0 :     pub(crate) async fn apply_timeline_archival_config(
    2161            0 :         self: &Arc<Self>,
    2162            0 :         timeline_id: TimelineId,
    2163            0 :         new_state: TimelineArchivalState,
    2164            0 :         broker_client: storage_broker::BrokerClientChannel,
    2165            0 :         ctx: RequestContext,
    2166            0 :     ) -> Result<(), TimelineArchivalError> {
    2167            0 :         info!("setting timeline archival config");
    2168              :         // First part: figure out what is needed to do, and do validation
    2169            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2170            0 :             let timelines = self.timelines.lock().unwrap();
    2171              : 
    2172            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2173            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2174            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2175            0 :                     return Err(TimelineArchivalError::NotFound);
    2176              :                 };
    2177            0 :                 if new_state == TimelineArchivalState::Archived {
    2178              :                     // It's offloaded already, so nothing to do
    2179            0 :                     return Ok(());
    2180            0 :                 }
    2181            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2182            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2183            0 :                         ancestor_timeline_id,
    2184            0 :                         &timelines,
    2185            0 :                         &offloaded_timelines,
    2186            0 :                     )?;
    2187            0 :                 }
    2188            0 :                 break 'outer None;
    2189              :             };
    2190              : 
    2191              :             // Do some validation. We release the timelines lock below, so there is potential
    2192              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2193              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2194            0 :             match new_state {
    2195              :                 TimelineArchivalState::Unarchived => {
    2196            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2197              :                 }
    2198              :                 TimelineArchivalState::Archived => {
    2199            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2200              :                 }
    2201              :             }
    2202            0 :             Some(Arc::clone(timeline))
    2203              :         };
    2204              : 
    2205              :         // Second part: unoffload timeline (if needed)
    2206            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2207            0 :             timeline
    2208              :         } else {
    2209              :             // Turn offloaded timeline into a non-offloaded one
    2210            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2211            0 :                 .await?
    2212              :         };
    2213              : 
    2214              :         // Third part: upload new timeline archival state and block until it is present in S3
    2215            0 :         let upload_needed = match timeline
    2216            0 :             .remote_client
    2217            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2218              :         {
    2219            0 :             Ok(upload_needed) => upload_needed,
    2220            0 :             Err(e) => {
    2221            0 :                 if timeline.cancel.is_cancelled() {
    2222            0 :                     return Err(TimelineArchivalError::Cancelled);
    2223              :                 } else {
    2224            0 :                     return Err(TimelineArchivalError::Other(e));
    2225              :                 }
    2226              :             }
    2227              :         };
    2228              : 
    2229            0 :         if upload_needed {
    2230            0 :             info!("Uploading new state");
    2231              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2232            0 :             let Ok(v) =
    2233            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2234              :             else {
    2235            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2236            0 :                 return Err(TimelineArchivalError::Timeout);
    2237              :             };
    2238            0 :             v.map_err(|e| match e {
    2239            0 :                 WaitCompletionError::NotInitialized(e) => {
    2240            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2241              :                 }
    2242              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2243            0 :                     TimelineArchivalError::Cancelled
    2244              :                 }
    2245            0 :             })?;
    2246            0 :         }
    2247            0 :         Ok(())
    2248            0 :     }
    2249              : 
    2250            2 :     pub fn get_offloaded_timeline(
    2251            2 :         &self,
    2252            2 :         timeline_id: TimelineId,
    2253            2 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2254            2 :         self.timelines_offloaded
    2255            2 :             .lock()
    2256            2 :             .unwrap()
    2257            2 :             .get(&timeline_id)
    2258            2 :             .map(Arc::clone)
    2259            2 :             .ok_or(GetTimelineError::NotFound {
    2260            2 :                 tenant_id: self.tenant_shard_id,
    2261            2 :                 timeline_id,
    2262            2 :             })
    2263            2 :     }
    2264              : 
    2265            4 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2266            4 :         self.tenant_shard_id
    2267            4 :     }
    2268              : 
    2269              :     /// Get Timeline handle for given Neon timeline ID.
    2270              :     /// This function is idempotent. It doesn't change internal state in any way.
    2271          222 :     pub fn get_timeline(
    2272          222 :         &self,
    2273          222 :         timeline_id: TimelineId,
    2274          222 :         active_only: bool,
    2275          222 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2276          222 :         let timelines_accessor = self.timelines.lock().unwrap();
    2277          222 :         let timeline = timelines_accessor
    2278          222 :             .get(&timeline_id)
    2279          222 :             .ok_or(GetTimelineError::NotFound {
    2280          222 :                 tenant_id: self.tenant_shard_id,
    2281          222 :                 timeline_id,
    2282          222 :             })?;
    2283              : 
    2284          220 :         if active_only && !timeline.is_active() {
    2285            0 :             Err(GetTimelineError::NotActive {
    2286            0 :                 tenant_id: self.tenant_shard_id,
    2287            0 :                 timeline_id,
    2288            0 :                 state: timeline.current_state(),
    2289            0 :             })
    2290              :         } else {
    2291          220 :             Ok(Arc::clone(timeline))
    2292              :         }
    2293          222 :     }
    2294              : 
    2295              :     /// Lists timelines the tenant contains.
    2296              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2297            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2298            0 :         self.timelines
    2299            0 :             .lock()
    2300            0 :             .unwrap()
    2301            0 :             .values()
    2302            0 :             .map(Arc::clone)
    2303            0 :             .collect()
    2304            0 :     }
    2305              : 
    2306              :     /// Lists timelines the tenant manages, including offloaded ones.
    2307              :     ///
    2308              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2309            0 :     pub fn list_timelines_and_offloaded(
    2310            0 :         &self,
    2311            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2312            0 :         let timelines = self
    2313            0 :             .timelines
    2314            0 :             .lock()
    2315            0 :             .unwrap()
    2316            0 :             .values()
    2317            0 :             .map(Arc::clone)
    2318            0 :             .collect();
    2319            0 :         let offloaded = self
    2320            0 :             .timelines_offloaded
    2321            0 :             .lock()
    2322            0 :             .unwrap()
    2323            0 :             .values()
    2324            0 :             .map(Arc::clone)
    2325            0 :             .collect();
    2326            0 :         (timelines, offloaded)
    2327            0 :     }
    2328              : 
    2329            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2330            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2331            0 :     }
    2332              : 
    2333              :     /// This is used by tests & import-from-basebackup.
    2334              :     ///
    2335              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2336              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2337              :     ///
    2338              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2339              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2340              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2341              :     /// to the [`Tenant::timelines`].
    2342              :     ///
    2343              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2344          212 :     pub(crate) async fn create_empty_timeline(
    2345          212 :         self: &Arc<Self>,
    2346          212 :         new_timeline_id: TimelineId,
    2347          212 :         initdb_lsn: Lsn,
    2348          212 :         pg_version: u32,
    2349          212 :         _ctx: &RequestContext,
    2350          212 :     ) -> anyhow::Result<UninitializedTimeline> {
    2351          212 :         anyhow::ensure!(
    2352          212 :             self.is_active(),
    2353            0 :             "Cannot create empty timelines on inactive tenant"
    2354              :         );
    2355              : 
    2356              :         // Protect against concurrent attempts to use this TimelineId
    2357          212 :         let create_guard = match self
    2358          212 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2359          212 :             .await?
    2360              :         {
    2361          210 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2362              :             StartCreatingTimelineResult::Idempotent(_) => {
    2363            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2364              :             }
    2365              :         };
    2366              : 
    2367          210 :         let new_metadata = TimelineMetadata::new(
    2368          210 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2369          210 :             // make it valid, before calling finish_creation()
    2370          210 :             Lsn(0),
    2371          210 :             None,
    2372          210 :             None,
    2373          210 :             Lsn(0),
    2374          210 :             initdb_lsn,
    2375          210 :             initdb_lsn,
    2376          210 :             pg_version,
    2377          210 :         );
    2378          210 :         self.prepare_new_timeline(
    2379          210 :             new_timeline_id,
    2380          210 :             &new_metadata,
    2381          210 :             create_guard,
    2382          210 :             initdb_lsn,
    2383          210 :             None,
    2384          210 :         )
    2385          210 :         .await
    2386          212 :     }
    2387              : 
    2388              :     /// Helper for unit tests to create an empty timeline.
    2389              :     ///
    2390              :     /// The timeline is has state value `Active` but its background loops are not running.
    2391              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2392              :     // Our current tests don't need the background loops.
    2393              :     #[cfg(test)]
    2394          202 :     pub async fn create_test_timeline(
    2395          202 :         self: &Arc<Self>,
    2396          202 :         new_timeline_id: TimelineId,
    2397          202 :         initdb_lsn: Lsn,
    2398          202 :         pg_version: u32,
    2399          202 :         ctx: &RequestContext,
    2400          202 :     ) -> anyhow::Result<Arc<Timeline>> {
    2401          202 :         let uninit_tl = self
    2402          202 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2403          202 :             .await?;
    2404          202 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2405          202 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2406              : 
    2407              :         // Setup minimum keys required for the timeline to be usable.
    2408          202 :         let mut modification = tline.begin_modification(initdb_lsn);
    2409          202 :         modification
    2410          202 :             .init_empty_test_timeline()
    2411          202 :             .context("init_empty_test_timeline")?;
    2412          202 :         modification
    2413          202 :             .commit(ctx)
    2414          202 :             .await
    2415          202 :             .context("commit init_empty_test_timeline modification")?;
    2416              : 
    2417              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2418          202 :         tline.maybe_spawn_flush_loop();
    2419          202 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2420              : 
    2421              :         // Make sure the freeze_and_flush reaches remote storage.
    2422          202 :         tline.remote_client.wait_completion().await.unwrap();
    2423              : 
    2424          202 :         let tl = uninit_tl.finish_creation()?;
    2425              :         // The non-test code would call tl.activate() here.
    2426          202 :         tl.set_state(TimelineState::Active);
    2427          202 :         Ok(tl)
    2428          202 :     }
    2429              : 
    2430              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2431              :     #[cfg(test)]
    2432              :     #[allow(clippy::too_many_arguments)]
    2433           36 :     pub async fn create_test_timeline_with_layers(
    2434           36 :         self: &Arc<Self>,
    2435           36 :         new_timeline_id: TimelineId,
    2436           36 :         initdb_lsn: Lsn,
    2437           36 :         pg_version: u32,
    2438           36 :         ctx: &RequestContext,
    2439           36 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2440           36 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2441           36 :         end_lsn: Lsn,
    2442           36 :     ) -> anyhow::Result<Arc<Timeline>> {
    2443              :         use checks::check_valid_layermap;
    2444              :         use itertools::Itertools;
    2445              : 
    2446           36 :         let tline = self
    2447           36 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2448           36 :             .await?;
    2449           36 :         tline.force_advance_lsn(end_lsn);
    2450          120 :         for deltas in delta_layer_desc {
    2451           84 :             tline
    2452           84 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2453           84 :                 .await?;
    2454              :         }
    2455           88 :         for (lsn, images) in image_layer_desc {
    2456           52 :             tline
    2457           52 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2458           52 :                 .await?;
    2459              :         }
    2460           36 :         let layer_names = tline
    2461           36 :             .layers
    2462           36 :             .read()
    2463           36 :             .await
    2464           36 :             .layer_map()
    2465           36 :             .unwrap()
    2466           36 :             .iter_historic_layers()
    2467          172 :             .map(|layer| layer.layer_name())
    2468           36 :             .collect_vec();
    2469           36 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2470            0 :             bail!("invalid layermap: {err}");
    2471           36 :         }
    2472           36 :         Ok(tline)
    2473           36 :     }
    2474              : 
    2475              :     /// Create a new timeline.
    2476              :     ///
    2477              :     /// Returns the new timeline ID and reference to its Timeline object.
    2478              :     ///
    2479              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2480              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2481              :     #[allow(clippy::too_many_arguments)]
    2482            0 :     pub(crate) async fn create_timeline(
    2483            0 :         self: &Arc<Tenant>,
    2484            0 :         params: CreateTimelineParams,
    2485            0 :         broker_client: storage_broker::BrokerClientChannel,
    2486            0 :         ctx: &RequestContext,
    2487            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2488            0 :         if !self.is_active() {
    2489            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2490            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2491              :             } else {
    2492            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2493            0 :                     "Cannot create timelines on inactive tenant"
    2494            0 :                 )));
    2495              :             }
    2496            0 :         }
    2497              : 
    2498            0 :         let _gate = self
    2499            0 :             .gate
    2500            0 :             .enter()
    2501            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2502              : 
    2503            0 :         let result: CreateTimelineResult = match params {
    2504              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2505            0 :                 new_timeline_id,
    2506            0 :                 existing_initdb_timeline_id,
    2507            0 :                 pg_version,
    2508            0 :             }) => {
    2509            0 :                 self.bootstrap_timeline(
    2510            0 :                     new_timeline_id,
    2511            0 :                     pg_version,
    2512            0 :                     existing_initdb_timeline_id,
    2513            0 :                     ctx,
    2514            0 :                 )
    2515            0 :                 .await?
    2516              :             }
    2517              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2518            0 :                 new_timeline_id,
    2519            0 :                 ancestor_timeline_id,
    2520            0 :                 mut ancestor_start_lsn,
    2521              :             }) => {
    2522            0 :                 let ancestor_timeline = self
    2523            0 :                     .get_timeline(ancestor_timeline_id, false)
    2524            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2525              : 
    2526              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2527              :                 // ready for other purposes either.
    2528            0 :                 if !ancestor_timeline.is_active() {
    2529            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2530            0 :                 }
    2531            0 : 
    2532            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2533            0 :                     info!("tried to branch archived timeline");
    2534            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2535            0 :                 }
    2536              : 
    2537            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2538            0 :                     *lsn = lsn.align();
    2539            0 : 
    2540            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2541            0 :                     if ancestor_ancestor_lsn > *lsn {
    2542              :                         // can we safely just branch from the ancestor instead?
    2543            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2544            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2545            0 :                             lsn,
    2546            0 :                             ancestor_timeline_id,
    2547            0 :                             ancestor_ancestor_lsn,
    2548            0 :                         )));
    2549            0 :                     }
    2550            0 : 
    2551            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2552            0 :                     // to the requested branch point. The repository code itself doesn't
    2553            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2554            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2555            0 :                     // sizes etc. and that would get confused if the previous page versions
    2556            0 :                     // are not in the repository yet.
    2557            0 :                     ancestor_timeline
    2558            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    2559            0 :                         .await
    2560            0 :                         .map_err(|e| match e {
    2561            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2562            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2563              :                             }
    2564            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2565            0 :                         })?;
    2566            0 :                 }
    2567              : 
    2568            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2569            0 :                     .await?
    2570              :             }
    2571            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2572            0 :                 self.create_timeline_import_pgdata(
    2573            0 :                     params,
    2574            0 :                     ActivateTimelineArgs::Yes {
    2575            0 :                         broker_client: broker_client.clone(),
    2576            0 :                     },
    2577            0 :                     ctx,
    2578            0 :                 )
    2579            0 :                 .await?
    2580              :             }
    2581              :         };
    2582              : 
    2583              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2584              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2585              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2586              :         //
    2587              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2588              :         // assume that, because they can see the timeline via API, that the creation is done and
    2589              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2590              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2591              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2592              :         //
    2593              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2594              :         // creation API until it returns success. Only then is durability guaranteed.
    2595            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2596            0 :         result
    2597            0 :             .timeline()
    2598            0 :             .remote_client
    2599            0 :             .wait_completion()
    2600            0 :             .await
    2601            0 :             .map_err(|e| match e {
    2602              :                 WaitCompletionError::NotInitialized(
    2603            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2604            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2605              :                 WaitCompletionError::NotInitialized(_) => {
    2606              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2607            0 :                     debug_assert!(false);
    2608            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2609              :                 }
    2610              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2611            0 :                     CreateTimelineError::ShuttingDown
    2612              :                 }
    2613            0 :             })?;
    2614              : 
    2615              :         // The creating task is responsible for activating the timeline.
    2616              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2617              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2618            0 :         let activated_timeline = match result {
    2619            0 :             CreateTimelineResult::Created(timeline) => {
    2620            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2621            0 :                 timeline
    2622              :             }
    2623            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2624            0 :                 info!(
    2625            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2626              :                 );
    2627            0 :                 timeline
    2628              :             }
    2629            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2630            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2631            0 :                 timeline
    2632              :             }
    2633              :         };
    2634              : 
    2635            0 :         Ok(activated_timeline)
    2636            0 :     }
    2637              : 
    2638              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2639              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2640              :     /// [`Tenant::timelines`] map when the import completes.
    2641              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2642              :     /// for the response.
    2643            0 :     async fn create_timeline_import_pgdata(
    2644            0 :         self: &Arc<Tenant>,
    2645            0 :         params: CreateTimelineParamsImportPgdata,
    2646            0 :         activate: ActivateTimelineArgs,
    2647            0 :         ctx: &RequestContext,
    2648            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2649            0 :         let CreateTimelineParamsImportPgdata {
    2650            0 :             new_timeline_id,
    2651            0 :             location,
    2652            0 :             idempotency_key,
    2653            0 :         } = params;
    2654            0 : 
    2655            0 :         let started_at = chrono::Utc::now().naive_utc();
    2656              : 
    2657              :         //
    2658              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2659              :         // is the canonical way we do it.
    2660              :         // - create an empty timeline in-memory
    2661              :         // - use its remote_timeline_client to do the upload
    2662              :         // - dispose of the uninit timeline
    2663              :         // - keep the creation guard alive
    2664              : 
    2665            0 :         let timeline_create_guard = match self
    2666            0 :             .start_creating_timeline(
    2667            0 :                 new_timeline_id,
    2668            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2669            0 :                     idempotency_key: idempotency_key.clone(),
    2670            0 :                 }),
    2671            0 :             )
    2672            0 :             .await?
    2673              :         {
    2674            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2675            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2676            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2677              :             }
    2678              :         };
    2679              : 
    2680            0 :         let mut uninit_timeline = {
    2681            0 :             let this = &self;
    2682            0 :             let initdb_lsn = Lsn(0);
    2683            0 :             let _ctx = ctx;
    2684            0 :             async move {
    2685            0 :                 let new_metadata = TimelineMetadata::new(
    2686            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2687            0 :                     // make it valid, before calling finish_creation()
    2688            0 :                     Lsn(0),
    2689            0 :                     None,
    2690            0 :                     None,
    2691            0 :                     Lsn(0),
    2692            0 :                     initdb_lsn,
    2693            0 :                     initdb_lsn,
    2694            0 :                     15,
    2695            0 :                 );
    2696            0 :                 this.prepare_new_timeline(
    2697            0 :                     new_timeline_id,
    2698            0 :                     &new_metadata,
    2699            0 :                     timeline_create_guard,
    2700            0 :                     initdb_lsn,
    2701            0 :                     None,
    2702            0 :                 )
    2703            0 :                 .await
    2704            0 :             }
    2705            0 :         }
    2706            0 :         .await?;
    2707              : 
    2708            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2709            0 :             idempotency_key,
    2710            0 :             location,
    2711            0 :             started_at,
    2712            0 :         };
    2713            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2714            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2715            0 :         );
    2716            0 :         uninit_timeline
    2717            0 :             .raw_timeline()
    2718            0 :             .unwrap()
    2719            0 :             .remote_client
    2720            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2721              : 
    2722              :         // wait_completion happens in caller
    2723              : 
    2724            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2725            0 : 
    2726            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2727            0 :             timeline.clone(),
    2728            0 :             index_part,
    2729            0 :             activate,
    2730            0 :             timeline_create_guard,
    2731            0 :         ));
    2732            0 : 
    2733            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2734            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2735            0 :     }
    2736              : 
    2737              :     #[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))]
    2738              :     async fn create_timeline_import_pgdata_task(
    2739              :         self: Arc<Tenant>,
    2740              :         timeline: Arc<Timeline>,
    2741              :         index_part: import_pgdata::index_part_format::Root,
    2742              :         activate: ActivateTimelineArgs,
    2743              :         timeline_create_guard: TimelineCreateGuard,
    2744              :     ) {
    2745              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2746              :         info!("starting");
    2747              :         scopeguard::defer! {info!("exiting")};
    2748              : 
    2749              :         let res = self
    2750              :             .create_timeline_import_pgdata_task_impl(
    2751              :                 timeline,
    2752              :                 index_part,
    2753              :                 activate,
    2754              :                 timeline_create_guard,
    2755              :             )
    2756              :             .await;
    2757              :         if let Err(err) = &res {
    2758              :             error!(?err, "task failed");
    2759              :             // TODO sleep & retry, sensitive to tenant shutdown
    2760              :             // TODO: allow timeline deletion requests => should cancel the task
    2761              :         }
    2762              :     }
    2763              : 
    2764            0 :     async fn create_timeline_import_pgdata_task_impl(
    2765            0 :         self: Arc<Tenant>,
    2766            0 :         timeline: Arc<Timeline>,
    2767            0 :         index_part: import_pgdata::index_part_format::Root,
    2768            0 :         activate: ActivateTimelineArgs,
    2769            0 :         timeline_create_guard: TimelineCreateGuard,
    2770            0 :     ) -> Result<(), anyhow::Error> {
    2771            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2772            0 : 
    2773            0 :         info!("importing pgdata");
    2774            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2775            0 :             .await
    2776            0 :             .context("import")?;
    2777            0 :         info!("import done");
    2778              : 
    2779              :         //
    2780              :         // Reload timeline from remote.
    2781              :         // This proves that the remote state is attachable, and it reuses the code.
    2782              :         //
    2783              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2784              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2785              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2786              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2787              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2788              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2789              :         // to manifest because of the long runtime of this import task.
    2790              : 
    2791              :         //        in theory this shouldn't even .await anything except for coop yield
    2792            0 :         info!("shutting down timeline");
    2793            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2794            0 :         info!("timeline shut down, reloading from remote");
    2795              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2796              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2797              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2798              :         // };
    2799            0 :         let timeline_id = timeline.timeline_id;
    2800            0 : 
    2801            0 :         // load from object storage like Tenant::attach does
    2802            0 :         let resources = self.build_timeline_resources(timeline_id);
    2803            0 :         let index_part = resources
    2804            0 :             .remote_client
    2805            0 :             .download_index_file(&self.cancel)
    2806            0 :             .await?;
    2807            0 :         let index_part = match index_part {
    2808              :             MaybeDeletedIndexPart::Deleted(_) => {
    2809              :                 // likely concurrent delete call, cplane should prevent this
    2810            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2811              :             }
    2812            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2813            0 :         };
    2814            0 :         let metadata = index_part.metadata.clone();
    2815            0 :         self
    2816            0 :             .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
    2817            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2818            0 :             .await?
    2819            0 :             .ready_to_activate()
    2820            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2821              : 
    2822            0 :         anyhow::Ok(())
    2823            0 :     }
    2824              : 
    2825            0 :     pub(crate) async fn delete_timeline(
    2826            0 :         self: Arc<Self>,
    2827            0 :         timeline_id: TimelineId,
    2828            0 :     ) -> Result<(), DeleteTimelineError> {
    2829            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2830              : 
    2831            0 :         Ok(())
    2832            0 :     }
    2833              : 
    2834              :     /// perform one garbage collection iteration, removing old data files from disk.
    2835              :     /// this function is periodically called by gc task.
    2836              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2837              :     ///
    2838              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2839              :     ///
    2840              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2841              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2842              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2843              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2844              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2845              :     /// requires more history to be retained.
    2846              :     //
    2847          754 :     pub(crate) async fn gc_iteration(
    2848          754 :         &self,
    2849          754 :         target_timeline_id: Option<TimelineId>,
    2850          754 :         horizon: u64,
    2851          754 :         pitr: Duration,
    2852          754 :         cancel: &CancellationToken,
    2853          754 :         ctx: &RequestContext,
    2854          754 :     ) -> Result<GcResult, GcError> {
    2855          754 :         // Don't start doing work during shutdown
    2856          754 :         if let TenantState::Stopping { .. } = self.current_state() {
    2857            0 :             return Ok(GcResult::default());
    2858          754 :         }
    2859          754 : 
    2860          754 :         // there is a global allowed_error for this
    2861          754 :         if !self.is_active() {
    2862            0 :             return Err(GcError::NotActive);
    2863          754 :         }
    2864          754 : 
    2865          754 :         {
    2866          754 :             let conf = self.tenant_conf.load();
    2867          754 : 
    2868          754 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2869          754 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2870          754 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2871          754 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2872          754 :             if !conf.location.may_delete_layers_hint() {
    2873            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2874            0 :                 return Ok(GcResult::default());
    2875          754 :             }
    2876          754 : 
    2877          754 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2878          750 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2879          750 :                 return Ok(GcResult::default());
    2880            4 :             }
    2881              :         }
    2882              : 
    2883            4 :         let _guard = match self.gc_block.start().await {
    2884            4 :             Ok(guard) => guard,
    2885            0 :             Err(reasons) => {
    2886            0 :                 info!("Skipping GC: {reasons}");
    2887            0 :                 return Ok(GcResult::default());
    2888              :             }
    2889              :         };
    2890              : 
    2891            4 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2892            4 :             .await
    2893          754 :     }
    2894              : 
    2895              :     /// Perform one compaction iteration.
    2896              :     /// This function is periodically called by compactor task.
    2897              :     /// Also it can be explicitly requested per timeline through page server
    2898              :     /// api's 'compact' command.
    2899              :     ///
    2900              :     /// Returns whether we have pending compaction task.
    2901            0 :     async fn compaction_iteration(
    2902            0 :         self: &Arc<Self>,
    2903            0 :         cancel: &CancellationToken,
    2904            0 :         ctx: &RequestContext,
    2905            0 :     ) -> Result<bool, timeline::CompactionError> {
    2906            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2907            0 :         if !self.is_active() {
    2908            0 :             return Ok(false);
    2909            0 :         }
    2910            0 : 
    2911            0 :         {
    2912            0 :             let conf = self.tenant_conf.load();
    2913            0 : 
    2914            0 :             // Note that compaction usually requires deletions, but we don't respect
    2915            0 :             // may_delete_layers_hint here: that is because tenants in AttachedMulti
    2916            0 :             // should proceed with compaction even if they can't do deletion, to avoid
    2917            0 :             // accumulating dangerously deep stacks of L0 layers.  Deletions will be
    2918            0 :             // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
    2919            0 :             // to AttachedSingle state.
    2920            0 :             if !conf.location.may_upload_layers_hint() {
    2921            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2922            0 :                 return Ok(false);
    2923            0 :             }
    2924            0 :         }
    2925            0 : 
    2926            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2927            0 :         // while holding the lock. Then drop the lock and actually perform the
    2928            0 :         // compactions.  We don't want to block everything else while the
    2929            0 :         // compaction runs.
    2930            0 :         let timelines_to_compact_or_offload;
    2931            0 :         {
    2932            0 :             let timelines = self.timelines.lock().unwrap();
    2933            0 :             timelines_to_compact_or_offload = timelines
    2934            0 :                 .iter()
    2935            0 :                 .filter_map(|(timeline_id, timeline)| {
    2936            0 :                     let (is_active, (can_offload, _)) =
    2937            0 :                         (timeline.is_active(), timeline.can_offload());
    2938            0 :                     let has_no_unoffloaded_children = {
    2939            0 :                         !timelines
    2940            0 :                             .iter()
    2941            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2942              :                     };
    2943            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2944            0 :                         || self
    2945            0 :                             .tenant_conf
    2946            0 :                             .load()
    2947            0 :                             .tenant_conf
    2948            0 :                             .timeline_offloading
    2949            0 :                             .unwrap_or_default();
    2950            0 :                     let can_offload =
    2951            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2952            0 :                     if (is_active, can_offload) == (false, false) {
    2953            0 :                         None
    2954              :                     } else {
    2955            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2956              :                     }
    2957            0 :                 })
    2958            0 :                 .collect::<Vec<_>>();
    2959            0 :             drop(timelines);
    2960            0 :         }
    2961            0 : 
    2962            0 :         // Before doing any I/O work, check our circuit breaker
    2963            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2964            0 :             info!("Skipping compaction due to previous failures");
    2965            0 :             return Ok(false);
    2966            0 :         }
    2967            0 : 
    2968            0 :         let mut has_pending_task = false;
    2969              : 
    2970            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2971              :         {
    2972              :             // pending_task_left == None: cannot compact, maybe still pending tasks
    2973              :             // pending_task_left == Some(true): compaction task left
    2974              :             // pending_task_left == Some(false): no compaction task left
    2975            0 :             let pending_task_left = if *can_compact {
    2976            0 :                 let has_pending_l0_compaction_task = timeline
    2977            0 :                     .compact(cancel, EnumSet::empty(), ctx)
    2978            0 :                     .instrument(info_span!("compact_timeline", %timeline_id))
    2979            0 :                     .await
    2980            0 :                     .inspect_err(|e| match e {
    2981            0 :                         timeline::CompactionError::ShuttingDown => (),
    2982            0 :                         timeline::CompactionError::Offload(_) => {
    2983            0 :                             // Failures to offload timelines do not trip the circuit breaker, because
    2984            0 :                             // they do not do lots of writes the way compaction itself does: it is cheap
    2985            0 :                             // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2986            0 :                         }
    2987            0 :                         timeline::CompactionError::Other(e) => {
    2988            0 :                             self.compaction_circuit_breaker
    2989            0 :                                 .lock()
    2990            0 :                                 .unwrap()
    2991            0 :                                 .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2992            0 :                         }
    2993            0 :                     })?;
    2994            0 :                 if has_pending_l0_compaction_task {
    2995            0 :                     Some(true)
    2996              :                 } else {
    2997            0 :                     let queue = {
    2998            0 :                         let guard = self.scheduled_compaction_tasks.lock().unwrap();
    2999            0 :                         guard.get(timeline_id).cloned()
    3000              :                     };
    3001            0 :                     if let Some(queue) = queue {
    3002            0 :                         let has_pending_tasks = queue
    3003            0 :                             .iteration(cancel, ctx, &self.gc_block, timeline)
    3004            0 :                             .await?;
    3005            0 :                         Some(has_pending_tasks)
    3006              :                     } else {
    3007            0 :                         Some(false)
    3008              :                     }
    3009              :                 }
    3010              :             } else {
    3011            0 :                 None
    3012              :             };
    3013            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    3014            0 :             if pending_task_left == Some(false) && *can_offload {
    3015            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3016            0 :                 match offload_timeline(self, timeline)
    3017            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    3018            0 :                     .await
    3019              :                 {
    3020              :                     Err(OffloadError::NotArchived) => {
    3021              :                         // Ignore this, we likely raced with unarchival
    3022            0 :                         Ok(())
    3023              :                     }
    3024            0 :                     other => other,
    3025            0 :                 }?;
    3026            0 :             }
    3027              :         }
    3028              : 
    3029            0 :         self.compaction_circuit_breaker
    3030            0 :             .lock()
    3031            0 :             .unwrap()
    3032            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3033            0 : 
    3034            0 :         Ok(has_pending_task)
    3035            0 :     }
    3036              : 
    3037              :     /// Cancel scheduled compaction tasks
    3038            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3039            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3040            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3041            0 :             q.cancel_scheduled();
    3042            0 :         }
    3043            0 :     }
    3044              : 
    3045            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3046            0 :         &self,
    3047            0 :         timeline_id: TimelineId,
    3048            0 :     ) -> Vec<CompactInfoResponse> {
    3049            0 :         let res = {
    3050            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3051            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3052              :         };
    3053            0 :         let Some((running, remaining)) = res else {
    3054            0 :             return Vec::new();
    3055              :         };
    3056            0 :         let mut result = Vec::new();
    3057            0 :         if let Some((id, running)) = running {
    3058            0 :             result.extend(running.into_compact_info_resp(id, true));
    3059            0 :         }
    3060            0 :         for (id, job) in remaining {
    3061            0 :             result.extend(job.into_compact_info_resp(id, false));
    3062            0 :         }
    3063            0 :         result
    3064            0 :     }
    3065              : 
    3066              :     /// Schedule a compaction task for a timeline.
    3067            0 :     pub(crate) async fn schedule_compaction(
    3068            0 :         &self,
    3069            0 :         timeline_id: TimelineId,
    3070            0 :         options: CompactOptions,
    3071            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3072            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3073            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3074            0 :         let q = guard
    3075            0 :             .entry(timeline_id)
    3076            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3077            0 :         q.schedule_manual_compaction(options, Some(tx));
    3078            0 :         Ok(rx)
    3079            0 :     }
    3080              : 
    3081              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    3082              :     // this happens during ingest: this background housekeeping is for freezing layers
    3083              :     // that are open but haven't been written to for some time.
    3084            0 :     async fn ingest_housekeeping(&self) {
    3085            0 :         // Scan through the hashmap and collect a list of all the timelines,
    3086            0 :         // while holding the lock. Then drop the lock and actually perform the
    3087            0 :         // compactions.  We don't want to block everything else while the
    3088            0 :         // compaction runs.
    3089            0 :         let timelines = {
    3090            0 :             self.timelines
    3091            0 :                 .lock()
    3092            0 :                 .unwrap()
    3093            0 :                 .values()
    3094            0 :                 .filter_map(|timeline| {
    3095            0 :                     if timeline.is_active() {
    3096            0 :                         Some(timeline.clone())
    3097              :                     } else {
    3098            0 :                         None
    3099              :                     }
    3100            0 :                 })
    3101            0 :                 .collect::<Vec<_>>()
    3102              :         };
    3103              : 
    3104            0 :         for timeline in &timelines {
    3105            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3106              :         }
    3107            0 :     }
    3108              : 
    3109            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3110            0 :         let timelines = self.timelines.lock().unwrap();
    3111            0 :         !timelines
    3112            0 :             .iter()
    3113            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3114            0 :     }
    3115              : 
    3116         1732 :     pub fn current_state(&self) -> TenantState {
    3117         1732 :         self.state.borrow().clone()
    3118         1732 :     }
    3119              : 
    3120          970 :     pub fn is_active(&self) -> bool {
    3121          970 :         self.current_state() == TenantState::Active
    3122          970 :     }
    3123              : 
    3124            0 :     pub fn generation(&self) -> Generation {
    3125            0 :         self.generation
    3126            0 :     }
    3127              : 
    3128            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3129            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3130            0 :     }
    3131              : 
    3132              :     /// Changes tenant status to active, unless shutdown was already requested.
    3133              :     ///
    3134              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3135              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3136            0 :     fn activate(
    3137            0 :         self: &Arc<Self>,
    3138            0 :         broker_client: BrokerClientChannel,
    3139            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3140            0 :         ctx: &RequestContext,
    3141            0 :     ) {
    3142            0 :         span::debug_assert_current_span_has_tenant_id();
    3143            0 : 
    3144            0 :         let mut activating = false;
    3145            0 :         self.state.send_modify(|current_state| {
    3146              :             use pageserver_api::models::ActivatingFrom;
    3147            0 :             match &*current_state {
    3148              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3149            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3150              :                 }
    3151            0 :                 TenantState::Attaching => {
    3152            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3153            0 :                 }
    3154            0 :             }
    3155            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3156            0 :             activating = true;
    3157            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3158            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3159            0 :         });
    3160            0 : 
    3161            0 :         if activating {
    3162            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3163            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3164            0 :             let timelines_to_activate = timelines_accessor
    3165            0 :                 .values()
    3166            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3167            0 : 
    3168            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3169            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3170            0 : 
    3171            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3172            0 :             // down when they notice that the tenant is inactive.
    3173            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3174            0 : 
    3175            0 :             let mut activated_timelines = 0;
    3176              : 
    3177            0 :             for timeline in timelines_to_activate {
    3178            0 :                 timeline.activate(
    3179            0 :                     self.clone(),
    3180            0 :                     broker_client.clone(),
    3181            0 :                     background_jobs_can_start,
    3182            0 :                     ctx,
    3183            0 :                 );
    3184            0 :                 activated_timelines += 1;
    3185            0 :             }
    3186              : 
    3187            0 :             self.state.send_modify(move |current_state| {
    3188            0 :                 assert!(
    3189            0 :                     matches!(current_state, TenantState::Activating(_)),
    3190            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3191              :                 );
    3192            0 :                 *current_state = TenantState::Active;
    3193            0 : 
    3194            0 :                 let elapsed = self.constructed_at.elapsed();
    3195            0 :                 let total_timelines = timelines_accessor.len();
    3196            0 : 
    3197            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3198            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3199            0 :                 info!(
    3200            0 :                     since_creation_millis = elapsed.as_millis(),
    3201            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3202            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3203            0 :                     activated_timelines,
    3204            0 :                     total_timelines,
    3205            0 :                     post_state = <&'static str>::from(&*current_state),
    3206            0 :                     "activation attempt finished"
    3207              :                 );
    3208              : 
    3209            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3210            0 :             });
    3211            0 :         }
    3212            0 :     }
    3213              : 
    3214              :     /// Shutdown the tenant and join all of the spawned tasks.
    3215              :     ///
    3216              :     /// The method caters for all use-cases:
    3217              :     /// - pageserver shutdown (freeze_and_flush == true)
    3218              :     /// - detach + ignore (freeze_and_flush == false)
    3219              :     ///
    3220              :     /// This will attempt to shutdown even if tenant is broken.
    3221              :     ///
    3222              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3223              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3224              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3225              :     /// the ongoing shutdown.
    3226            6 :     async fn shutdown(
    3227            6 :         &self,
    3228            6 :         shutdown_progress: completion::Barrier,
    3229            6 :         shutdown_mode: timeline::ShutdownMode,
    3230            6 :     ) -> Result<(), completion::Barrier> {
    3231            6 :         span::debug_assert_current_span_has_tenant_id();
    3232              : 
    3233              :         // Set tenant (and its timlines) to Stoppping state.
    3234              :         //
    3235              :         // Since we can only transition into Stopping state after activation is complete,
    3236              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3237              :         //
    3238              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3239              :         // 1. Lock out any new requests to the tenants.
    3240              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3241              :         // 3. Signal cancellation for other tenant background loops.
    3242              :         // 4. ???
    3243              :         //
    3244              :         // The waiting for the cancellation is not done uniformly.
    3245              :         // We certainly wait for WAL receivers to shut down.
    3246              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3247              :         // But the tenant background loops are joined-on in our caller.
    3248              :         // It's mesed up.
    3249              :         // we just ignore the failure to stop
    3250              : 
    3251              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3252              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3253              :         // is very slow.
    3254            6 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3255            0 :             self.cancel.cancel();
    3256            0 : 
    3257            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3258            0 :             // are children of ours, so their flush loops will have shut down already
    3259            0 :             timeline::ShutdownMode::Hard
    3260              :         } else {
    3261            6 :             shutdown_mode
    3262              :         };
    3263              : 
    3264            6 :         match self.set_stopping(shutdown_progress, false, false).await {
    3265            6 :             Ok(()) => {}
    3266            0 :             Err(SetStoppingError::Broken) => {
    3267            0 :                 // assume that this is acceptable
    3268            0 :             }
    3269            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3270            0 :                 // give caller the option to wait for this this shutdown
    3271            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3272            0 :                 return Err(other);
    3273              :             }
    3274              :         };
    3275              : 
    3276            6 :         let mut js = tokio::task::JoinSet::new();
    3277            6 :         {
    3278            6 :             let timelines = self.timelines.lock().unwrap();
    3279            6 :             timelines.values().for_each(|timeline| {
    3280            6 :                 let timeline = Arc::clone(timeline);
    3281            6 :                 let timeline_id = timeline.timeline_id;
    3282            6 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3283            6 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3284            6 :             });
    3285            6 :         }
    3286            6 :         {
    3287            6 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3288            6 :             timelines_offloaded.values().for_each(|timeline| {
    3289            0 :                 timeline.defuse_for_tenant_drop();
    3290            6 :             });
    3291            6 :         }
    3292            6 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3293            6 :         tracing::info!("Waiting for timelines...");
    3294           12 :         while let Some(res) = js.join_next().await {
    3295            0 :             match res {
    3296            6 :                 Ok(()) => {}
    3297            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3298            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3299            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3300              :             }
    3301              :         }
    3302              : 
    3303            6 :         if let ShutdownMode::Reload = shutdown_mode {
    3304            0 :             tracing::info!("Flushing deletion queue");
    3305            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3306            0 :                 match e {
    3307            0 :                     DeletionQueueError::ShuttingDown => {
    3308            0 :                         // This is the only error we expect for now. In the future, if more error
    3309            0 :                         // variants are added, we should handle them here.
    3310            0 :                     }
    3311              :                 }
    3312            0 :             }
    3313            6 :         }
    3314              : 
    3315              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3316              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3317            6 :         tracing::debug!("Cancelling CancellationToken");
    3318            6 :         self.cancel.cancel();
    3319            6 : 
    3320            6 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3321            6 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3322            6 :         //
    3323            6 :         // this will additionally shutdown and await all timeline tasks.
    3324            6 :         tracing::debug!("Waiting for tasks...");
    3325            6 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3326              : 
    3327            6 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3328            6 :             walredo_mgr.shutdown().await;
    3329            0 :         }
    3330              : 
    3331              :         // Wait for any in-flight operations to complete
    3332            6 :         self.gate.close().await;
    3333              : 
    3334            6 :         remove_tenant_metrics(&self.tenant_shard_id);
    3335            6 : 
    3336            6 :         Ok(())
    3337            6 :     }
    3338              : 
    3339              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3340              :     ///
    3341              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3342              :     ///
    3343              :     /// This function is not cancel-safe!
    3344              :     ///
    3345              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3346              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3347            6 :     async fn set_stopping(
    3348            6 :         &self,
    3349            6 :         progress: completion::Barrier,
    3350            6 :         _allow_transition_from_loading: bool,
    3351            6 :         allow_transition_from_attaching: bool,
    3352            6 :     ) -> Result<(), SetStoppingError> {
    3353            6 :         let mut rx = self.state.subscribe();
    3354            6 : 
    3355            6 :         // cannot stop before we're done activating, so wait out until we're done activating
    3356            6 :         rx.wait_for(|state| match state {
    3357            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3358              :             TenantState::Activating(_) | TenantState::Attaching => {
    3359            0 :                 info!(
    3360            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3361            0 :                     <&'static str>::from(state)
    3362              :                 );
    3363            0 :                 false
    3364              :             }
    3365            6 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3366            6 :         })
    3367            6 :         .await
    3368            6 :         .expect("cannot drop self.state while on a &self method");
    3369            6 : 
    3370            6 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3371            6 :         let mut err = None;
    3372            6 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3373              :             TenantState::Activating(_) => {
    3374            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3375              :             }
    3376              :             TenantState::Attaching => {
    3377            0 :                 if !allow_transition_from_attaching {
    3378            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3379            0 :                 };
    3380            0 :                 *current_state = TenantState::Stopping { progress };
    3381            0 :                 true
    3382              :             }
    3383              :             TenantState::Active => {
    3384              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3385              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3386              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3387            6 :                 *current_state = TenantState::Stopping { progress };
    3388            6 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3389            6 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3390            6 :                 true
    3391              :             }
    3392            0 :             TenantState::Broken { reason, .. } => {
    3393            0 :                 info!(
    3394            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3395              :                 );
    3396            0 :                 err = Some(SetStoppingError::Broken);
    3397            0 :                 false
    3398              :             }
    3399            0 :             TenantState::Stopping { progress } => {
    3400            0 :                 info!("Tenant is already in Stopping state");
    3401            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3402            0 :                 false
    3403              :             }
    3404            6 :         });
    3405            6 :         match (stopping, err) {
    3406            6 :             (true, None) => {} // continue
    3407            0 :             (false, Some(err)) => return Err(err),
    3408            0 :             (true, Some(_)) => unreachable!(
    3409            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3410            0 :             ),
    3411            0 :             (false, None) => unreachable!(
    3412            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3413            0 :             ),
    3414              :         }
    3415              : 
    3416            6 :         let timelines_accessor = self.timelines.lock().unwrap();
    3417            6 :         let not_broken_timelines = timelines_accessor
    3418            6 :             .values()
    3419            6 :             .filter(|timeline| !timeline.is_broken());
    3420           12 :         for timeline in not_broken_timelines {
    3421            6 :             timeline.set_state(TimelineState::Stopping);
    3422            6 :         }
    3423            6 :         Ok(())
    3424            6 :     }
    3425              : 
    3426              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3427              :     /// `remove_tenant_from_memory`
    3428              :     ///
    3429              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3430              :     ///
    3431              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3432            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3433            0 :         let mut rx = self.state.subscribe();
    3434            0 : 
    3435            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3436            0 :         // So, wait until it's done.
    3437            0 :         rx.wait_for(|state| match state {
    3438              :             TenantState::Activating(_) | TenantState::Attaching => {
    3439            0 :                 info!(
    3440            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3441            0 :                     <&'static str>::from(state)
    3442              :                 );
    3443            0 :                 false
    3444              :             }
    3445            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3446            0 :         })
    3447            0 :         .await
    3448            0 :         .expect("cannot drop self.state while on a &self method");
    3449            0 : 
    3450            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3451            0 :         self.set_broken_no_wait(reason)
    3452            0 :     }
    3453              : 
    3454            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3455            0 :         let reason = reason.to_string();
    3456            0 :         self.state.send_modify(|current_state| {
    3457            0 :             match *current_state {
    3458              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3459            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3460              :                 }
    3461              :                 TenantState::Active => {
    3462            0 :                     if cfg!(feature = "testing") {
    3463            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3464            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3465              :                     } else {
    3466            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3467              :                     }
    3468              :                 }
    3469              :                 TenantState::Broken { .. } => {
    3470            0 :                     warn!("Tenant is already in Broken state");
    3471              :                 }
    3472              :                 // This is the only "expected" path, any other path is a bug.
    3473              :                 TenantState::Stopping { .. } => {
    3474            0 :                     warn!(
    3475            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3476              :                         reason
    3477              :                     );
    3478            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3479              :                 }
    3480              :            }
    3481            0 :         });
    3482            0 :     }
    3483              : 
    3484            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3485            0 :         self.state.subscribe()
    3486            0 :     }
    3487              : 
    3488              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3489              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3490            0 :     pub(crate) fn activate_now(&self) {
    3491            0 :         self.activate_now_sem.add_permits(1);
    3492            0 :     }
    3493              : 
    3494            0 :     pub(crate) async fn wait_to_become_active(
    3495            0 :         &self,
    3496            0 :         timeout: Duration,
    3497            0 :     ) -> Result<(), GetActiveTenantError> {
    3498            0 :         let mut receiver = self.state.subscribe();
    3499              :         loop {
    3500            0 :             let current_state = receiver.borrow_and_update().clone();
    3501            0 :             match current_state {
    3502              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3503              :                     // in these states, there's a chance that we can reach ::Active
    3504            0 :                     self.activate_now();
    3505            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3506            0 :                         Ok(r) => {
    3507            0 :                             r.map_err(
    3508            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3509              :                                 // Tenant existed but was dropped: report it as non-existent
    3510            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3511            0 :                         )?
    3512              :                         }
    3513              :                         Err(TimeoutCancellableError::Cancelled) => {
    3514            0 :                             return Err(GetActiveTenantError::Cancelled);
    3515              :                         }
    3516              :                         Err(TimeoutCancellableError::Timeout) => {
    3517            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3518            0 :                                 latest_state: Some(self.current_state()),
    3519            0 :                                 wait_time: timeout,
    3520            0 :                             });
    3521              :                         }
    3522              :                     }
    3523              :                 }
    3524              :                 TenantState::Active { .. } => {
    3525            0 :                     return Ok(());
    3526              :                 }
    3527            0 :                 TenantState::Broken { reason, .. } => {
    3528            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3529            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3530            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3531              :                 }
    3532              :                 TenantState::Stopping { .. } => {
    3533              :                     // There's no chance the tenant can transition back into ::Active
    3534            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3535              :                 }
    3536              :             }
    3537              :         }
    3538            0 :     }
    3539              : 
    3540            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3541            0 :         self.tenant_conf.load().location.attach_mode
    3542            0 :     }
    3543              : 
    3544              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3545              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3546              :     /// rare external API calls, like a reconciliation at startup.
    3547            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3548            0 :         let conf = self.tenant_conf.load();
    3549              : 
    3550            0 :         let location_config_mode = match conf.location.attach_mode {
    3551            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3552            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3553            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3554              :         };
    3555              : 
    3556              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3557            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3558            0 : 
    3559            0 :         models::LocationConfig {
    3560            0 :             mode: location_config_mode,
    3561            0 :             generation: self.generation.into(),
    3562            0 :             secondary_conf: None,
    3563            0 :             shard_number: self.shard_identity.number.0,
    3564            0 :             shard_count: self.shard_identity.count.literal(),
    3565            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3566            0 :             tenant_conf: tenant_config,
    3567            0 :         }
    3568            0 :     }
    3569              : 
    3570            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3571            0 :         &self.tenant_shard_id
    3572            0 :     }
    3573              : 
    3574            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3575            0 :         self.shard_identity.stripe_size
    3576            0 :     }
    3577              : 
    3578            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3579            0 :         self.generation
    3580            0 :     }
    3581              : 
    3582              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3583              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3584              :     /// resetting this tenant to a valid state if we fail.
    3585            0 :     pub(crate) async fn split_prepare(
    3586            0 :         &self,
    3587            0 :         child_shards: &Vec<TenantShardId>,
    3588            0 :     ) -> anyhow::Result<()> {
    3589            0 :         let (timelines, offloaded) = {
    3590            0 :             let timelines = self.timelines.lock().unwrap();
    3591            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3592            0 :             (timelines.clone(), offloaded.clone())
    3593            0 :         };
    3594            0 :         let timelines_iter = timelines
    3595            0 :             .values()
    3596            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3597            0 :             .chain(
    3598            0 :                 offloaded
    3599            0 :                     .values()
    3600            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3601            0 :             );
    3602            0 :         for timeline in timelines_iter {
    3603              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3604              :             // to ensure that they do not start a split if currently in the process of doing these.
    3605              : 
    3606            0 :             let timeline_id = timeline.timeline_id();
    3607              : 
    3608            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3609              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3610              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3611              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3612            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3613            0 :                 timeline
    3614            0 :                     .remote_client
    3615            0 :                     .schedule_index_upload_for_file_changes()?;
    3616            0 :                 timeline.remote_client.wait_completion().await?;
    3617            0 :             }
    3618              : 
    3619            0 :             let remote_client = match timeline {
    3620            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3621            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3622            0 :                     let remote_client = self
    3623            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3624            0 :                     Arc::new(remote_client)
    3625              :                 }
    3626              :             };
    3627              : 
    3628              :             // Shut down the timeline's remote client: this means that the indices we write
    3629              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3630            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3631            0 :             remote_client.shutdown().await;
    3632              : 
    3633              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3634              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3635              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3636              :             // we use here really is the remotely persistent one).
    3637            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3638            0 :             let result = remote_client
    3639            0 :                 .download_index_file(&self.cancel)
    3640            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))
    3641            0 :                 .await?;
    3642            0 :             let index_part = match result {
    3643              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3644            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3645              :                 }
    3646            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3647              :             };
    3648              : 
    3649            0 :             for child_shard in child_shards {
    3650            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3651            0 :                 upload_index_part(
    3652            0 :                     &self.remote_storage,
    3653            0 :                     child_shard,
    3654            0 :                     &timeline_id,
    3655            0 :                     self.generation,
    3656            0 :                     &index_part,
    3657            0 :                     &self.cancel,
    3658            0 :                 )
    3659            0 :                 .await?;
    3660              :             }
    3661              :         }
    3662              : 
    3663            0 :         let tenant_manifest = self.build_tenant_manifest();
    3664            0 :         for child_shard in child_shards {
    3665            0 :             tracing::info!(
    3666            0 :                 "Uploading tenant manifest for child {}",
    3667            0 :                 child_shard.to_index()
    3668              :             );
    3669            0 :             upload_tenant_manifest(
    3670            0 :                 &self.remote_storage,
    3671            0 :                 child_shard,
    3672            0 :                 self.generation,
    3673            0 :                 &tenant_manifest,
    3674            0 :                 &self.cancel,
    3675            0 :             )
    3676            0 :             .await?;
    3677              :         }
    3678              : 
    3679            0 :         Ok(())
    3680            0 :     }
    3681              : 
    3682            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3683            0 :         let mut result = TopTenantShardItem {
    3684            0 :             id: self.tenant_shard_id,
    3685            0 :             resident_size: 0,
    3686            0 :             physical_size: 0,
    3687            0 :             max_logical_size: 0,
    3688            0 :         };
    3689              : 
    3690            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3691            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3692            0 : 
    3693            0 :             result.physical_size += timeline
    3694            0 :                 .remote_client
    3695            0 :                 .metrics
    3696            0 :                 .remote_physical_size_gauge
    3697            0 :                 .get();
    3698            0 :             result.max_logical_size = std::cmp::max(
    3699            0 :                 result.max_logical_size,
    3700            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3701            0 :             );
    3702            0 :         }
    3703              : 
    3704            0 :         result
    3705            0 :     }
    3706              : }
    3707              : 
    3708              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3709              : /// perform a topological sort, so that the parent of each timeline comes
    3710              : /// before the children.
    3711              : /// E extracts the ancestor from T
    3712              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3713          220 : fn tree_sort_timelines<T, E>(
    3714          220 :     timelines: HashMap<TimelineId, T>,
    3715          220 :     extractor: E,
    3716          220 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3717          220 : where
    3718          220 :     E: Fn(&T) -> Option<TimelineId>,
    3719          220 : {
    3720          220 :     let mut result = Vec::with_capacity(timelines.len());
    3721          220 : 
    3722          220 :     let mut now = Vec::with_capacity(timelines.len());
    3723          220 :     // (ancestor, children)
    3724          220 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3725          220 :         HashMap::with_capacity(timelines.len());
    3726              : 
    3727          226 :     for (timeline_id, value) in timelines {
    3728            6 :         if let Some(ancestor_id) = extractor(&value) {
    3729            2 :             let children = later.entry(ancestor_id).or_default();
    3730            2 :             children.push((timeline_id, value));
    3731            4 :         } else {
    3732            4 :             now.push((timeline_id, value));
    3733            4 :         }
    3734              :     }
    3735              : 
    3736          226 :     while let Some((timeline_id, metadata)) = now.pop() {
    3737            6 :         result.push((timeline_id, metadata));
    3738              :         // All children of this can be loaded now
    3739            6 :         if let Some(mut children) = later.remove(&timeline_id) {
    3740            2 :             now.append(&mut children);
    3741            4 :         }
    3742              :     }
    3743              : 
    3744              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3745          220 :     if !later.is_empty() {
    3746            0 :         for (missing_id, orphan_ids) in later {
    3747            0 :             for (orphan_id, _) in orphan_ids {
    3748            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3749              :             }
    3750              :         }
    3751            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3752          220 :     }
    3753          220 : 
    3754          220 :     Ok(result)
    3755          220 : }
    3756              : 
    3757              : enum ActivateTimelineArgs {
    3758              :     Yes {
    3759              :         broker_client: storage_broker::BrokerClientChannel,
    3760              :     },
    3761              :     No,
    3762              : }
    3763              : 
    3764              : impl Tenant {
    3765            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3766            0 :         self.tenant_conf.load().tenant_conf.clone()
    3767            0 :     }
    3768              : 
    3769            0 :     pub fn effective_config(&self) -> TenantConf {
    3770            0 :         self.tenant_specific_overrides()
    3771            0 :             .merge(self.conf.default_tenant_conf.clone())
    3772            0 :     }
    3773              : 
    3774            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3775            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3776            0 :         tenant_conf
    3777            0 :             .checkpoint_distance
    3778            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3779            0 :     }
    3780              : 
    3781            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3782            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3783            0 :         tenant_conf
    3784            0 :             .checkpoint_timeout
    3785            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3786            0 :     }
    3787              : 
    3788            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3789            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3790            0 :         tenant_conf
    3791            0 :             .compaction_target_size
    3792            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3793            0 :     }
    3794              : 
    3795            0 :     pub fn get_compaction_period(&self) -> Duration {
    3796            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3797            0 :         tenant_conf
    3798            0 :             .compaction_period
    3799            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3800            0 :     }
    3801              : 
    3802            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3803            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3804            0 :         tenant_conf
    3805            0 :             .compaction_threshold
    3806            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3807            0 :     }
    3808              : 
    3809            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3810            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3811            0 :         tenant_conf
    3812            0 :             .gc_horizon
    3813            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3814            0 :     }
    3815              : 
    3816            0 :     pub fn get_gc_period(&self) -> Duration {
    3817            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3818            0 :         tenant_conf
    3819            0 :             .gc_period
    3820            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3821            0 :     }
    3822              : 
    3823            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3824            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3825            0 :         tenant_conf
    3826            0 :             .image_creation_threshold
    3827            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3828            0 :     }
    3829              : 
    3830            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3831            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3832            0 :         tenant_conf
    3833            0 :             .pitr_interval
    3834            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3835            0 :     }
    3836              : 
    3837            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3838            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3839            0 :         tenant_conf
    3840            0 :             .min_resident_size_override
    3841            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3842            0 :     }
    3843              : 
    3844            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3845            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3846            0 :         let heatmap_period = tenant_conf
    3847            0 :             .heatmap_period
    3848            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3849            0 :         if heatmap_period.is_zero() {
    3850            0 :             None
    3851              :         } else {
    3852            0 :             Some(heatmap_period)
    3853              :         }
    3854            0 :     }
    3855              : 
    3856            4 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3857            4 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3858            4 :         tenant_conf
    3859            4 :             .lsn_lease_length
    3860            4 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3861            4 :     }
    3862              : 
    3863              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3864            2 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3865            2 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3866            2 : 
    3867            2 :         let mut timeline_manifests = timelines_offloaded
    3868            2 :             .iter()
    3869            2 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3870            2 :             .collect::<Vec<_>>();
    3871            2 :         // Sort the manifests so that our output is deterministic
    3872            2 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3873            2 : 
    3874            2 :         TenantManifest {
    3875            2 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3876            2 :             offloaded_timelines: timeline_manifests,
    3877            2 :         }
    3878            2 :     }
    3879              : 
    3880            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    3881            0 :         &self,
    3882            0 :         update: F,
    3883            0 :     ) -> anyhow::Result<TenantConfOpt> {
    3884            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3885            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3886            0 :         // this race is not possible if both request types come from the storage
    3887            0 :         // controller (as they should!) because an exclusive op lock is required
    3888            0 :         // on the storage controller side.
    3889            0 : 
    3890            0 :         self.tenant_conf
    3891            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    3892            0 :                 Ok(Arc::new(AttachedTenantConf {
    3893            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    3894            0 :                     location: attached_conf.location,
    3895            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    3896              :                 }))
    3897            0 :             })?;
    3898              : 
    3899            0 :         let updated = self.tenant_conf.load();
    3900            0 : 
    3901            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    3902            0 :         // Don't hold self.timelines.lock() during the notifies.
    3903            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3904            0 :         // mutexes in struct Timeline in the future.
    3905            0 :         let timelines = self.list_timelines();
    3906            0 :         for timeline in timelines {
    3907            0 :             timeline.tenant_conf_updated(&updated);
    3908            0 :         }
    3909              : 
    3910            0 :         Ok(updated.tenant_conf.clone())
    3911            0 :     }
    3912              : 
    3913            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3914            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3915            0 : 
    3916            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    3917            0 : 
    3918            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3919            0 :         // Don't hold self.timelines.lock() during the notifies.
    3920            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3921            0 :         // mutexes in struct Timeline in the future.
    3922            0 :         let timelines = self.list_timelines();
    3923            0 :         for timeline in timelines {
    3924            0 :             timeline.tenant_conf_updated(&new_conf);
    3925            0 :         }
    3926            0 :     }
    3927              : 
    3928          220 :     fn get_pagestream_throttle_config(
    3929          220 :         psconf: &'static PageServerConf,
    3930          220 :         overrides: &TenantConfOpt,
    3931          220 :     ) -> throttle::Config {
    3932          220 :         overrides
    3933          220 :             .timeline_get_throttle
    3934          220 :             .clone()
    3935          220 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3936          220 :     }
    3937              : 
    3938            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3939            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    3940            0 :         self.pagestream_throttle.reconfigure(conf)
    3941            0 :     }
    3942              : 
    3943              :     /// Helper function to create a new Timeline struct.
    3944              :     ///
    3945              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3946              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3947              :     /// map.
    3948              :     ///
    3949              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3950              :     /// and we might not have the ancestor present anymore which is fine for to be
    3951              :     /// deleted timelines.
    3952              :     #[allow(clippy::too_many_arguments)]
    3953          446 :     fn create_timeline_struct(
    3954          446 :         &self,
    3955          446 :         new_timeline_id: TimelineId,
    3956          446 :         new_metadata: &TimelineMetadata,
    3957          446 :         ancestor: Option<Arc<Timeline>>,
    3958          446 :         resources: TimelineResources,
    3959          446 :         cause: CreateTimelineCause,
    3960          446 :         create_idempotency: CreateTimelineIdempotency,
    3961          446 :     ) -> anyhow::Result<Arc<Timeline>> {
    3962          446 :         let state = match cause {
    3963              :             CreateTimelineCause::Load => {
    3964          446 :                 let ancestor_id = new_metadata.ancestor_timeline();
    3965          446 :                 anyhow::ensure!(
    3966          446 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    3967            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    3968              :                 );
    3969          446 :                 TimelineState::Loading
    3970              :             }
    3971            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    3972              :         };
    3973              : 
    3974          446 :         let pg_version = new_metadata.pg_version();
    3975          446 : 
    3976          446 :         let timeline = Timeline::new(
    3977          446 :             self.conf,
    3978          446 :             Arc::clone(&self.tenant_conf),
    3979          446 :             new_metadata,
    3980          446 :             ancestor,
    3981          446 :             new_timeline_id,
    3982          446 :             self.tenant_shard_id,
    3983          446 :             self.generation,
    3984          446 :             self.shard_identity,
    3985          446 :             self.walredo_mgr.clone(),
    3986          446 :             resources,
    3987          446 :             pg_version,
    3988          446 :             state,
    3989          446 :             self.attach_wal_lag_cooldown.clone(),
    3990          446 :             create_idempotency,
    3991          446 :             self.cancel.child_token(),
    3992          446 :         );
    3993          446 : 
    3994          446 :         Ok(timeline)
    3995          446 :     }
    3996              : 
    3997              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    3998              :     /// to ensure proper cleanup of background tasks and metrics.
    3999              :     //
    4000              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4001              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4002              :     #[allow(clippy::too_many_arguments)]
    4003          220 :     fn new(
    4004          220 :         state: TenantState,
    4005          220 :         conf: &'static PageServerConf,
    4006          220 :         attached_conf: AttachedTenantConf,
    4007          220 :         shard_identity: ShardIdentity,
    4008          220 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4009          220 :         tenant_shard_id: TenantShardId,
    4010          220 :         remote_storage: GenericRemoteStorage,
    4011          220 :         deletion_queue_client: DeletionQueueClient,
    4012          220 :         l0_flush_global_state: L0FlushGlobalState,
    4013          220 :     ) -> Tenant {
    4014          220 :         debug_assert!(
    4015          220 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4016              :         );
    4017              : 
    4018          220 :         let (state, mut rx) = watch::channel(state);
    4019          220 : 
    4020          220 :         tokio::spawn(async move {
    4021          220 :             // reflect tenant state in metrics:
    4022          220 :             // - global per tenant state: TENANT_STATE_METRIC
    4023          220 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4024          220 :             //
    4025          220 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4026          220 :             // alerting.
    4027          220 : 
    4028          220 :             let tid = tenant_shard_id.to_string();
    4029          220 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4030          220 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4031              : 
    4032          440 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4033          440 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4034          440 :             }
    4035              : 
    4036          220 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4037          220 : 
    4038          220 :             let is_broken = tuple.1;
    4039          220 :             let mut counted_broken = if is_broken {
    4040              :                 // add the id to the set right away, there should not be any updates on the channel
    4041              :                 // after before tenant is removed, if ever
    4042            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4043            0 :                 true
    4044              :             } else {
    4045          220 :                 false
    4046              :             };
    4047              : 
    4048              :             loop {
    4049          440 :                 let labels = &tuple.0;
    4050          440 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4051          440 :                 current.inc();
    4052          440 : 
    4053          440 :                 if rx.changed().await.is_err() {
    4054              :                     // tenant has been dropped
    4055           14 :                     current.dec();
    4056           14 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4057           14 :                     break;
    4058          220 :                 }
    4059          220 : 
    4060          220 :                 current.dec();
    4061          220 :                 tuple = inspect_state(&rx.borrow_and_update());
    4062          220 : 
    4063          220 :                 let is_broken = tuple.1;
    4064          220 :                 if is_broken && !counted_broken {
    4065            0 :                     counted_broken = true;
    4066            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4067            0 :                     // access
    4068            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4069          220 :                 }
    4070              :             }
    4071          220 :         });
    4072          220 : 
    4073          220 :         Tenant {
    4074          220 :             tenant_shard_id,
    4075          220 :             shard_identity,
    4076          220 :             generation: attached_conf.location.generation,
    4077          220 :             conf,
    4078          220 :             // using now here is good enough approximation to catch tenants with really long
    4079          220 :             // activation times.
    4080          220 :             constructed_at: Instant::now(),
    4081          220 :             timelines: Mutex::new(HashMap::new()),
    4082          220 :             timelines_creating: Mutex::new(HashSet::new()),
    4083          220 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4084          220 :             tenant_manifest_upload: Default::default(),
    4085          220 :             gc_cs: tokio::sync::Mutex::new(()),
    4086          220 :             walredo_mgr,
    4087          220 :             remote_storage,
    4088          220 :             deletion_queue_client,
    4089          220 :             state,
    4090          220 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4091          220 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4092          220 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4093          220 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4094          220 :                 format!("compaction-{tenant_shard_id}"),
    4095          220 :                 5,
    4096          220 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4097          220 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4098          220 :                 // use an extremely long backoff.
    4099          220 :                 Some(Duration::from_secs(3600 * 24)),
    4100          220 :             )),
    4101          220 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4102          220 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4103          220 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4104          220 :             cancel: CancellationToken::default(),
    4105          220 :             gate: Gate::default(),
    4106          220 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4107          220 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4108          220 :             )),
    4109          220 :             pagestream_throttle_metrics: Arc::new(
    4110          220 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4111          220 :             ),
    4112          220 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4113          220 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4114          220 :             gc_block: Default::default(),
    4115          220 :             l0_flush_global_state,
    4116          220 :         }
    4117          220 :     }
    4118              : 
    4119              :     /// Locate and load config
    4120            0 :     pub(super) fn load_tenant_config(
    4121            0 :         conf: &'static PageServerConf,
    4122            0 :         tenant_shard_id: &TenantShardId,
    4123            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4124            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4125            0 : 
    4126            0 :         info!("loading tenant configuration from {config_path}");
    4127              : 
    4128              :         // load and parse file
    4129            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4130            0 :             match e.kind() {
    4131              :                 std::io::ErrorKind::NotFound => {
    4132              :                     // The config should almost always exist for a tenant directory:
    4133              :                     //  - When attaching a tenant, the config is the first thing we write
    4134              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4135              :                     //    before deleting contents.
    4136              :                     //
    4137              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4138              :                     // between creating directory and writing config.  Callers should handle that as if the
    4139              :                     // directory didn't exist.
    4140              : 
    4141            0 :                     LoadConfigError::NotFound(config_path)
    4142              :                 }
    4143              :                 _ => {
    4144              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4145              :                     // that we cannot cleanly recover
    4146            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4147              :                 }
    4148              :             }
    4149            0 :         })?;
    4150              : 
    4151            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4152            0 :     }
    4153              : 
    4154              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4155              :     pub(super) async fn persist_tenant_config(
    4156              :         conf: &'static PageServerConf,
    4157              :         tenant_shard_id: &TenantShardId,
    4158              :         location_conf: &LocationConf,
    4159              :     ) -> std::io::Result<()> {
    4160              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4161              : 
    4162              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4163              :     }
    4164              : 
    4165              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4166              :     pub(super) async fn persist_tenant_config_at(
    4167              :         tenant_shard_id: &TenantShardId,
    4168              :         config_path: &Utf8Path,
    4169              :         location_conf: &LocationConf,
    4170              :     ) -> std::io::Result<()> {
    4171              :         debug!("persisting tenantconf to {config_path}");
    4172              : 
    4173              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4174              : #  It is read in case of pageserver restart.
    4175              : "#
    4176              :         .to_string();
    4177              : 
    4178            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4179            0 :             Err(std::io::Error::new(
    4180            0 :                 std::io::ErrorKind::Other,
    4181            0 :                 "tenant-config-before-write",
    4182            0 :             ))
    4183            0 :         });
    4184              : 
    4185              :         // Convert the config to a toml file.
    4186              :         conf_content +=
    4187              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4188              : 
    4189              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4190              : 
    4191              :         let conf_content = conf_content.into_bytes();
    4192              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4193              :     }
    4194              : 
    4195              :     //
    4196              :     // How garbage collection works:
    4197              :     //
    4198              :     //                    +--bar------------->
    4199              :     //                   /
    4200              :     //             +----+-----foo---------------->
    4201              :     //            /
    4202              :     // ----main--+-------------------------->
    4203              :     //                \
    4204              :     //                 +-----baz-------->
    4205              :     //
    4206              :     //
    4207              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4208              :     //    `gc_infos` are being refreshed
    4209              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4210              :     //    all the points where other timelines have been branched off.
    4211              :     //    We will refrain from removing page versions at those LSNs.
    4212              :     // 3. For each timeline, scan all layer files on the timeline.
    4213              :     //    Remove all files for which a newer file exists and which
    4214              :     //    don't cover any branch point LSNs.
    4215              :     //
    4216              :     // TODO:
    4217              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4218              :     //   don't need to keep that in the parent anymore. But currently
    4219              :     //   we do.
    4220            4 :     async fn gc_iteration_internal(
    4221            4 :         &self,
    4222            4 :         target_timeline_id: Option<TimelineId>,
    4223            4 :         horizon: u64,
    4224            4 :         pitr: Duration,
    4225            4 :         cancel: &CancellationToken,
    4226            4 :         ctx: &RequestContext,
    4227            4 :     ) -> Result<GcResult, GcError> {
    4228            4 :         let mut totals: GcResult = Default::default();
    4229            4 :         let now = Instant::now();
    4230              : 
    4231            4 :         let gc_timelines = self
    4232            4 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4233            4 :             .await?;
    4234              : 
    4235            4 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4236              : 
    4237              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4238            4 :         if !gc_timelines.is_empty() {
    4239            4 :             info!("{} timelines need GC", gc_timelines.len());
    4240              :         } else {
    4241            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4242              :         }
    4243              : 
    4244              :         // Perform GC for each timeline.
    4245              :         //
    4246              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4247              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4248              :         // with branch creation.
    4249              :         //
    4250              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4251              :         // creation task can run concurrently with timeline's GC iteration.
    4252            8 :         for timeline in gc_timelines {
    4253            4 :             if cancel.is_cancelled() {
    4254              :                 // We were requested to shut down. Stop and return with the progress we
    4255              :                 // made.
    4256            0 :                 break;
    4257            4 :             }
    4258            4 :             let result = match timeline.gc().await {
    4259              :                 Err(GcError::TimelineCancelled) => {
    4260            0 :                     if target_timeline_id.is_some() {
    4261              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4262            0 :                         return Err(GcError::TimelineCancelled);
    4263              :                     } else {
    4264              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4265              :                         // skip past this and proceed to try GC on other timelines.
    4266            0 :                         continue;
    4267              :                     }
    4268              :                 }
    4269            4 :                 r => r?,
    4270              :             };
    4271            4 :             totals += result;
    4272              :         }
    4273              : 
    4274            4 :         totals.elapsed = now.elapsed();
    4275            4 :         Ok(totals)
    4276            4 :     }
    4277              : 
    4278              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4279              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4280              :     /// [`Tenant::get_gc_horizon`].
    4281              :     ///
    4282              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4283            0 :     pub(crate) async fn refresh_gc_info(
    4284            0 :         &self,
    4285            0 :         cancel: &CancellationToken,
    4286            0 :         ctx: &RequestContext,
    4287            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4288            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4289            0 :         // might be that these configuration values get applied faster than what it was previously,
    4290            0 :         // since these were only read from the gc task.
    4291            0 :         let horizon = self.get_gc_horizon();
    4292            0 :         let pitr = self.get_pitr_interval();
    4293            0 : 
    4294            0 :         // refresh all timelines
    4295            0 :         let target_timeline_id = None;
    4296            0 : 
    4297            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4298            0 :             .await
    4299            0 :     }
    4300              : 
    4301              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4302              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4303              :     ///
    4304              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4305            0 :     fn initialize_gc_info(
    4306            0 :         &self,
    4307            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4308            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4309            0 :         restrict_to_timeline: Option<TimelineId>,
    4310            0 :     ) {
    4311            0 :         if restrict_to_timeline.is_none() {
    4312              :             // This function must be called before activation: after activation timeline create/delete operations
    4313              :             // might happen, and this function is not safe to run concurrently with those.
    4314            0 :             assert!(!self.is_active());
    4315            0 :         }
    4316              : 
    4317              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4318              :         // the branch point where it was created.
    4319            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4320            0 :             BTreeMap::new();
    4321            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4322            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4323            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4324            0 :                 ancestor_children.push((
    4325            0 :                     timeline_entry.get_ancestor_lsn(),
    4326            0 :                     *timeline_id,
    4327            0 :                     MaybeOffloaded::No,
    4328            0 :                 ));
    4329            0 :             }
    4330            0 :         });
    4331            0 :         timelines_offloaded
    4332            0 :             .iter()
    4333            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4334            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4335            0 :                     return;
    4336              :                 };
    4337            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4338            0 :                     return;
    4339              :                 };
    4340            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4341            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4342            0 :             });
    4343            0 : 
    4344            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4345            0 :         let horizon = self.get_gc_horizon();
    4346              : 
    4347              :         // Populate each timeline's GcInfo with information about its child branches
    4348            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4349            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4350              :         } else {
    4351            0 :             itertools::Either::Right(timelines.values())
    4352              :         };
    4353            0 :         for timeline in timelines_to_write {
    4354            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4355            0 :                 .remove(&timeline.timeline_id)
    4356            0 :                 .unwrap_or_default();
    4357            0 : 
    4358            0 :             branchpoints.sort_by_key(|b| b.0);
    4359            0 : 
    4360            0 :             let mut target = timeline.gc_info.write().unwrap();
    4361            0 : 
    4362            0 :             target.retain_lsns = branchpoints;
    4363            0 : 
    4364            0 :             let space_cutoff = timeline
    4365            0 :                 .get_last_record_lsn()
    4366            0 :                 .checked_sub(horizon)
    4367            0 :                 .unwrap_or(Lsn(0));
    4368            0 : 
    4369            0 :             target.cutoffs = GcCutoffs {
    4370            0 :                 space: space_cutoff,
    4371            0 :                 time: Lsn::INVALID,
    4372            0 :             };
    4373            0 :         }
    4374            0 :     }
    4375              : 
    4376            4 :     async fn refresh_gc_info_internal(
    4377            4 :         &self,
    4378            4 :         target_timeline_id: Option<TimelineId>,
    4379            4 :         horizon: u64,
    4380            4 :         pitr: Duration,
    4381            4 :         cancel: &CancellationToken,
    4382            4 :         ctx: &RequestContext,
    4383            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4384            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4385            4 :         // currently visible timelines.
    4386            4 :         let timelines = self
    4387            4 :             .timelines
    4388            4 :             .lock()
    4389            4 :             .unwrap()
    4390            4 :             .values()
    4391            4 :             .filter(|tl| match target_timeline_id.as_ref() {
    4392            4 :                 Some(target) => &tl.timeline_id == target,
    4393            0 :                 None => true,
    4394            4 :             })
    4395            4 :             .cloned()
    4396            4 :             .collect::<Vec<_>>();
    4397            4 : 
    4398            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4399              :             // We were to act on a particular timeline and it wasn't found
    4400            0 :             return Err(GcError::TimelineNotFound);
    4401            4 :         }
    4402            4 : 
    4403            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4404            4 :             HashMap::with_capacity(timelines.len());
    4405            4 : 
    4406            4 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4407            4 :         let now_ts_for_pitr_calc = SystemTime::now();
    4408            4 :         for timeline in timelines.iter() {
    4409            4 :             let cutoff = timeline
    4410            4 :                 .get_last_record_lsn()
    4411            4 :                 .checked_sub(horizon)
    4412            4 :                 .unwrap_or(Lsn(0));
    4413              : 
    4414            4 :             let cutoffs = timeline
    4415            4 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4416            4 :                 .await?;
    4417            4 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4418            4 :             assert!(old.is_none());
    4419              :         }
    4420              : 
    4421            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    4422            0 :             return Err(GcError::TenantCancelled);
    4423            4 :         }
    4424              : 
    4425              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4426              :         // because that will stall branch creation.
    4427            4 :         let gc_cs = self.gc_cs.lock().await;
    4428              : 
    4429              :         // Ok, we now know all the branch points.
    4430              :         // Update the GC information for each timeline.
    4431            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4432            8 :         for timeline in timelines {
    4433              :             // We filtered the timeline list above
    4434            4 :             if let Some(target_timeline_id) = target_timeline_id {
    4435            4 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4436            0 :             }
    4437              : 
    4438              :             {
    4439            4 :                 let mut target = timeline.gc_info.write().unwrap();
    4440            4 : 
    4441            4 :                 // Cull any expired leases
    4442            4 :                 let now = SystemTime::now();
    4443            6 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4444            4 : 
    4445            4 :                 timeline
    4446            4 :                     .metrics
    4447            4 :                     .valid_lsn_lease_count_gauge
    4448            4 :                     .set(target.leases.len() as u64);
    4449              : 
    4450              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4451            4 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4452            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4453            0 :                         target.within_ancestor_pitr =
    4454            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4455            0 :                     }
    4456            4 :                 }
    4457              : 
    4458              :                 // Update metrics that depend on GC state
    4459            4 :                 timeline
    4460            4 :                     .metrics
    4461            4 :                     .archival_size
    4462            4 :                     .set(if target.within_ancestor_pitr {
    4463            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4464              :                     } else {
    4465            4 :                         0
    4466              :                     });
    4467            4 :                 timeline.metrics.pitr_history_size.set(
    4468            4 :                     timeline
    4469            4 :                         .get_last_record_lsn()
    4470            4 :                         .checked_sub(target.cutoffs.time)
    4471            4 :                         .unwrap_or(Lsn(0))
    4472            4 :                         .0,
    4473            4 :                 );
    4474              : 
    4475              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4476              :                 // - this timeline was created while we were finding cutoffs
    4477              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4478            4 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4479            4 :                     let original_cutoffs = target.cutoffs.clone();
    4480            4 :                     // GC cutoffs should never go back
    4481            4 :                     target.cutoffs = GcCutoffs {
    4482            4 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4483            4 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4484            4 :                     }
    4485            0 :                 }
    4486              :             }
    4487              : 
    4488            4 :             gc_timelines.push(timeline);
    4489              :         }
    4490            4 :         drop(gc_cs);
    4491            4 :         Ok(gc_timelines)
    4492            4 :     }
    4493              : 
    4494              :     /// A substitute for `branch_timeline` for use in unit tests.
    4495              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4496              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4497              :     /// timeline background tasks are launched, except the flush loop.
    4498              :     #[cfg(test)]
    4499          232 :     async fn branch_timeline_test(
    4500          232 :         self: &Arc<Self>,
    4501          232 :         src_timeline: &Arc<Timeline>,
    4502          232 :         dst_id: TimelineId,
    4503          232 :         ancestor_lsn: Option<Lsn>,
    4504          232 :         ctx: &RequestContext,
    4505          232 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4506          232 :         let tl = self
    4507          232 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4508          232 :             .await?
    4509          228 :             .into_timeline_for_test();
    4510          228 :         tl.set_state(TimelineState::Active);
    4511          228 :         Ok(tl)
    4512          232 :     }
    4513              : 
    4514              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4515              :     #[cfg(test)]
    4516              :     #[allow(clippy::too_many_arguments)]
    4517            6 :     pub async fn branch_timeline_test_with_layers(
    4518            6 :         self: &Arc<Self>,
    4519            6 :         src_timeline: &Arc<Timeline>,
    4520            6 :         dst_id: TimelineId,
    4521            6 :         ancestor_lsn: Option<Lsn>,
    4522            6 :         ctx: &RequestContext,
    4523            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4524            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4525            6 :         end_lsn: Lsn,
    4526            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4527              :         use checks::check_valid_layermap;
    4528              :         use itertools::Itertools;
    4529              : 
    4530            6 :         let tline = self
    4531            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4532            6 :             .await?;
    4533            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4534            6 :             ancestor_lsn
    4535              :         } else {
    4536            0 :             tline.get_last_record_lsn()
    4537              :         };
    4538            6 :         assert!(end_lsn >= ancestor_lsn);
    4539            6 :         tline.force_advance_lsn(end_lsn);
    4540           12 :         for deltas in delta_layer_desc {
    4541            6 :             tline
    4542            6 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4543            6 :                 .await?;
    4544              :         }
    4545           10 :         for (lsn, images) in image_layer_desc {
    4546            4 :             tline
    4547            4 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4548            4 :                 .await?;
    4549              :         }
    4550            6 :         let layer_names = tline
    4551            6 :             .layers
    4552            6 :             .read()
    4553            6 :             .await
    4554            6 :             .layer_map()
    4555            6 :             .unwrap()
    4556            6 :             .iter_historic_layers()
    4557           10 :             .map(|layer| layer.layer_name())
    4558            6 :             .collect_vec();
    4559            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4560            0 :             bail!("invalid layermap: {err}");
    4561            6 :         }
    4562            6 :         Ok(tline)
    4563            6 :     }
    4564              : 
    4565              :     /// Branch an existing timeline.
    4566            0 :     async fn branch_timeline(
    4567            0 :         self: &Arc<Self>,
    4568            0 :         src_timeline: &Arc<Timeline>,
    4569            0 :         dst_id: TimelineId,
    4570            0 :         start_lsn: Option<Lsn>,
    4571            0 :         ctx: &RequestContext,
    4572            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4573            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4574            0 :             .await
    4575            0 :     }
    4576              : 
    4577          232 :     async fn branch_timeline_impl(
    4578          232 :         self: &Arc<Self>,
    4579          232 :         src_timeline: &Arc<Timeline>,
    4580          232 :         dst_id: TimelineId,
    4581          232 :         start_lsn: Option<Lsn>,
    4582          232 :         _ctx: &RequestContext,
    4583          232 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4584          232 :         let src_id = src_timeline.timeline_id;
    4585              : 
    4586              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4587              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4588              :         // valid while we are creating the branch.
    4589          232 :         let _gc_cs = self.gc_cs.lock().await;
    4590              : 
    4591              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4592          232 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4593            2 :             let lsn = src_timeline.get_last_record_lsn();
    4594            2 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4595            2 :             lsn
    4596          232 :         });
    4597              : 
    4598              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4599          232 :         let timeline_create_guard = match self
    4600          232 :             .start_creating_timeline(
    4601          232 :                 dst_id,
    4602          232 :                 CreateTimelineIdempotency::Branch {
    4603          232 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4604          232 :                     ancestor_start_lsn: start_lsn,
    4605          232 :                 },
    4606          232 :             )
    4607          232 :             .await?
    4608              :         {
    4609          232 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4610            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4611            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4612              :             }
    4613              :         };
    4614              : 
    4615              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4616              :         // horizon on the source timeline
    4617              :         //
    4618              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4619              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4620              :         // planned GC cutoff in 'gc_info' is normally larger than
    4621              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4622              :         // changed the GC settings for the tenant to make the PITR window
    4623              :         // larger, but some of the data was already removed by an earlier GC
    4624              :         // iteration.
    4625              : 
    4626              :         // check against last actual 'latest_gc_cutoff' first
    4627          232 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4628          232 :         src_timeline
    4629          232 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4630          232 :             .context(format!(
    4631          232 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4632          232 :                 *latest_gc_cutoff_lsn,
    4633          232 :             ))
    4634          232 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4635              : 
    4636              :         // and then the planned GC cutoff
    4637              :         {
    4638          228 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4639          228 :             let cutoff = gc_info.min_cutoff();
    4640          228 :             if start_lsn < cutoff {
    4641            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4642            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4643            0 :                 )));
    4644          228 :             }
    4645          228 :         }
    4646          228 : 
    4647          228 :         //
    4648          228 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4649          228 :         // so that GC cannot advance the GC cutoff until we are finished.
    4650          228 :         // Proceed with the branch creation.
    4651          228 :         //
    4652          228 : 
    4653          228 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4654          228 :         // the timeline was branched at the current end of the source timeline.
    4655          228 :         let RecordLsn {
    4656          228 :             last: src_last,
    4657          228 :             prev: src_prev,
    4658          228 :         } = src_timeline.get_last_record_rlsn();
    4659          228 :         let dst_prev = if src_last == start_lsn {
    4660          216 :             Some(src_prev)
    4661              :         } else {
    4662           12 :             None
    4663              :         };
    4664              : 
    4665              :         // Create the metadata file, noting the ancestor of the new timeline.
    4666              :         // There is initially no data in it, but all the read-calls know to look
    4667              :         // into the ancestor.
    4668          228 :         let metadata = TimelineMetadata::new(
    4669          228 :             start_lsn,
    4670          228 :             dst_prev,
    4671          228 :             Some(src_id),
    4672          228 :             start_lsn,
    4673          228 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4674          228 :             src_timeline.initdb_lsn,
    4675          228 :             src_timeline.pg_version,
    4676          228 :         );
    4677              : 
    4678          228 :         let uninitialized_timeline = self
    4679          228 :             .prepare_new_timeline(
    4680          228 :                 dst_id,
    4681          228 :                 &metadata,
    4682          228 :                 timeline_create_guard,
    4683          228 :                 start_lsn + 1,
    4684          228 :                 Some(Arc::clone(src_timeline)),
    4685          228 :             )
    4686          228 :             .await?;
    4687              : 
    4688          228 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4689              : 
    4690              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4691              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4692              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4693              :         // could get incorrect information and remove more layers, than needed.
    4694              :         // See also https://github.com/neondatabase/neon/issues/3865
    4695          228 :         new_timeline
    4696          228 :             .remote_client
    4697          228 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4698          228 :             .context("branch initial metadata upload")?;
    4699              : 
    4700              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4701              : 
    4702          228 :         Ok(CreateTimelineResult::Created(new_timeline))
    4703          232 :     }
    4704              : 
    4705              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4706              :     #[cfg(test)]
    4707              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4708              :     pub(crate) async fn bootstrap_timeline_test(
    4709              :         self: &Arc<Self>,
    4710              :         timeline_id: TimelineId,
    4711              :         pg_version: u32,
    4712              :         load_existing_initdb: Option<TimelineId>,
    4713              :         ctx: &RequestContext,
    4714              :     ) -> anyhow::Result<Arc<Timeline>> {
    4715              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4716              :             .await
    4717              :             .map_err(anyhow::Error::new)
    4718            2 :             .map(|r| r.into_timeline_for_test())
    4719              :     }
    4720              : 
    4721              :     /// Get exclusive access to the timeline ID for creation.
    4722              :     ///
    4723              :     /// Timeline-creating code paths must use this function before making changes
    4724              :     /// to in-memory or persistent state.
    4725              :     ///
    4726              :     /// The `state` parameter is a description of the timeline creation operation
    4727              :     /// we intend to perform.
    4728              :     /// If the timeline was already created in the meantime, we check whether this
    4729              :     /// request conflicts or is idempotent , based on `state`.
    4730          446 :     async fn start_creating_timeline(
    4731          446 :         self: &Arc<Self>,
    4732          446 :         new_timeline_id: TimelineId,
    4733          446 :         idempotency: CreateTimelineIdempotency,
    4734          446 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4735          446 :         let allow_offloaded = false;
    4736          446 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4737          444 :             Ok(create_guard) => {
    4738          444 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4739          444 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4740              :             }
    4741            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4742              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4743              :                 // Creation is in progress, we cannot create it again, and we cannot
    4744              :                 // check if this request matches the existing one, so caller must try
    4745              :                 // again later.
    4746            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4747              :             }
    4748            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4749              :             Err(TimelineExclusionError::AlreadyExists {
    4750            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4751            0 :                 ..
    4752            0 :             }) => {
    4753            0 :                 info!("timeline already exists but is offloaded");
    4754            0 :                 Err(CreateTimelineError::Conflict)
    4755              :             }
    4756              :             Err(TimelineExclusionError::AlreadyExists {
    4757            2 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4758            2 :                 arg,
    4759            2 :             }) => {
    4760            2 :                 {
    4761            2 :                     let existing = &existing.create_idempotency;
    4762            2 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4763            2 :                     debug!("timeline already exists");
    4764              : 
    4765            2 :                     match (existing, &arg) {
    4766              :                         // FailWithConflict => no idempotency check
    4767              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4768              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4769            2 :                             warn!("timeline already exists, failing request");
    4770            2 :                             return Err(CreateTimelineError::Conflict);
    4771              :                         }
    4772              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4773            0 :                         (x, y) if x == y => {
    4774            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4775              :                             // fallthrough
    4776              :                         }
    4777              :                         (_, _) => {
    4778            0 :                             warn!("idempotency conflict, failing request");
    4779            0 :                             return Err(CreateTimelineError::Conflict);
    4780              :                         }
    4781              :                     }
    4782              :                 }
    4783              : 
    4784            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4785              :             }
    4786              :         }
    4787          446 :     }
    4788              : 
    4789            0 :     async fn upload_initdb(
    4790            0 :         &self,
    4791            0 :         timelines_path: &Utf8PathBuf,
    4792            0 :         pgdata_path: &Utf8PathBuf,
    4793            0 :         timeline_id: &TimelineId,
    4794            0 :     ) -> anyhow::Result<()> {
    4795            0 :         let temp_path = timelines_path.join(format!(
    4796            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4797            0 :         ));
    4798            0 : 
    4799            0 :         scopeguard::defer! {
    4800            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4801            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4802            0 :             }
    4803            0 :         }
    4804              : 
    4805            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4806              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4807            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4808            0 :             warn!(
    4809            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4810              :             );
    4811            0 :         }
    4812              : 
    4813            0 :         pausable_failpoint!("before-initdb-upload");
    4814              : 
    4815            0 :         backoff::retry(
    4816            0 :             || async {
    4817            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4818            0 :                     &self.remote_storage,
    4819            0 :                     &self.tenant_shard_id.tenant_id,
    4820            0 :                     timeline_id,
    4821            0 :                     pgdata_zstd.try_clone().await?,
    4822            0 :                     tar_zst_size,
    4823            0 :                     &self.cancel,
    4824            0 :                 )
    4825            0 :                 .await
    4826            0 :             },
    4827            0 :             |_| false,
    4828            0 :             3,
    4829            0 :             u32::MAX,
    4830            0 :             "persist_initdb_tar_zst",
    4831            0 :             &self.cancel,
    4832            0 :         )
    4833            0 :         .await
    4834            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4835            0 :         .and_then(|x| x)
    4836            0 :     }
    4837              : 
    4838              :     /// - run initdb to init temporary instance and get bootstrap data
    4839              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4840            2 :     async fn bootstrap_timeline(
    4841            2 :         self: &Arc<Self>,
    4842            2 :         timeline_id: TimelineId,
    4843            2 :         pg_version: u32,
    4844            2 :         load_existing_initdb: Option<TimelineId>,
    4845            2 :         ctx: &RequestContext,
    4846            2 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4847            2 :         let timeline_create_guard = match self
    4848            2 :             .start_creating_timeline(
    4849            2 :                 timeline_id,
    4850            2 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4851            2 :             )
    4852            2 :             .await?
    4853              :         {
    4854            2 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4855            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4856            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4857              :             }
    4858              :         };
    4859              : 
    4860              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4861              :         // temporary directory for basebackup files for the given timeline.
    4862              : 
    4863            2 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4864            2 :         let pgdata_path = path_with_suffix_extension(
    4865            2 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4866            2 :             TEMP_FILE_SUFFIX,
    4867            2 :         );
    4868            2 : 
    4869            2 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4870            2 :         // we won't race with other creations or existent timelines with the same path.
    4871            2 :         if pgdata_path.exists() {
    4872            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4873            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4874            0 :             })?;
    4875            2 :         }
    4876              : 
    4877              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4878            2 :         scopeguard::defer! {
    4879            2 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4880            2 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4881            2 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4882            2 :             }
    4883            2 :         }
    4884            2 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4885            2 :             if existing_initdb_timeline_id != timeline_id {
    4886            0 :                 let source_path = &remote_initdb_archive_path(
    4887            0 :                     &self.tenant_shard_id.tenant_id,
    4888            0 :                     &existing_initdb_timeline_id,
    4889            0 :                 );
    4890            0 :                 let dest_path =
    4891            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4892            0 : 
    4893            0 :                 // if this fails, it will get retried by retried control plane requests
    4894            0 :                 self.remote_storage
    4895            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4896            0 :                     .await
    4897            0 :                     .context("copy initdb tar")?;
    4898            2 :             }
    4899            2 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4900            2 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4901            2 :                     self.conf,
    4902            2 :                     &self.remote_storage,
    4903            2 :                     &self.tenant_shard_id,
    4904            2 :                     &existing_initdb_timeline_id,
    4905            2 :                     &self.cancel,
    4906            2 :                 )
    4907            2 :                 .await
    4908            2 :                 .context("download initdb tar")?;
    4909              : 
    4910            2 :             scopeguard::defer! {
    4911            2 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4912            2 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4913            2 :                 }
    4914            2 :             }
    4915            2 : 
    4916            2 :             let buf_read =
    4917            2 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4918            2 :             extract_zst_tarball(&pgdata_path, buf_read)
    4919            2 :                 .await
    4920            2 :                 .context("extract initdb tar")?;
    4921              :         } else {
    4922              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4923            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4924            0 :                 .await
    4925            0 :                 .context("run initdb")?;
    4926              : 
    4927              :             // Upload the created data dir to S3
    4928            0 :             if self.tenant_shard_id().is_shard_zero() {
    4929            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4930            0 :                     .await?;
    4931            0 :             }
    4932              :         }
    4933            2 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4934            2 : 
    4935            2 :         // Import the contents of the data directory at the initial checkpoint
    4936            2 :         // LSN, and any WAL after that.
    4937            2 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4938            2 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4939            2 :         let new_metadata = TimelineMetadata::new(
    4940            2 :             Lsn(0),
    4941            2 :             None,
    4942            2 :             None,
    4943            2 :             Lsn(0),
    4944            2 :             pgdata_lsn,
    4945            2 :             pgdata_lsn,
    4946            2 :             pg_version,
    4947            2 :         );
    4948            2 :         let raw_timeline = self
    4949            2 :             .prepare_new_timeline(
    4950            2 :                 timeline_id,
    4951            2 :                 &new_metadata,
    4952            2 :                 timeline_create_guard,
    4953            2 :                 pgdata_lsn,
    4954            2 :                 None,
    4955            2 :             )
    4956            2 :             .await?;
    4957              : 
    4958            2 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4959            2 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4960              : 
    4961              :         // Flush the new layer files to disk, before we make the timeline as available to
    4962              :         // the outside world.
    4963              :         //
    4964              :         // Flush loop needs to be spawned in order to be able to flush.
    4965            2 :         unfinished_timeline.maybe_spawn_flush_loop();
    4966            2 : 
    4967            2 :         import_datadir::import_timeline_from_postgres_datadir(
    4968            2 :             unfinished_timeline,
    4969            2 :             &pgdata_path,
    4970            2 :             pgdata_lsn,
    4971            2 :             ctx,
    4972            2 :         )
    4973            2 :         .await
    4974            2 :         .with_context(|| {
    4975            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    4976            2 :         })?;
    4977              : 
    4978            2 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    4979            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    4980            0 :                 "failpoint before-checkpoint-new-timeline"
    4981            0 :             )))
    4982            2 :         });
    4983              : 
    4984            2 :         unfinished_timeline
    4985            2 :             .freeze_and_flush()
    4986            2 :             .await
    4987            2 :             .with_context(|| {
    4988            0 :                 format!(
    4989            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    4990            0 :                 )
    4991            2 :             })?;
    4992              : 
    4993              :         // All done!
    4994            2 :         let timeline = raw_timeline.finish_creation()?;
    4995              : 
    4996              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4997              : 
    4998            2 :         Ok(CreateTimelineResult::Created(timeline))
    4999            2 :     }
    5000              : 
    5001          440 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5002          440 :         RemoteTimelineClient::new(
    5003          440 :             self.remote_storage.clone(),
    5004          440 :             self.deletion_queue_client.clone(),
    5005          440 :             self.conf,
    5006          440 :             self.tenant_shard_id,
    5007          440 :             timeline_id,
    5008          440 :             self.generation,
    5009          440 :             &self.tenant_conf.load().location,
    5010          440 :         )
    5011          440 :     }
    5012              : 
    5013              :     /// Call this before constructing a timeline, to build its required structures
    5014          440 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5015          440 :         TimelineResources {
    5016          440 :             remote_client: self.build_timeline_remote_client(timeline_id),
    5017          440 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5018          440 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5019          440 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5020          440 :         }
    5021          440 :     }
    5022              : 
    5023              :     /// Creates intermediate timeline structure and its files.
    5024              :     ///
    5025              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5026              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5027              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5028          440 :     async fn prepare_new_timeline<'a>(
    5029          440 :         &'a self,
    5030          440 :         new_timeline_id: TimelineId,
    5031          440 :         new_metadata: &TimelineMetadata,
    5032          440 :         create_guard: TimelineCreateGuard,
    5033          440 :         start_lsn: Lsn,
    5034          440 :         ancestor: Option<Arc<Timeline>>,
    5035          440 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5036          440 :         let tenant_shard_id = self.tenant_shard_id;
    5037          440 : 
    5038          440 :         let resources = self.build_timeline_resources(new_timeline_id);
    5039          440 :         resources
    5040          440 :             .remote_client
    5041          440 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5042              : 
    5043          440 :         let timeline_struct = self
    5044          440 :             .create_timeline_struct(
    5045          440 :                 new_timeline_id,
    5046          440 :                 new_metadata,
    5047          440 :                 ancestor,
    5048          440 :                 resources,
    5049          440 :                 CreateTimelineCause::Load,
    5050          440 :                 create_guard.idempotency.clone(),
    5051          440 :             )
    5052          440 :             .context("Failed to create timeline data structure")?;
    5053              : 
    5054          440 :         timeline_struct.init_empty_layer_map(start_lsn);
    5055              : 
    5056          440 :         if let Err(e) = self
    5057          440 :             .create_timeline_files(&create_guard.timeline_path)
    5058          440 :             .await
    5059              :         {
    5060            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5061            0 :             cleanup_timeline_directory(create_guard);
    5062            0 :             return Err(e);
    5063          440 :         }
    5064          440 : 
    5065          440 :         debug!(
    5066            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5067              :         );
    5068              : 
    5069          440 :         Ok(UninitializedTimeline::new(
    5070          440 :             self,
    5071          440 :             new_timeline_id,
    5072          440 :             Some((timeline_struct, create_guard)),
    5073          440 :         ))
    5074          440 :     }
    5075              : 
    5076          440 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5077          440 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5078              : 
    5079          440 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5080            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5081          440 :         });
    5082              : 
    5083          440 :         Ok(())
    5084          440 :     }
    5085              : 
    5086              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5087              :     /// concurrent attempts to create the same timeline.
    5088              :     ///
    5089              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5090              :     /// offloaded timelines or not.
    5091          446 :     fn create_timeline_create_guard(
    5092          446 :         self: &Arc<Self>,
    5093          446 :         timeline_id: TimelineId,
    5094          446 :         idempotency: CreateTimelineIdempotency,
    5095          446 :         allow_offloaded: bool,
    5096          446 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5097          446 :         let tenant_shard_id = self.tenant_shard_id;
    5098          446 : 
    5099          446 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5100              : 
    5101          446 :         let create_guard = TimelineCreateGuard::new(
    5102          446 :             self,
    5103          446 :             timeline_id,
    5104          446 :             timeline_path.clone(),
    5105          446 :             idempotency,
    5106          446 :             allow_offloaded,
    5107          446 :         )?;
    5108              : 
    5109              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5110              :         // for creation.
    5111              :         // A timeline directory should never exist on disk already:
    5112              :         // - a previous failed creation would have cleaned up after itself
    5113              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5114              :         //
    5115              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5116              :         // this error may indicate a bug in cleanup on failed creations.
    5117          444 :         if timeline_path.exists() {
    5118            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5119            0 :                 "Timeline directory already exists! This is a bug."
    5120            0 :             )));
    5121          444 :         }
    5122          444 : 
    5123          444 :         Ok(create_guard)
    5124          446 :     }
    5125              : 
    5126              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5127              :     ///
    5128              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5129              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5130              :     pub async fn gather_size_inputs(
    5131              :         &self,
    5132              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5133              :         // (only if it is shorter than the real cutoff).
    5134              :         max_retention_period: Option<u64>,
    5135              :         cause: LogicalSizeCalculationCause,
    5136              :         cancel: &CancellationToken,
    5137              :         ctx: &RequestContext,
    5138              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5139              :         let logical_sizes_at_once = self
    5140              :             .conf
    5141              :             .concurrent_tenant_size_logical_size_queries
    5142              :             .inner();
    5143              : 
    5144              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5145              :         //
    5146              :         // But the only case where we need to run multiple of these at once is when we
    5147              :         // request a size for a tenant manually via API, while another background calculation
    5148              :         // is in progress (which is not a common case).
    5149              :         //
    5150              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5151              :         let mut shared_cache = tokio::select! {
    5152              :             locked = self.cached_logical_sizes.lock() => locked,
    5153              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5154              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5155              :         };
    5156              : 
    5157              :         size::gather_inputs(
    5158              :             self,
    5159              :             logical_sizes_at_once,
    5160              :             max_retention_period,
    5161              :             &mut shared_cache,
    5162              :             cause,
    5163              :             cancel,
    5164              :             ctx,
    5165              :         )
    5166              :         .await
    5167              :     }
    5168              : 
    5169              :     /// Calculate synthetic tenant size and cache the result.
    5170              :     /// This is periodically called by background worker.
    5171              :     /// result is cached in tenant struct
    5172              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5173              :     pub async fn calculate_synthetic_size(
    5174              :         &self,
    5175              :         cause: LogicalSizeCalculationCause,
    5176              :         cancel: &CancellationToken,
    5177              :         ctx: &RequestContext,
    5178              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5179              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5180              : 
    5181              :         let size = inputs.calculate();
    5182              : 
    5183              :         self.set_cached_synthetic_size(size);
    5184              : 
    5185              :         Ok(size)
    5186              :     }
    5187              : 
    5188              :     /// Cache given synthetic size and update the metric value
    5189            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5190            0 :         self.cached_synthetic_tenant_size
    5191            0 :             .store(size, Ordering::Relaxed);
    5192            0 : 
    5193            0 :         // Only shard zero should be calculating synthetic sizes
    5194            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5195              : 
    5196            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5197            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5198            0 :             .unwrap()
    5199            0 :             .set(size);
    5200            0 :     }
    5201              : 
    5202            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5203            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5204            0 :     }
    5205              : 
    5206              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5207              :     ///
    5208              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5209              :     /// from an external API handler.
    5210              :     ///
    5211              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5212              :     /// still bounded by tenant/timeline shutdown.
    5213              :     #[tracing::instrument(skip_all)]
    5214              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5215              :         let timelines = self.timelines.lock().unwrap().clone();
    5216              : 
    5217            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5218            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5219            0 :             timeline.freeze_and_flush().await?;
    5220            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5221            0 :             timeline.remote_client.wait_completion().await?;
    5222              : 
    5223            0 :             Ok(())
    5224            0 :         }
    5225              : 
    5226              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5227              :         // aborted when this function's future is cancelled: they should stay alive
    5228              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5229              :         // before Timeline shutdown completes.
    5230              :         let mut results = FuturesUnordered::new();
    5231              : 
    5232              :         for (_timeline_id, timeline) in timelines {
    5233              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5234              :             // means that if this function's future is cancelled, the Timeline shutdown
    5235              :             // will still wait for any I/O in here to complete.
    5236              :             let Ok(gate) = timeline.gate.enter() else {
    5237              :                 continue;
    5238              :             };
    5239            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5240              :             results.push(jh);
    5241              :         }
    5242              : 
    5243              :         while let Some(r) = results.next().await {
    5244              :             if let Err(e) = r {
    5245              :                 if !e.is_cancelled() && !e.is_panic() {
    5246              :                     tracing::error!("unexpected join error: {e:?}");
    5247              :                 }
    5248              :             }
    5249              :         }
    5250              : 
    5251              :         // The flushes we did above were just writes, but the Tenant might have had
    5252              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5253              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5254              :         // because it's typically a no-op.
    5255              :         match self.deletion_queue_client.flush_execute().await {
    5256              :             Ok(_) => {}
    5257              :             Err(DeletionQueueError::ShuttingDown) => {}
    5258              :         }
    5259              : 
    5260              :         Ok(())
    5261              :     }
    5262              : 
    5263            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5264            0 :         self.tenant_conf.load().tenant_conf.clone()
    5265            0 :     }
    5266              : 
    5267              :     /// How much local storage would this tenant like to have?  It can cope with
    5268              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5269              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5270              :     /// by keeping important things on local disk.
    5271              :     ///
    5272              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5273              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5274              :     /// actually use more than they report here.
    5275            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5276            0 :         let timelines = self.timelines.lock().unwrap();
    5277            0 : 
    5278            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5279            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5280            0 :         // of them is used actively enough to occupy space on disk.
    5281            0 :         timelines
    5282            0 :             .values()
    5283            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5284            0 :             .max()
    5285            0 :             .unwrap_or(0)
    5286            0 :     }
    5287              : 
    5288              :     /// Serialize and write the latest TenantManifest to remote storage.
    5289            2 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5290              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5291              :         // must be loaded while holding this lock. This makes it safe to call this function
    5292              :         // from anywhere without worrying about colliding updates.
    5293            2 :         let mut guard = tokio::select! {
    5294            2 :             g = self.tenant_manifest_upload.lock() => {
    5295            2 :                 g
    5296              :             },
    5297            2 :             _ = self.cancel.cancelled() => {
    5298            0 :                 return Err(TenantManifestError::Cancelled);
    5299              :             }
    5300              :         };
    5301              : 
    5302            2 :         let manifest = self.build_tenant_manifest();
    5303            2 :         if Some(&manifest) == (*guard).as_ref() {
    5304              :             // Optimisation: skip uploads that don't change anything.
    5305            0 :             return Ok(());
    5306            2 :         }
    5307            2 : 
    5308            2 :         upload_tenant_manifest(
    5309            2 :             &self.remote_storage,
    5310            2 :             &self.tenant_shard_id,
    5311            2 :             self.generation,
    5312            2 :             &manifest,
    5313            2 :             &self.cancel,
    5314            2 :         )
    5315            2 :         .await
    5316            2 :         .map_err(|e| {
    5317            0 :             if self.cancel.is_cancelled() {
    5318            0 :                 TenantManifestError::Cancelled
    5319              :             } else {
    5320            0 :                 TenantManifestError::RemoteStorage(e)
    5321              :             }
    5322            2 :         })?;
    5323              : 
    5324              :         // Store the successfully uploaded manifest, so that future callers can avoid
    5325              :         // re-uploading the same thing.
    5326            2 :         *guard = Some(manifest);
    5327            2 : 
    5328            2 :         Ok(())
    5329            2 :     }
    5330              : }
    5331              : 
    5332              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5333              : /// to get bootstrap data for timeline initialization.
    5334            0 : async fn run_initdb(
    5335            0 :     conf: &'static PageServerConf,
    5336            0 :     initdb_target_dir: &Utf8Path,
    5337            0 :     pg_version: u32,
    5338            0 :     cancel: &CancellationToken,
    5339            0 : ) -> Result<(), InitdbError> {
    5340            0 :     let initdb_bin_path = conf
    5341            0 :         .pg_bin_dir(pg_version)
    5342            0 :         .map_err(InitdbError::Other)?
    5343            0 :         .join("initdb");
    5344            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5345            0 :     info!(
    5346            0 :         "running {} in {}, libdir: {}",
    5347              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5348              :     );
    5349              : 
    5350            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    5351              : 
    5352            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5353            0 :         superuser: &conf.superuser,
    5354            0 :         locale: &conf.locale,
    5355            0 :         initdb_bin: &initdb_bin_path,
    5356            0 :         pg_version,
    5357            0 :         library_search_path: &initdb_lib_dir,
    5358            0 :         pgdata: initdb_target_dir,
    5359            0 :     })
    5360            0 :     .await
    5361            0 :     .map_err(InitdbError::Inner);
    5362            0 : 
    5363            0 :     // This isn't true cancellation support, see above. Still return an error to
    5364            0 :     // excercise the cancellation code path.
    5365            0 :     if cancel.is_cancelled() {
    5366            0 :         return Err(InitdbError::Cancelled);
    5367            0 :     }
    5368            0 : 
    5369            0 :     res
    5370            0 : }
    5371              : 
    5372              : /// Dump contents of a layer file to stdout.
    5373            0 : pub async fn dump_layerfile_from_path(
    5374            0 :     path: &Utf8Path,
    5375            0 :     verbose: bool,
    5376            0 :     ctx: &RequestContext,
    5377            0 : ) -> anyhow::Result<()> {
    5378              :     use std::os::unix::fs::FileExt;
    5379              : 
    5380              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5381              :     // file.
    5382            0 :     let file = File::open(path)?;
    5383            0 :     let mut header_buf = [0u8; 2];
    5384            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5385              : 
    5386            0 :     match u16::from_be_bytes(header_buf) {
    5387              :         crate::IMAGE_FILE_MAGIC => {
    5388            0 :             ImageLayer::new_for_path(path, file)?
    5389            0 :                 .dump(verbose, ctx)
    5390            0 :                 .await?
    5391              :         }
    5392              :         crate::DELTA_FILE_MAGIC => {
    5393            0 :             DeltaLayer::new_for_path(path, file)?
    5394            0 :                 .dump(verbose, ctx)
    5395            0 :                 .await?
    5396              :         }
    5397            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5398              :     }
    5399              : 
    5400            0 :     Ok(())
    5401            0 : }
    5402              : 
    5403              : #[cfg(test)]
    5404              : pub(crate) mod harness {
    5405              :     use bytes::{Bytes, BytesMut};
    5406              :     use once_cell::sync::OnceCell;
    5407              :     use pageserver_api::models::ShardParameters;
    5408              :     use pageserver_api::shard::ShardIndex;
    5409              :     use utils::logging;
    5410              : 
    5411              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5412              :     use crate::l0_flush::L0FlushConfig;
    5413              :     use crate::walredo::apply_neon;
    5414              :     use pageserver_api::key::Key;
    5415              :     use pageserver_api::record::NeonWalRecord;
    5416              : 
    5417              :     use super::*;
    5418              :     use hex_literal::hex;
    5419              :     use utils::id::TenantId;
    5420              : 
    5421              :     pub const TIMELINE_ID: TimelineId =
    5422              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5423              :     pub const NEW_TIMELINE_ID: TimelineId =
    5424              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5425              : 
    5426              :     /// Convenience function to create a page image with given string as the only content
    5427      5028755 :     pub fn test_img(s: &str) -> Bytes {
    5428      5028755 :         let mut buf = BytesMut::new();
    5429      5028755 :         buf.extend_from_slice(s.as_bytes());
    5430      5028755 :         buf.resize(64, 0);
    5431      5028755 : 
    5432      5028755 :         buf.freeze()
    5433      5028755 :     }
    5434              : 
    5435              :     impl From<TenantConf> for TenantConfOpt {
    5436          220 :         fn from(tenant_conf: TenantConf) -> Self {
    5437          220 :             Self {
    5438          220 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5439          220 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5440          220 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5441          220 :                 compaction_period: Some(tenant_conf.compaction_period),
    5442          220 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5443          220 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5444          220 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5445          220 :                 gc_period: Some(tenant_conf.gc_period),
    5446          220 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5447          220 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5448          220 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5449          220 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5450          220 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5451          220 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5452          220 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5453          220 :                 evictions_low_residence_duration_metric_threshold: Some(
    5454          220 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5455          220 :                 ),
    5456          220 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5457          220 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5458          220 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5459          220 :                 image_layer_creation_check_threshold: Some(
    5460          220 :                     tenant_conf.image_layer_creation_check_threshold,
    5461          220 :                 ),
    5462          220 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5463          220 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5464          220 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5465          220 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5466          220 :             }
    5467          220 :         }
    5468              :     }
    5469              : 
    5470              :     pub struct TenantHarness {
    5471              :         pub conf: &'static PageServerConf,
    5472              :         pub tenant_conf: TenantConf,
    5473              :         pub tenant_shard_id: TenantShardId,
    5474              :         pub generation: Generation,
    5475              :         pub shard: ShardIndex,
    5476              :         pub remote_storage: GenericRemoteStorage,
    5477              :         pub remote_fs_dir: Utf8PathBuf,
    5478              :         pub deletion_queue: MockDeletionQueue,
    5479              :     }
    5480              : 
    5481              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5482              : 
    5483          236 :     pub(crate) fn setup_logging() {
    5484          236 :         LOG_HANDLE.get_or_init(|| {
    5485          224 :             logging::init(
    5486          224 :                 logging::LogFormat::Test,
    5487          224 :                 // enable it in case the tests exercise code paths that use
    5488          224 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5489          224 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5490          224 :                 logging::Output::Stdout,
    5491          224 :             )
    5492          224 :             .expect("Failed to init test logging")
    5493          236 :         });
    5494          236 :     }
    5495              : 
    5496              :     impl TenantHarness {
    5497          220 :         pub async fn create_custom(
    5498          220 :             test_name: &'static str,
    5499          220 :             tenant_conf: TenantConf,
    5500          220 :             tenant_id: TenantId,
    5501          220 :             shard_identity: ShardIdentity,
    5502          220 :             generation: Generation,
    5503          220 :         ) -> anyhow::Result<Self> {
    5504          220 :             setup_logging();
    5505          220 : 
    5506          220 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5507          220 :             let _ = fs::remove_dir_all(&repo_dir);
    5508          220 :             fs::create_dir_all(&repo_dir)?;
    5509              : 
    5510          220 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5511          220 :             // Make a static copy of the config. This can never be free'd, but that's
    5512          220 :             // OK in a test.
    5513          220 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5514          220 : 
    5515          220 :             let shard = shard_identity.shard_index();
    5516          220 :             let tenant_shard_id = TenantShardId {
    5517          220 :                 tenant_id,
    5518          220 :                 shard_number: shard.shard_number,
    5519          220 :                 shard_count: shard.shard_count,
    5520          220 :             };
    5521          220 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5522          220 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5523              : 
    5524              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5525          220 :             let remote_fs_dir = conf.workdir.join("localfs");
    5526          220 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5527          220 :             let config = RemoteStorageConfig {
    5528          220 :                 storage: RemoteStorageKind::LocalFs {
    5529          220 :                     local_path: remote_fs_dir.clone(),
    5530          220 :                 },
    5531          220 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5532          220 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5533          220 :             };
    5534          220 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5535          220 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5536          220 : 
    5537          220 :             Ok(Self {
    5538          220 :                 conf,
    5539          220 :                 tenant_conf,
    5540          220 :                 tenant_shard_id,
    5541          220 :                 generation,
    5542          220 :                 shard,
    5543          220 :                 remote_storage,
    5544          220 :                 remote_fs_dir,
    5545          220 :                 deletion_queue,
    5546          220 :             })
    5547          220 :         }
    5548              : 
    5549          208 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5550          208 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5551          208 :             // The tests perform them manually if needed.
    5552          208 :             let tenant_conf = TenantConf {
    5553          208 :                 gc_period: Duration::ZERO,
    5554          208 :                 compaction_period: Duration::ZERO,
    5555          208 :                 ..TenantConf::default()
    5556          208 :             };
    5557          208 :             let tenant_id = TenantId::generate();
    5558          208 :             let shard = ShardIdentity::unsharded();
    5559          208 :             Self::create_custom(
    5560          208 :                 test_name,
    5561          208 :                 tenant_conf,
    5562          208 :                 tenant_id,
    5563          208 :                 shard,
    5564          208 :                 Generation::new(0xdeadbeef),
    5565          208 :             )
    5566          208 :             .await
    5567          208 :         }
    5568              : 
    5569           20 :         pub fn span(&self) -> tracing::Span {
    5570           20 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5571           20 :         }
    5572              : 
    5573          220 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5574          220 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5575          220 :             (
    5576          220 :                 self.do_try_load(&ctx)
    5577          220 :                     .await
    5578          220 :                     .expect("failed to load test tenant"),
    5579          220 :                 ctx,
    5580          220 :             )
    5581          220 :         }
    5582              : 
    5583              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5584              :         pub(crate) async fn do_try_load(
    5585              :             &self,
    5586              :             ctx: &RequestContext,
    5587              :         ) -> anyhow::Result<Arc<Tenant>> {
    5588              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5589              : 
    5590              :             let tenant = Arc::new(Tenant::new(
    5591              :                 TenantState::Attaching,
    5592              :                 self.conf,
    5593              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5594              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5595              :                     self.generation,
    5596              :                     &ShardParameters::default(),
    5597              :                 ))
    5598              :                 .unwrap(),
    5599              :                 // This is a legacy/test code path: sharding isn't supported here.
    5600              :                 ShardIdentity::unsharded(),
    5601              :                 Some(walredo_mgr),
    5602              :                 self.tenant_shard_id,
    5603              :                 self.remote_storage.clone(),
    5604              :                 self.deletion_queue.new_client(),
    5605              :                 // TODO: ideally we should run all unit tests with both configs
    5606              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5607              :             ));
    5608              : 
    5609              :             let preload = tenant
    5610              :                 .preload(&self.remote_storage, CancellationToken::new())
    5611              :                 .await?;
    5612              :             tenant.attach(Some(preload), ctx).await?;
    5613              : 
    5614              :             tenant.state.send_replace(TenantState::Active);
    5615              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5616              :                 timeline.set_state(TimelineState::Active);
    5617              :             }
    5618              :             Ok(tenant)
    5619              :         }
    5620              : 
    5621            2 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5622            2 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5623            2 :         }
    5624              :     }
    5625              : 
    5626              :     // Mock WAL redo manager that doesn't do much
    5627              :     pub(crate) struct TestRedoManager;
    5628              : 
    5629              :     impl TestRedoManager {
    5630              :         /// # Cancel-Safety
    5631              :         ///
    5632              :         /// This method is cancellation-safe.
    5633          818 :         pub async fn request_redo(
    5634          818 :             &self,
    5635          818 :             key: Key,
    5636          818 :             lsn: Lsn,
    5637          818 :             base_img: Option<(Lsn, Bytes)>,
    5638          818 :             records: Vec<(Lsn, NeonWalRecord)>,
    5639          818 :             _pg_version: u32,
    5640          818 :         ) -> Result<Bytes, walredo::Error> {
    5641         1196 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5642          818 :             if records_neon {
    5643              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5644          818 :                 let mut page = match (base_img, records.first()) {
    5645          752 :                     (Some((_lsn, img)), _) => {
    5646          752 :                         let mut page = BytesMut::new();
    5647          752 :                         page.extend_from_slice(&img);
    5648          752 :                         page
    5649              :                     }
    5650           66 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5651              :                     _ => {
    5652            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5653              :                     }
    5654              :                 };
    5655              : 
    5656         2014 :                 for (record_lsn, record) in records {
    5657         1196 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5658              :                 }
    5659          818 :                 Ok(page.freeze())
    5660              :             } else {
    5661              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5662            0 :                 let s = format!(
    5663            0 :                     "redo for {} to get to {}, with {} and {} records",
    5664            0 :                     key,
    5665            0 :                     lsn,
    5666            0 :                     if base_img.is_some() {
    5667            0 :                         "base image"
    5668              :                     } else {
    5669            0 :                         "no base image"
    5670              :                     },
    5671            0 :                     records.len()
    5672            0 :                 );
    5673            0 :                 println!("{s}");
    5674            0 : 
    5675            0 :                 Ok(test_img(&s))
    5676              :             }
    5677          818 :         }
    5678              :     }
    5679              : }
    5680              : 
    5681              : #[cfg(test)]
    5682              : mod tests {
    5683              :     use std::collections::{BTreeMap, BTreeSet};
    5684              : 
    5685              :     use super::*;
    5686              :     use crate::keyspace::KeySpaceAccum;
    5687              :     use crate::tenant::harness::*;
    5688              :     use crate::tenant::timeline::CompactFlags;
    5689              :     use crate::DEFAULT_PG_VERSION;
    5690              :     use bytes::{Bytes, BytesMut};
    5691              :     use hex_literal::hex;
    5692              :     use itertools::Itertools;
    5693              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5694              :     use pageserver_api::keyspace::KeySpace;
    5695              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5696              :     use pageserver_api::value::Value;
    5697              :     use pageserver_compaction::helpers::overlaps_with;
    5698              :     use rand::{thread_rng, Rng};
    5699              :     use storage_layer::PersistentLayerKey;
    5700              :     use tests::storage_layer::ValuesReconstructState;
    5701              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5702              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5703              :     use utils::id::TenantId;
    5704              : 
    5705              :     #[cfg(feature = "testing")]
    5706              :     use models::CompactLsnRange;
    5707              :     #[cfg(feature = "testing")]
    5708              :     use pageserver_api::record::NeonWalRecord;
    5709              :     #[cfg(feature = "testing")]
    5710              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5711              :     #[cfg(feature = "testing")]
    5712              :     use timeline::GcInfo;
    5713              : 
    5714              :     static TEST_KEY: Lazy<Key> =
    5715           18 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5716              : 
    5717              :     #[tokio::test]
    5718            2 :     async fn test_basic() -> anyhow::Result<()> {
    5719            2 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5720            2 :         let tline = tenant
    5721            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5722            2 :             .await?;
    5723            2 : 
    5724            2 :         let mut writer = tline.writer().await;
    5725            2 :         writer
    5726            2 :             .put(
    5727            2 :                 *TEST_KEY,
    5728            2 :                 Lsn(0x10),
    5729            2 :                 &Value::Image(test_img("foo at 0x10")),
    5730            2 :                 &ctx,
    5731            2 :             )
    5732            2 :             .await?;
    5733            2 :         writer.finish_write(Lsn(0x10));
    5734            2 :         drop(writer);
    5735            2 : 
    5736            2 :         let mut writer = tline.writer().await;
    5737            2 :         writer
    5738            2 :             .put(
    5739            2 :                 *TEST_KEY,
    5740            2 :                 Lsn(0x20),
    5741            2 :                 &Value::Image(test_img("foo at 0x20")),
    5742            2 :                 &ctx,
    5743            2 :             )
    5744            2 :             .await?;
    5745            2 :         writer.finish_write(Lsn(0x20));
    5746            2 :         drop(writer);
    5747            2 : 
    5748            2 :         assert_eq!(
    5749            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5750            2 :             test_img("foo at 0x10")
    5751            2 :         );
    5752            2 :         assert_eq!(
    5753            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5754            2 :             test_img("foo at 0x10")
    5755            2 :         );
    5756            2 :         assert_eq!(
    5757            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5758            2 :             test_img("foo at 0x20")
    5759            2 :         );
    5760            2 : 
    5761            2 :         Ok(())
    5762            2 :     }
    5763              : 
    5764              :     #[tokio::test]
    5765            2 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5766            2 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5767            2 :             .await?
    5768            2 :             .load()
    5769            2 :             .await;
    5770            2 :         let _ = tenant
    5771            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5772            2 :             .await?;
    5773            2 : 
    5774            2 :         match tenant
    5775            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5776            2 :             .await
    5777            2 :         {
    5778            2 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5779            2 :             Err(e) => assert_eq!(
    5780            2 :                 e.to_string(),
    5781            2 :                 "timeline already exists with different parameters".to_string()
    5782            2 :             ),
    5783            2 :         }
    5784            2 : 
    5785            2 :         Ok(())
    5786            2 :     }
    5787              : 
    5788              :     /// Convenience function to create a page image with given string as the only content
    5789           10 :     pub fn test_value(s: &str) -> Value {
    5790           10 :         let mut buf = BytesMut::new();
    5791           10 :         buf.extend_from_slice(s.as_bytes());
    5792           10 :         Value::Image(buf.freeze())
    5793           10 :     }
    5794              : 
    5795              :     ///
    5796              :     /// Test branch creation
    5797              :     ///
    5798              :     #[tokio::test]
    5799            2 :     async fn test_branch() -> anyhow::Result<()> {
    5800            2 :         use std::str::from_utf8;
    5801            2 : 
    5802            2 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5803            2 :         let tline = tenant
    5804            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5805            2 :             .await?;
    5806            2 :         let mut writer = tline.writer().await;
    5807            2 : 
    5808            2 :         #[allow(non_snake_case)]
    5809            2 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5810            2 :         #[allow(non_snake_case)]
    5811            2 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5812            2 : 
    5813            2 :         // Insert a value on the timeline
    5814            2 :         writer
    5815            2 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5816            2 :             .await?;
    5817            2 :         writer
    5818            2 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5819            2 :             .await?;
    5820            2 :         writer.finish_write(Lsn(0x20));
    5821            2 : 
    5822            2 :         writer
    5823            2 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5824            2 :             .await?;
    5825            2 :         writer.finish_write(Lsn(0x30));
    5826            2 :         writer
    5827            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5828            2 :             .await?;
    5829            2 :         writer.finish_write(Lsn(0x40));
    5830            2 : 
    5831            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5832            2 : 
    5833            2 :         // Branch the history, modify relation differently on the new timeline
    5834            2 :         tenant
    5835            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5836            2 :             .await?;
    5837            2 :         let newtline = tenant
    5838            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5839            2 :             .expect("Should have a local timeline");
    5840            2 :         let mut new_writer = newtline.writer().await;
    5841            2 :         new_writer
    5842            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5843            2 :             .await?;
    5844            2 :         new_writer.finish_write(Lsn(0x40));
    5845            2 : 
    5846            2 :         // Check page contents on both branches
    5847            2 :         assert_eq!(
    5848            2 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5849            2 :             "foo at 0x40"
    5850            2 :         );
    5851            2 :         assert_eq!(
    5852            2 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5853            2 :             "bar at 0x40"
    5854            2 :         );
    5855            2 :         assert_eq!(
    5856            2 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5857            2 :             "foobar at 0x20"
    5858            2 :         );
    5859            2 : 
    5860            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5861            2 : 
    5862            2 :         Ok(())
    5863            2 :     }
    5864              : 
    5865           20 :     async fn make_some_layers(
    5866           20 :         tline: &Timeline,
    5867           20 :         start_lsn: Lsn,
    5868           20 :         ctx: &RequestContext,
    5869           20 :     ) -> anyhow::Result<()> {
    5870           20 :         let mut lsn = start_lsn;
    5871              :         {
    5872           20 :             let mut writer = tline.writer().await;
    5873              :             // Create a relation on the timeline
    5874           20 :             writer
    5875           20 :                 .put(
    5876           20 :                     *TEST_KEY,
    5877           20 :                     lsn,
    5878           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5879           20 :                     ctx,
    5880           20 :                 )
    5881           20 :                 .await?;
    5882           20 :             writer.finish_write(lsn);
    5883           20 :             lsn += 0x10;
    5884           20 :             writer
    5885           20 :                 .put(
    5886           20 :                     *TEST_KEY,
    5887           20 :                     lsn,
    5888           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5889           20 :                     ctx,
    5890           20 :                 )
    5891           20 :                 .await?;
    5892           20 :             writer.finish_write(lsn);
    5893           20 :             lsn += 0x10;
    5894           20 :         }
    5895           20 :         tline.freeze_and_flush().await?;
    5896              :         {
    5897           20 :             let mut writer = tline.writer().await;
    5898           20 :             writer
    5899           20 :                 .put(
    5900           20 :                     *TEST_KEY,
    5901           20 :                     lsn,
    5902           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5903           20 :                     ctx,
    5904           20 :                 )
    5905           20 :                 .await?;
    5906           20 :             writer.finish_write(lsn);
    5907           20 :             lsn += 0x10;
    5908           20 :             writer
    5909           20 :                 .put(
    5910           20 :                     *TEST_KEY,
    5911           20 :                     lsn,
    5912           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5913           20 :                     ctx,
    5914           20 :                 )
    5915           20 :                 .await?;
    5916           20 :             writer.finish_write(lsn);
    5917           20 :         }
    5918           20 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5919           20 :     }
    5920              : 
    5921              :     #[tokio::test(start_paused = true)]
    5922            2 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5923            2 :         let (tenant, ctx) =
    5924            2 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5925            2 :                 .await?
    5926            2 :                 .load()
    5927            2 :                 .await;
    5928            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5929            2 :         // initial transition into AttachedSingle.
    5930            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5931            2 :         tokio::time::resume();
    5932            2 :         let tline = tenant
    5933            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5934            2 :             .await?;
    5935            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5936            2 : 
    5937            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5938            2 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5939            2 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5940            2 :         // below should fail.
    5941            2 :         tenant
    5942            2 :             .gc_iteration(
    5943            2 :                 Some(TIMELINE_ID),
    5944            2 :                 0x10,
    5945            2 :                 Duration::ZERO,
    5946            2 :                 &CancellationToken::new(),
    5947            2 :                 &ctx,
    5948            2 :             )
    5949            2 :             .await?;
    5950            2 : 
    5951            2 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5952            2 :         match tenant
    5953            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5954            2 :             .await
    5955            2 :         {
    5956            2 :             Ok(_) => panic!("branching should have failed"),
    5957            2 :             Err(err) => {
    5958            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5959            2 :                     panic!("wrong error type")
    5960            2 :                 };
    5961            2 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    5962            2 :                 assert!(err
    5963            2 :                     .source()
    5964            2 :                     .unwrap()
    5965            2 :                     .to_string()
    5966            2 :                     .contains("we might've already garbage collected needed data"))
    5967            2 :             }
    5968            2 :         }
    5969            2 : 
    5970            2 :         Ok(())
    5971            2 :     }
    5972              : 
    5973              :     #[tokio::test]
    5974            2 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    5975            2 :         let (tenant, ctx) =
    5976            2 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    5977            2 :                 .await?
    5978            2 :                 .load()
    5979            2 :                 .await;
    5980            2 : 
    5981            2 :         let tline = tenant
    5982            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    5983            2 :             .await?;
    5984            2 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    5985            2 :         match tenant
    5986            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5987            2 :             .await
    5988            2 :         {
    5989            2 :             Ok(_) => panic!("branching should have failed"),
    5990            2 :             Err(err) => {
    5991            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5992            2 :                     panic!("wrong error type");
    5993            2 :                 };
    5994            2 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    5995            2 :                 assert!(&err
    5996            2 :                     .source()
    5997            2 :                     .unwrap()
    5998            2 :                     .to_string()
    5999            2 :                     .contains("is earlier than latest GC cutoff"));
    6000            2 :             }
    6001            2 :         }
    6002            2 : 
    6003            2 :         Ok(())
    6004            2 :     }
    6005              : 
    6006              :     /*
    6007              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6008              :     // remove the old value, we'd need to work a little harder
    6009              :     #[tokio::test]
    6010              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6011              :         let repo =
    6012              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6013              :             .load();
    6014              : 
    6015              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6016              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6017              : 
    6018              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6019              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    6020              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    6021              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6022              :             Ok(_) => panic!("request for page should have failed"),
    6023              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6024              :         }
    6025              :         Ok(())
    6026              :     }
    6027              :      */
    6028              : 
    6029              :     #[tokio::test]
    6030            2 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6031            2 :         let (tenant, ctx) =
    6032            2 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6033            2 :                 .await?
    6034            2 :                 .load()
    6035            2 :                 .await;
    6036            2 :         let tline = tenant
    6037            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6038            2 :             .await?;
    6039            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6040            2 : 
    6041            2 :         tenant
    6042            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6043            2 :             .await?;
    6044            2 :         let newtline = tenant
    6045            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6046            2 :             .expect("Should have a local timeline");
    6047            2 : 
    6048            2 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6049            2 : 
    6050            2 :         tline.set_broken("test".to_owned());
    6051            2 : 
    6052            2 :         tenant
    6053            2 :             .gc_iteration(
    6054            2 :                 Some(TIMELINE_ID),
    6055            2 :                 0x10,
    6056            2 :                 Duration::ZERO,
    6057            2 :                 &CancellationToken::new(),
    6058            2 :                 &ctx,
    6059            2 :             )
    6060            2 :             .await?;
    6061            2 : 
    6062            2 :         // The branchpoints should contain all timelines, even ones marked
    6063            2 :         // as Broken.
    6064            2 :         {
    6065            2 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6066            2 :             assert_eq!(branchpoints.len(), 1);
    6067            2 :             assert_eq!(
    6068            2 :                 branchpoints[0],
    6069            2 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6070            2 :             );
    6071            2 :         }
    6072            2 : 
    6073            2 :         // You can read the key from the child branch even though the parent is
    6074            2 :         // Broken, as long as you don't need to access data from the parent.
    6075            2 :         assert_eq!(
    6076            2 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6077            2 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6078            2 :         );
    6079            2 : 
    6080            2 :         // This needs to traverse to the parent, and fails.
    6081            2 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6082            2 :         assert!(
    6083            2 :             err.to_string().starts_with(&format!(
    6084            2 :                 "bad state on timeline {}: Broken",
    6085            2 :                 tline.timeline_id
    6086            2 :             )),
    6087            2 :             "{err}"
    6088            2 :         );
    6089            2 : 
    6090            2 :         Ok(())
    6091            2 :     }
    6092              : 
    6093              :     #[tokio::test]
    6094            2 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6095            2 :         let (tenant, ctx) =
    6096            2 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6097            2 :                 .await?
    6098            2 :                 .load()
    6099            2 :                 .await;
    6100            2 :         let tline = tenant
    6101            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6102            2 :             .await?;
    6103            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6104            2 : 
    6105            2 :         tenant
    6106            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6107            2 :             .await?;
    6108            2 :         let newtline = tenant
    6109            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6110            2 :             .expect("Should have a local timeline");
    6111            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6112            2 :         tenant
    6113            2 :             .gc_iteration(
    6114            2 :                 Some(TIMELINE_ID),
    6115            2 :                 0x10,
    6116            2 :                 Duration::ZERO,
    6117            2 :                 &CancellationToken::new(),
    6118            2 :                 &ctx,
    6119            2 :             )
    6120            2 :             .await?;
    6121            2 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6122            2 : 
    6123            2 :         Ok(())
    6124            2 :     }
    6125              :     #[tokio::test]
    6126            2 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6127            2 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6128            2 :             .await?
    6129            2 :             .load()
    6130            2 :             .await;
    6131            2 :         let tline = tenant
    6132            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6133            2 :             .await?;
    6134            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6135            2 : 
    6136            2 :         tenant
    6137            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6138            2 :             .await?;
    6139            2 :         let newtline = tenant
    6140            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6141            2 :             .expect("Should have a local timeline");
    6142            2 : 
    6143            2 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6144            2 : 
    6145            2 :         // run gc on parent
    6146            2 :         tenant
    6147            2 :             .gc_iteration(
    6148            2 :                 Some(TIMELINE_ID),
    6149            2 :                 0x10,
    6150            2 :                 Duration::ZERO,
    6151            2 :                 &CancellationToken::new(),
    6152            2 :                 &ctx,
    6153            2 :             )
    6154            2 :             .await?;
    6155            2 : 
    6156            2 :         // Check that the data is still accessible on the branch.
    6157            2 :         assert_eq!(
    6158            2 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6159            2 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6160            2 :         );
    6161            2 : 
    6162            2 :         Ok(())
    6163            2 :     }
    6164              : 
    6165              :     #[tokio::test]
    6166            2 :     async fn timeline_load() -> anyhow::Result<()> {
    6167            2 :         const TEST_NAME: &str = "timeline_load";
    6168            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6169            2 :         {
    6170            2 :             let (tenant, ctx) = harness.load().await;
    6171            2 :             let tline = tenant
    6172            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6173            2 :                 .await?;
    6174            2 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6175            2 :             // so that all uploads finish & we can call harness.load() below again
    6176            2 :             tenant
    6177            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6178            2 :                 .instrument(harness.span())
    6179            2 :                 .await
    6180            2 :                 .ok()
    6181            2 :                 .unwrap();
    6182            2 :         }
    6183            2 : 
    6184            2 :         let (tenant, _ctx) = harness.load().await;
    6185            2 :         tenant
    6186            2 :             .get_timeline(TIMELINE_ID, true)
    6187            2 :             .expect("cannot load timeline");
    6188            2 : 
    6189            2 :         Ok(())
    6190            2 :     }
    6191              : 
    6192              :     #[tokio::test]
    6193            2 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6194            2 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6195            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6196            2 :         // create two timelines
    6197            2 :         {
    6198            2 :             let (tenant, ctx) = harness.load().await;
    6199            2 :             let tline = tenant
    6200            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6201            2 :                 .await?;
    6202            2 : 
    6203            2 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6204            2 : 
    6205            2 :             let child_tline = tenant
    6206            2 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6207            2 :                 .await?;
    6208            2 :             child_tline.set_state(TimelineState::Active);
    6209            2 : 
    6210            2 :             let newtline = tenant
    6211            2 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6212            2 :                 .expect("Should have a local timeline");
    6213            2 : 
    6214            2 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6215            2 : 
    6216            2 :             // so that all uploads finish & we can call harness.load() below again
    6217            2 :             tenant
    6218            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6219            2 :                 .instrument(harness.span())
    6220            2 :                 .await
    6221            2 :                 .ok()
    6222            2 :                 .unwrap();
    6223            2 :         }
    6224            2 : 
    6225            2 :         // check that both of them are initially unloaded
    6226            2 :         let (tenant, _ctx) = harness.load().await;
    6227            2 : 
    6228            2 :         // check that both, child and ancestor are loaded
    6229            2 :         let _child_tline = tenant
    6230            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6231            2 :             .expect("cannot get child timeline loaded");
    6232            2 : 
    6233            2 :         let _ancestor_tline = tenant
    6234            2 :             .get_timeline(TIMELINE_ID, true)
    6235            2 :             .expect("cannot get ancestor timeline loaded");
    6236            2 : 
    6237            2 :         Ok(())
    6238            2 :     }
    6239              : 
    6240              :     #[tokio::test]
    6241            2 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6242            2 :         use storage_layer::AsLayerDesc;
    6243            2 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6244            2 :             .await?
    6245            2 :             .load()
    6246            2 :             .await;
    6247            2 :         let tline = tenant
    6248            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6249            2 :             .await?;
    6250            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6251            2 : 
    6252            2 :         let layer_map = tline.layers.read().await;
    6253            2 :         let level0_deltas = layer_map
    6254            2 :             .layer_map()?
    6255            2 :             .level0_deltas()
    6256            2 :             .iter()
    6257            4 :             .map(|desc| layer_map.get_from_desc(desc))
    6258            2 :             .collect::<Vec<_>>();
    6259            2 : 
    6260            2 :         assert!(!level0_deltas.is_empty());
    6261            2 : 
    6262            6 :         for delta in level0_deltas {
    6263            2 :             // Ensure we are dumping a delta layer here
    6264            4 :             assert!(delta.layer_desc().is_delta);
    6265            4 :             delta.dump(true, &ctx).await.unwrap();
    6266            2 :         }
    6267            2 : 
    6268            2 :         Ok(())
    6269            2 :     }
    6270              : 
    6271              :     #[tokio::test]
    6272            2 :     async fn test_images() -> anyhow::Result<()> {
    6273            2 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6274            2 :         let tline = tenant
    6275            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6276            2 :             .await?;
    6277            2 : 
    6278            2 :         let mut writer = tline.writer().await;
    6279            2 :         writer
    6280            2 :             .put(
    6281            2 :                 *TEST_KEY,
    6282            2 :                 Lsn(0x10),
    6283            2 :                 &Value::Image(test_img("foo at 0x10")),
    6284            2 :                 &ctx,
    6285            2 :             )
    6286            2 :             .await?;
    6287            2 :         writer.finish_write(Lsn(0x10));
    6288            2 :         drop(writer);
    6289            2 : 
    6290            2 :         tline.freeze_and_flush().await?;
    6291            2 :         tline
    6292            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6293            2 :             .await?;
    6294            2 : 
    6295            2 :         let mut writer = tline.writer().await;
    6296            2 :         writer
    6297            2 :             .put(
    6298            2 :                 *TEST_KEY,
    6299            2 :                 Lsn(0x20),
    6300            2 :                 &Value::Image(test_img("foo at 0x20")),
    6301            2 :                 &ctx,
    6302            2 :             )
    6303            2 :             .await?;
    6304            2 :         writer.finish_write(Lsn(0x20));
    6305            2 :         drop(writer);
    6306            2 : 
    6307            2 :         tline.freeze_and_flush().await?;
    6308            2 :         tline
    6309            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6310            2 :             .await?;
    6311            2 : 
    6312            2 :         let mut writer = tline.writer().await;
    6313            2 :         writer
    6314            2 :             .put(
    6315            2 :                 *TEST_KEY,
    6316            2 :                 Lsn(0x30),
    6317            2 :                 &Value::Image(test_img("foo at 0x30")),
    6318            2 :                 &ctx,
    6319            2 :             )
    6320            2 :             .await?;
    6321            2 :         writer.finish_write(Lsn(0x30));
    6322            2 :         drop(writer);
    6323            2 : 
    6324            2 :         tline.freeze_and_flush().await?;
    6325            2 :         tline
    6326            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6327            2 :             .await?;
    6328            2 : 
    6329            2 :         let mut writer = tline.writer().await;
    6330            2 :         writer
    6331            2 :             .put(
    6332            2 :                 *TEST_KEY,
    6333            2 :                 Lsn(0x40),
    6334            2 :                 &Value::Image(test_img("foo at 0x40")),
    6335            2 :                 &ctx,
    6336            2 :             )
    6337            2 :             .await?;
    6338            2 :         writer.finish_write(Lsn(0x40));
    6339            2 :         drop(writer);
    6340            2 : 
    6341            2 :         tline.freeze_and_flush().await?;
    6342            2 :         tline
    6343            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6344            2 :             .await?;
    6345            2 : 
    6346            2 :         assert_eq!(
    6347            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6348            2 :             test_img("foo at 0x10")
    6349            2 :         );
    6350            2 :         assert_eq!(
    6351            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6352            2 :             test_img("foo at 0x10")
    6353            2 :         );
    6354            2 :         assert_eq!(
    6355            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6356            2 :             test_img("foo at 0x20")
    6357            2 :         );
    6358            2 :         assert_eq!(
    6359            2 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6360            2 :             test_img("foo at 0x30")
    6361            2 :         );
    6362            2 :         assert_eq!(
    6363            2 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6364            2 :             test_img("foo at 0x40")
    6365            2 :         );
    6366            2 : 
    6367            2 :         Ok(())
    6368            2 :     }
    6369              : 
    6370            4 :     async fn bulk_insert_compact_gc(
    6371            4 :         tenant: &Tenant,
    6372            4 :         timeline: &Arc<Timeline>,
    6373            4 :         ctx: &RequestContext,
    6374            4 :         lsn: Lsn,
    6375            4 :         repeat: usize,
    6376            4 :         key_count: usize,
    6377            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6378            4 :         let compact = true;
    6379            4 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6380            4 :     }
    6381              : 
    6382            8 :     async fn bulk_insert_maybe_compact_gc(
    6383            8 :         tenant: &Tenant,
    6384            8 :         timeline: &Arc<Timeline>,
    6385            8 :         ctx: &RequestContext,
    6386            8 :         mut lsn: Lsn,
    6387            8 :         repeat: usize,
    6388            8 :         key_count: usize,
    6389            8 :         compact: bool,
    6390            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6391            8 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6392            8 : 
    6393            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6394            8 :         let mut blknum = 0;
    6395            8 : 
    6396            8 :         // Enforce that key range is monotonously increasing
    6397            8 :         let mut keyspace = KeySpaceAccum::new();
    6398            8 : 
    6399            8 :         let cancel = CancellationToken::new();
    6400            8 : 
    6401            8 :         for _ in 0..repeat {
    6402          400 :             for _ in 0..key_count {
    6403      4000000 :                 test_key.field6 = blknum;
    6404      4000000 :                 let mut writer = timeline.writer().await;
    6405      4000000 :                 writer
    6406      4000000 :                     .put(
    6407      4000000 :                         test_key,
    6408      4000000 :                         lsn,
    6409      4000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6410      4000000 :                         ctx,
    6411      4000000 :                     )
    6412      4000000 :                     .await?;
    6413      4000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6414      4000000 :                 writer.finish_write(lsn);
    6415      4000000 :                 drop(writer);
    6416      4000000 : 
    6417      4000000 :                 keyspace.add_key(test_key);
    6418      4000000 : 
    6419      4000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6420      4000000 :                 blknum += 1;
    6421              :             }
    6422              : 
    6423          400 :             timeline.freeze_and_flush().await?;
    6424          400 :             if compact {
    6425              :                 // this requires timeline to be &Arc<Timeline>
    6426          200 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6427          200 :             }
    6428              : 
    6429              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6430              :             // originally was.
    6431          400 :             let res = tenant
    6432          400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6433          400 :                 .await?;
    6434              : 
    6435          400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6436              :         }
    6437              : 
    6438            8 :         Ok(inserted)
    6439            8 :     }
    6440              : 
    6441              :     //
    6442              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6443              :     // Repeat 50 times.
    6444              :     //
    6445              :     #[tokio::test]
    6446            2 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6447            2 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6448            2 :         let (tenant, ctx) = harness.load().await;
    6449            2 :         let tline = tenant
    6450            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6451            2 :             .await?;
    6452            2 : 
    6453            2 :         let lsn = Lsn(0x10);
    6454            2 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6455            2 : 
    6456            2 :         Ok(())
    6457            2 :     }
    6458              : 
    6459              :     // Test the vectored get real implementation against a simple sequential implementation.
    6460              :     //
    6461              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6462              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6463              :     // grow to the right on the X axis.
    6464              :     //                       [Delta]
    6465              :     //                 [Delta]
    6466              :     //           [Delta]
    6467              :     //    [Delta]
    6468              :     // ------------ Image ---------------
    6469              :     //
    6470              :     // After layer generation we pick the ranges to query as follows:
    6471              :     // 1. The beginning of each delta layer
    6472              :     // 2. At the seam between two adjacent delta layers
    6473              :     //
    6474              :     // There's one major downside to this test: delta layers only contains images,
    6475              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6476              :     #[tokio::test]
    6477            2 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6478            2 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6479            2 :         let (tenant, ctx) = harness.load().await;
    6480            2 :         let tline = tenant
    6481            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6482            2 :             .await?;
    6483            2 : 
    6484            2 :         let lsn = Lsn(0x10);
    6485            2 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6486            2 : 
    6487            2 :         let guard = tline.layers.read().await;
    6488            2 :         let lm = guard.layer_map()?;
    6489            2 : 
    6490            2 :         lm.dump(true, &ctx).await?;
    6491            2 : 
    6492            2 :         let mut reads = Vec::new();
    6493            2 :         let mut prev = None;
    6494           12 :         lm.iter_historic_layers().for_each(|desc| {
    6495           12 :             if !desc.is_delta() {
    6496            2 :                 prev = Some(desc.clone());
    6497            2 :                 return;
    6498           10 :             }
    6499           10 : 
    6500           10 :             let start = desc.key_range.start;
    6501           10 :             let end = desc
    6502           10 :                 .key_range
    6503           10 :                 .start
    6504           10 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6505           10 :             reads.push(KeySpace {
    6506           10 :                 ranges: vec![start..end],
    6507           10 :             });
    6508            2 : 
    6509           10 :             if let Some(prev) = &prev {
    6510           10 :                 if !prev.is_delta() {
    6511           10 :                     return;
    6512            2 :                 }
    6513            0 : 
    6514            0 :                 let first_range = Key {
    6515            0 :                     field6: prev.key_range.end.field6 - 4,
    6516            0 :                     ..prev.key_range.end
    6517            0 :                 }..prev.key_range.end;
    6518            0 : 
    6519            0 :                 let second_range = desc.key_range.start..Key {
    6520            0 :                     field6: desc.key_range.start.field6 + 4,
    6521            0 :                     ..desc.key_range.start
    6522            0 :                 };
    6523            0 : 
    6524            0 :                 reads.push(KeySpace {
    6525            0 :                     ranges: vec![first_range, second_range],
    6526            0 :                 });
    6527            2 :             };
    6528            2 : 
    6529            2 :             prev = Some(desc.clone());
    6530           12 :         });
    6531            2 : 
    6532            2 :         drop(guard);
    6533            2 : 
    6534            2 :         // Pick a big LSN such that we query over all the changes.
    6535            2 :         let reads_lsn = Lsn(u64::MAX - 1);
    6536            2 : 
    6537           12 :         for read in reads {
    6538           10 :             info!("Doing vectored read on {:?}", read);
    6539            2 : 
    6540           10 :             let vectored_res = tline
    6541           10 :                 .get_vectored_impl(
    6542           10 :                     read.clone(),
    6543           10 :                     reads_lsn,
    6544           10 :                     &mut ValuesReconstructState::new(),
    6545           10 :                     &ctx,
    6546           10 :                 )
    6547           10 :                 .await;
    6548            2 : 
    6549           10 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6550           10 :             let mut expect_missing = false;
    6551           10 :             let mut key = read.start().unwrap();
    6552          330 :             while key != read.end().unwrap() {
    6553          320 :                 if let Some(lsns) = inserted.get(&key) {
    6554          320 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6555          320 :                     match expected_lsn {
    6556          320 :                         Some(lsn) => {
    6557          320 :                             expected_lsns.insert(key, *lsn);
    6558          320 :                         }
    6559            2 :                         None => {
    6560            2 :                             expect_missing = true;
    6561            0 :                             break;
    6562            2 :                         }
    6563            2 :                     }
    6564            2 :                 } else {
    6565            2 :                     expect_missing = true;
    6566            0 :                     break;
    6567            2 :                 }
    6568            2 : 
    6569          320 :                 key = key.next();
    6570            2 :             }
    6571            2 : 
    6572           10 :             if expect_missing {
    6573            2 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6574            2 :             } else {
    6575          320 :                 for (key, image) in vectored_res? {
    6576          320 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6577          320 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6578          320 :                     assert_eq!(image?, expected_image);
    6579            2 :                 }
    6580            2 :             }
    6581            2 :         }
    6582            2 : 
    6583            2 :         Ok(())
    6584            2 :     }
    6585              : 
    6586              :     #[tokio::test]
    6587            2 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6588            2 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6589            2 : 
    6590            2 :         let (tenant, ctx) = harness.load().await;
    6591            2 :         let tline = tenant
    6592            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6593            2 :             .await?;
    6594            2 :         let tline = tline.raw_timeline().unwrap();
    6595            2 : 
    6596            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6597            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6598            2 :         modification.set_lsn(Lsn(0x1008))?;
    6599            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6600            2 :         modification.commit(&ctx).await?;
    6601            2 : 
    6602            2 :         let child_timeline_id = TimelineId::generate();
    6603            2 :         tenant
    6604            2 :             .branch_timeline_test(
    6605            2 :                 tline,
    6606            2 :                 child_timeline_id,
    6607            2 :                 Some(tline.get_last_record_lsn()),
    6608            2 :                 &ctx,
    6609            2 :             )
    6610            2 :             .await?;
    6611            2 : 
    6612            2 :         let child_timeline = tenant
    6613            2 :             .get_timeline(child_timeline_id, true)
    6614            2 :             .expect("Should have the branched timeline");
    6615            2 : 
    6616            2 :         let aux_keyspace = KeySpace {
    6617            2 :             ranges: vec![NON_INHERITED_RANGE],
    6618            2 :         };
    6619            2 :         let read_lsn = child_timeline.get_last_record_lsn();
    6620            2 : 
    6621            2 :         let vectored_res = child_timeline
    6622            2 :             .get_vectored_impl(
    6623            2 :                 aux_keyspace.clone(),
    6624            2 :                 read_lsn,
    6625            2 :                 &mut ValuesReconstructState::new(),
    6626            2 :                 &ctx,
    6627            2 :             )
    6628            2 :             .await;
    6629            2 : 
    6630            2 :         let images = vectored_res?;
    6631            2 :         assert!(images.is_empty());
    6632            2 :         Ok(())
    6633            2 :     }
    6634              : 
    6635              :     // Test that vectored get handles layer gaps correctly
    6636              :     // by advancing into the next ancestor timeline if required.
    6637              :     //
    6638              :     // The test generates timelines that look like the diagram below.
    6639              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6640              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6641              :     //
    6642              :     // ```
    6643              :     //-------------------------------+
    6644              :     //                          ...  |
    6645              :     //               [   L1   ]      |
    6646              :     //     [ / L1   ]                | Child Timeline
    6647              :     // ...                           |
    6648              :     // ------------------------------+
    6649              :     //     [ X L1   ]                | Parent Timeline
    6650              :     // ------------------------------+
    6651              :     // ```
    6652              :     #[tokio::test]
    6653            2 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6654            2 :         let tenant_conf = TenantConf {
    6655            2 :             // Make compaction deterministic
    6656            2 :             gc_period: Duration::ZERO,
    6657            2 :             compaction_period: Duration::ZERO,
    6658            2 :             // Encourage creation of L1 layers
    6659            2 :             checkpoint_distance: 16 * 1024,
    6660            2 :             compaction_target_size: 8 * 1024,
    6661            2 :             ..TenantConf::default()
    6662            2 :         };
    6663            2 : 
    6664            2 :         let harness = TenantHarness::create_custom(
    6665            2 :             "test_get_vectored_key_gap",
    6666            2 :             tenant_conf,
    6667            2 :             TenantId::generate(),
    6668            2 :             ShardIdentity::unsharded(),
    6669            2 :             Generation::new(0xdeadbeef),
    6670            2 :         )
    6671            2 :         .await?;
    6672            2 :         let (tenant, ctx) = harness.load().await;
    6673            2 : 
    6674            2 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6675            2 :         let gap_at_key = current_key.add(100);
    6676            2 :         let mut current_lsn = Lsn(0x10);
    6677            2 : 
    6678            2 :         const KEY_COUNT: usize = 10_000;
    6679            2 : 
    6680            2 :         let timeline_id = TimelineId::generate();
    6681            2 :         let current_timeline = tenant
    6682            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6683            2 :             .await?;
    6684            2 : 
    6685            2 :         current_lsn += 0x100;
    6686            2 : 
    6687            2 :         let mut writer = current_timeline.writer().await;
    6688            2 :         writer
    6689            2 :             .put(
    6690            2 :                 gap_at_key,
    6691            2 :                 current_lsn,
    6692            2 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6693            2 :                 &ctx,
    6694            2 :             )
    6695            2 :             .await?;
    6696            2 :         writer.finish_write(current_lsn);
    6697            2 :         drop(writer);
    6698            2 : 
    6699            2 :         let mut latest_lsns = HashMap::new();
    6700            2 :         latest_lsns.insert(gap_at_key, current_lsn);
    6701            2 : 
    6702            2 :         current_timeline.freeze_and_flush().await?;
    6703            2 : 
    6704            2 :         let child_timeline_id = TimelineId::generate();
    6705            2 : 
    6706            2 :         tenant
    6707            2 :             .branch_timeline_test(
    6708            2 :                 &current_timeline,
    6709            2 :                 child_timeline_id,
    6710            2 :                 Some(current_lsn),
    6711            2 :                 &ctx,
    6712            2 :             )
    6713            2 :             .await?;
    6714            2 :         let child_timeline = tenant
    6715            2 :             .get_timeline(child_timeline_id, true)
    6716            2 :             .expect("Should have the branched timeline");
    6717            2 : 
    6718        20002 :         for i in 0..KEY_COUNT {
    6719        20000 :             if current_key == gap_at_key {
    6720            2 :                 current_key = current_key.next();
    6721            2 :                 continue;
    6722        19998 :             }
    6723        19998 : 
    6724        19998 :             current_lsn += 0x10;
    6725            2 : 
    6726        19998 :             let mut writer = child_timeline.writer().await;
    6727        19998 :             writer
    6728        19998 :                 .put(
    6729        19998 :                     current_key,
    6730        19998 :                     current_lsn,
    6731        19998 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6732        19998 :                     &ctx,
    6733        19998 :                 )
    6734        19998 :                 .await?;
    6735        19998 :             writer.finish_write(current_lsn);
    6736        19998 :             drop(writer);
    6737        19998 : 
    6738        19998 :             latest_lsns.insert(current_key, current_lsn);
    6739        19998 :             current_key = current_key.next();
    6740        19998 : 
    6741        19998 :             // Flush every now and then to encourage layer file creation.
    6742        19998 :             if i % 500 == 0 {
    6743           40 :                 child_timeline.freeze_and_flush().await?;
    6744        19958 :             }
    6745            2 :         }
    6746            2 : 
    6747            2 :         child_timeline.freeze_and_flush().await?;
    6748            2 :         let mut flags = EnumSet::new();
    6749            2 :         flags.insert(CompactFlags::ForceRepartition);
    6750            2 :         child_timeline
    6751            2 :             .compact(&CancellationToken::new(), flags, &ctx)
    6752            2 :             .await?;
    6753            2 : 
    6754            2 :         let key_near_end = {
    6755            2 :             let mut tmp = current_key;
    6756            2 :             tmp.field6 -= 10;
    6757            2 :             tmp
    6758            2 :         };
    6759            2 : 
    6760            2 :         let key_near_gap = {
    6761            2 :             let mut tmp = gap_at_key;
    6762            2 :             tmp.field6 -= 10;
    6763            2 :             tmp
    6764            2 :         };
    6765            2 : 
    6766            2 :         let read = KeySpace {
    6767            2 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6768            2 :         };
    6769            2 :         let results = child_timeline
    6770            2 :             .get_vectored_impl(
    6771            2 :                 read.clone(),
    6772            2 :                 current_lsn,
    6773            2 :                 &mut ValuesReconstructState::new(),
    6774            2 :                 &ctx,
    6775            2 :             )
    6776            2 :             .await?;
    6777            2 : 
    6778           44 :         for (key, img_res) in results {
    6779           42 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6780           42 :             assert_eq!(img_res?, expected);
    6781            2 :         }
    6782            2 : 
    6783            2 :         Ok(())
    6784            2 :     }
    6785              : 
    6786              :     // Test that vectored get descends into ancestor timelines correctly and
    6787              :     // does not return an image that's newer than requested.
    6788              :     //
    6789              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6790              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6791              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6792              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6793              :     // order to avoid returning an image that's too new. The test below constructs such
    6794              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6795              :     // ```
    6796              :     //    LSN
    6797              :     //     ^
    6798              :     //     |
    6799              :     //     |
    6800              :     // 500 | --------------------------------------> branch point
    6801              :     // 400 |        X
    6802              :     // 300 |        X
    6803              :     // 200 | --------------------------------------> requested lsn
    6804              :     // 100 |        X
    6805              :     //     |---------------------------------------> Key
    6806              :     //              |
    6807              :     //              ------> requested key
    6808              :     //
    6809              :     // Legend:
    6810              :     // * X - page images
    6811              :     // ```
    6812              :     #[tokio::test]
    6813            2 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6814            2 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6815            2 :         let (tenant, ctx) = harness.load().await;
    6816            2 : 
    6817            2 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6818            2 :         let end_key = start_key.add(1000);
    6819            2 :         let child_gap_at_key = start_key.add(500);
    6820            2 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6821            2 : 
    6822            2 :         let mut current_lsn = Lsn(0x10);
    6823            2 : 
    6824            2 :         let timeline_id = TimelineId::generate();
    6825            2 :         let parent_timeline = tenant
    6826            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6827            2 :             .await?;
    6828            2 : 
    6829            2 :         current_lsn += 0x100;
    6830            2 : 
    6831            8 :         for _ in 0..3 {
    6832            6 :             let mut key = start_key;
    6833         6006 :             while key < end_key {
    6834         6000 :                 current_lsn += 0x10;
    6835         6000 : 
    6836         6000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6837            2 : 
    6838         6000 :                 let mut writer = parent_timeline.writer().await;
    6839         6000 :                 writer
    6840         6000 :                     .put(
    6841         6000 :                         key,
    6842         6000 :                         current_lsn,
    6843         6000 :                         &Value::Image(test_img(&image_value)),
    6844         6000 :                         &ctx,
    6845         6000 :                     )
    6846         6000 :                     .await?;
    6847         6000 :                 writer.finish_write(current_lsn);
    6848         6000 : 
    6849         6000 :                 if key == child_gap_at_key {
    6850            6 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6851         5994 :                 }
    6852            2 : 
    6853         6000 :                 key = key.next();
    6854            2 :             }
    6855            2 : 
    6856            6 :             parent_timeline.freeze_and_flush().await?;
    6857            2 :         }
    6858            2 : 
    6859            2 :         let child_timeline_id = TimelineId::generate();
    6860            2 : 
    6861            2 :         let child_timeline = tenant
    6862            2 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6863            2 :             .await?;
    6864            2 : 
    6865            2 :         let mut key = start_key;
    6866         2002 :         while key < end_key {
    6867         2000 :             if key == child_gap_at_key {
    6868            2 :                 key = key.next();
    6869            2 :                 continue;
    6870         1998 :             }
    6871         1998 : 
    6872         1998 :             current_lsn += 0x10;
    6873            2 : 
    6874         1998 :             let mut writer = child_timeline.writer().await;
    6875         1998 :             writer
    6876         1998 :                 .put(
    6877         1998 :                     key,
    6878         1998 :                     current_lsn,
    6879         1998 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6880         1998 :                     &ctx,
    6881         1998 :                 )
    6882         1998 :                 .await?;
    6883         1998 :             writer.finish_write(current_lsn);
    6884         1998 : 
    6885         1998 :             key = key.next();
    6886            2 :         }
    6887            2 : 
    6888            2 :         child_timeline.freeze_and_flush().await?;
    6889            2 : 
    6890            2 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6891            2 :         let mut query_lsns = Vec::new();
    6892            6 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6893           36 :             for offset in lsn_offsets {
    6894           30 :                 query_lsns.push(Lsn(image_lsn
    6895           30 :                     .0
    6896           30 :                     .checked_add_signed(offset)
    6897           30 :                     .expect("Shouldn't overflow")));
    6898           30 :             }
    6899            2 :         }
    6900            2 : 
    6901           32 :         for query_lsn in query_lsns {
    6902           30 :             let results = child_timeline
    6903           30 :                 .get_vectored_impl(
    6904           30 :                     KeySpace {
    6905           30 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6906           30 :                     },
    6907           30 :                     query_lsn,
    6908           30 :                     &mut ValuesReconstructState::new(),
    6909           30 :                     &ctx,
    6910           30 :                 )
    6911           30 :                 .await;
    6912            2 : 
    6913           30 :             let expected_item = parent_gap_lsns
    6914           30 :                 .iter()
    6915           30 :                 .rev()
    6916           68 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6917           30 : 
    6918           30 :             info!(
    6919            2 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6920            2 :                 query_lsn, expected_item
    6921            2 :             );
    6922            2 : 
    6923           30 :             match expected_item {
    6924           26 :                 Some((_, img_value)) => {
    6925           26 :                     let key_results = results.expect("No vectored get error expected");
    6926           26 :                     let key_result = &key_results[&child_gap_at_key];
    6927           26 :                     let returned_img = key_result
    6928           26 :                         .as_ref()
    6929           26 :                         .expect("No page reconstruct error expected");
    6930           26 : 
    6931           26 :                     info!(
    6932            2 :                         "Vectored read at LSN {} returned image {}",
    6933            0 :                         query_lsn,
    6934            0 :                         std::str::from_utf8(returned_img)?
    6935            2 :                     );
    6936           26 :                     assert_eq!(*returned_img, test_img(img_value));
    6937            2 :                 }
    6938            2 :                 None => {
    6939            4 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6940            2 :                 }
    6941            2 :             }
    6942            2 :         }
    6943            2 : 
    6944            2 :         Ok(())
    6945            2 :     }
    6946              : 
    6947              :     #[tokio::test]
    6948            2 :     async fn test_random_updates() -> anyhow::Result<()> {
    6949            2 :         let names_algorithms = [
    6950            2 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    6951            2 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    6952            2 :         ];
    6953            6 :         for (name, algorithm) in names_algorithms {
    6954            4 :             test_random_updates_algorithm(name, algorithm).await?;
    6955            2 :         }
    6956            2 :         Ok(())
    6957            2 :     }
    6958              : 
    6959            4 :     async fn test_random_updates_algorithm(
    6960            4 :         name: &'static str,
    6961            4 :         compaction_algorithm: CompactionAlgorithm,
    6962            4 :     ) -> anyhow::Result<()> {
    6963            4 :         let mut harness = TenantHarness::create(name).await?;
    6964            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6965            4 :             kind: compaction_algorithm,
    6966            4 :         };
    6967            4 :         let (tenant, ctx) = harness.load().await;
    6968            4 :         let tline = tenant
    6969            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6970            4 :             .await?;
    6971              : 
    6972              :         const NUM_KEYS: usize = 1000;
    6973            4 :         let cancel = CancellationToken::new();
    6974            4 : 
    6975            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6976            4 :         let mut test_key_end = test_key;
    6977            4 :         test_key_end.field6 = NUM_KEYS as u32;
    6978            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    6979            4 : 
    6980            4 :         let mut keyspace = KeySpaceAccum::new();
    6981            4 : 
    6982            4 :         // Track when each page was last modified. Used to assert that
    6983            4 :         // a read sees the latest page version.
    6984            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    6985            4 : 
    6986            4 :         let mut lsn = Lsn(0x10);
    6987              :         #[allow(clippy::needless_range_loop)]
    6988         4004 :         for blknum in 0..NUM_KEYS {
    6989         4000 :             lsn = Lsn(lsn.0 + 0x10);
    6990         4000 :             test_key.field6 = blknum as u32;
    6991         4000 :             let mut writer = tline.writer().await;
    6992         4000 :             writer
    6993         4000 :                 .put(
    6994         4000 :                     test_key,
    6995         4000 :                     lsn,
    6996         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6997         4000 :                     &ctx,
    6998         4000 :                 )
    6999         4000 :                 .await?;
    7000         4000 :             writer.finish_write(lsn);
    7001         4000 :             updated[blknum] = lsn;
    7002         4000 :             drop(writer);
    7003         4000 : 
    7004         4000 :             keyspace.add_key(test_key);
    7005              :         }
    7006              : 
    7007          204 :         for _ in 0..50 {
    7008       200200 :             for _ in 0..NUM_KEYS {
    7009       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7010       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7011       200000 :                 test_key.field6 = blknum as u32;
    7012       200000 :                 let mut writer = tline.writer().await;
    7013       200000 :                 writer
    7014       200000 :                     .put(
    7015       200000 :                         test_key,
    7016       200000 :                         lsn,
    7017       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7018       200000 :                         &ctx,
    7019       200000 :                     )
    7020       200000 :                     .await?;
    7021       200000 :                 writer.finish_write(lsn);
    7022       200000 :                 drop(writer);
    7023       200000 :                 updated[blknum] = lsn;
    7024              :             }
    7025              : 
    7026              :             // Read all the blocks
    7027       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7028       200000 :                 test_key.field6 = blknum as u32;
    7029       200000 :                 assert_eq!(
    7030       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7031       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7032              :                 );
    7033              :             }
    7034              : 
    7035              :             // Perform a cycle of flush, and GC
    7036          200 :             tline.freeze_and_flush().await?;
    7037          200 :             tenant
    7038          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7039          200 :                 .await?;
    7040              :         }
    7041              : 
    7042            4 :         Ok(())
    7043            4 :     }
    7044              : 
    7045              :     #[tokio::test]
    7046            2 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7047            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7048            2 :             .await?
    7049            2 :             .load()
    7050            2 :             .await;
    7051            2 :         let mut tline = tenant
    7052            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7053            2 :             .await?;
    7054            2 : 
    7055            2 :         const NUM_KEYS: usize = 1000;
    7056            2 : 
    7057            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7058            2 : 
    7059            2 :         let mut keyspace = KeySpaceAccum::new();
    7060            2 : 
    7061            2 :         let cancel = CancellationToken::new();
    7062            2 : 
    7063            2 :         // Track when each page was last modified. Used to assert that
    7064            2 :         // a read sees the latest page version.
    7065            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7066            2 : 
    7067            2 :         let mut lsn = Lsn(0x10);
    7068            2 :         #[allow(clippy::needless_range_loop)]
    7069         2002 :         for blknum in 0..NUM_KEYS {
    7070         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7071         2000 :             test_key.field6 = blknum as u32;
    7072         2000 :             let mut writer = tline.writer().await;
    7073         2000 :             writer
    7074         2000 :                 .put(
    7075         2000 :                     test_key,
    7076         2000 :                     lsn,
    7077         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7078         2000 :                     &ctx,
    7079         2000 :                 )
    7080         2000 :                 .await?;
    7081         2000 :             writer.finish_write(lsn);
    7082         2000 :             updated[blknum] = lsn;
    7083         2000 :             drop(writer);
    7084         2000 : 
    7085         2000 :             keyspace.add_key(test_key);
    7086            2 :         }
    7087            2 : 
    7088          102 :         for _ in 0..50 {
    7089          100 :             let new_tline_id = TimelineId::generate();
    7090          100 :             tenant
    7091          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7092          100 :                 .await?;
    7093          100 :             tline = tenant
    7094          100 :                 .get_timeline(new_tline_id, true)
    7095          100 :                 .expect("Should have the branched timeline");
    7096            2 : 
    7097       100100 :             for _ in 0..NUM_KEYS {
    7098       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7099       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7100       100000 :                 test_key.field6 = blknum as u32;
    7101       100000 :                 let mut writer = tline.writer().await;
    7102       100000 :                 writer
    7103       100000 :                     .put(
    7104       100000 :                         test_key,
    7105       100000 :                         lsn,
    7106       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7107       100000 :                         &ctx,
    7108       100000 :                     )
    7109       100000 :                     .await?;
    7110       100000 :                 println!("updating {} at {}", blknum, lsn);
    7111       100000 :                 writer.finish_write(lsn);
    7112       100000 :                 drop(writer);
    7113       100000 :                 updated[blknum] = lsn;
    7114            2 :             }
    7115            2 : 
    7116            2 :             // Read all the blocks
    7117       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7118       100000 :                 test_key.field6 = blknum as u32;
    7119       100000 :                 assert_eq!(
    7120       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7121       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7122            2 :                 );
    7123            2 :             }
    7124            2 : 
    7125            2 :             // Perform a cycle of flush, compact, and GC
    7126          100 :             tline.freeze_and_flush().await?;
    7127          100 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7128          100 :             tenant
    7129          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7130          100 :                 .await?;
    7131            2 :         }
    7132            2 : 
    7133            2 :         Ok(())
    7134            2 :     }
    7135              : 
    7136              :     #[tokio::test]
    7137            2 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7138            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7139            2 :             .await?
    7140            2 :             .load()
    7141            2 :             .await;
    7142            2 :         let mut tline = tenant
    7143            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7144            2 :             .await?;
    7145            2 : 
    7146            2 :         const NUM_KEYS: usize = 100;
    7147            2 :         const NUM_TLINES: usize = 50;
    7148            2 : 
    7149            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7150            2 :         // Track page mutation lsns across different timelines.
    7151            2 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7152            2 : 
    7153            2 :         let mut lsn = Lsn(0x10);
    7154            2 : 
    7155            2 :         #[allow(clippy::needless_range_loop)]
    7156          102 :         for idx in 0..NUM_TLINES {
    7157          100 :             let new_tline_id = TimelineId::generate();
    7158          100 :             tenant
    7159          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7160          100 :                 .await?;
    7161          100 :             tline = tenant
    7162          100 :                 .get_timeline(new_tline_id, true)
    7163          100 :                 .expect("Should have the branched timeline");
    7164            2 : 
    7165        10100 :             for _ in 0..NUM_KEYS {
    7166        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    7167        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7168        10000 :                 test_key.field6 = blknum as u32;
    7169        10000 :                 let mut writer = tline.writer().await;
    7170        10000 :                 writer
    7171        10000 :                     .put(
    7172        10000 :                         test_key,
    7173        10000 :                         lsn,
    7174        10000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7175        10000 :                         &ctx,
    7176        10000 :                     )
    7177        10000 :                     .await?;
    7178        10000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7179        10000 :                 writer.finish_write(lsn);
    7180        10000 :                 drop(writer);
    7181        10000 :                 updated[idx][blknum] = lsn;
    7182            2 :             }
    7183            2 :         }
    7184            2 : 
    7185            2 :         // Read pages from leaf timeline across all ancestors.
    7186          100 :         for (idx, lsns) in updated.iter().enumerate() {
    7187        10000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7188            2 :                 // Skip empty mutations.
    7189        10000 :                 if lsn.0 == 0 {
    7190         3683 :                     continue;
    7191         6317 :                 }
    7192         6317 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7193         6317 :                 test_key.field6 = blknum as u32;
    7194         6317 :                 assert_eq!(
    7195         6317 :                     tline.get(test_key, *lsn, &ctx).await?,
    7196         6317 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7197            2 :                 );
    7198            2 :             }
    7199            2 :         }
    7200            2 :         Ok(())
    7201            2 :     }
    7202              : 
    7203              :     #[tokio::test]
    7204            2 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7205            2 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7206            2 :             .await?
    7207            2 :             .load()
    7208            2 :             .await;
    7209            2 : 
    7210            2 :         let initdb_lsn = Lsn(0x20);
    7211            2 :         let utline = tenant
    7212            2 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7213            2 :             .await?;
    7214            2 :         let tline = utline.raw_timeline().unwrap();
    7215            2 : 
    7216            2 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7217            2 :         tline.maybe_spawn_flush_loop();
    7218            2 : 
    7219            2 :         // Make sure the timeline has the minimum set of required keys for operation.
    7220            2 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7221            2 :         // Except if you `put` at `initdb_lsn`.
    7222            2 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7223            2 :         // It uses `repartition()`, which assumes some keys to be present.
    7224            2 :         // Let's make sure the test timeline can handle that case.
    7225            2 :         {
    7226            2 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7227            2 :             assert_eq!(
    7228            2 :                 timeline::FlushLoopState::Running {
    7229            2 :                     expect_initdb_optimization: false,
    7230            2 :                     initdb_optimization_count: 0,
    7231            2 :                 },
    7232            2 :                 *state
    7233            2 :             );
    7234            2 :             *state = timeline::FlushLoopState::Running {
    7235            2 :                 expect_initdb_optimization: true,
    7236            2 :                 initdb_optimization_count: 0,
    7237            2 :             };
    7238            2 :         }
    7239            2 : 
    7240            2 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7241            2 :         // As explained above, the optimization requires some keys to be present.
    7242            2 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7243            2 :         // This is what `create_test_timeline` does, by the way.
    7244            2 :         let mut modification = tline.begin_modification(initdb_lsn);
    7245            2 :         modification
    7246            2 :             .init_empty_test_timeline()
    7247            2 :             .context("init_empty_test_timeline")?;
    7248            2 :         modification
    7249            2 :             .commit(&ctx)
    7250            2 :             .await
    7251            2 :             .context("commit init_empty_test_timeline modification")?;
    7252            2 : 
    7253            2 :         // Do the flush. The flush code will check the expectations that we set above.
    7254            2 :         tline.freeze_and_flush().await?;
    7255            2 : 
    7256            2 :         // assert freeze_and_flush exercised the initdb optimization
    7257            2 :         {
    7258            2 :             let state = tline.flush_loop_state.lock().unwrap();
    7259            2 :             let timeline::FlushLoopState::Running {
    7260            2 :                 expect_initdb_optimization,
    7261            2 :                 initdb_optimization_count,
    7262            2 :             } = *state
    7263            2 :             else {
    7264            2 :                 panic!("unexpected state: {:?}", *state);
    7265            2 :             };
    7266            2 :             assert!(expect_initdb_optimization);
    7267            2 :             assert!(initdb_optimization_count > 0);
    7268            2 :         }
    7269            2 :         Ok(())
    7270            2 :     }
    7271              : 
    7272              :     #[tokio::test]
    7273            2 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7274            2 :         let name = "test_create_guard_crash";
    7275            2 :         let harness = TenantHarness::create(name).await?;
    7276            2 :         {
    7277            2 :             let (tenant, ctx) = harness.load().await;
    7278            2 :             let tline = tenant
    7279            2 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7280            2 :                 .await?;
    7281            2 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7282            2 :             let raw_tline = tline.raw_timeline().unwrap();
    7283            2 :             raw_tline
    7284            2 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7285            2 :                 .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
    7286            2 :                 .await;
    7287            2 :             std::mem::forget(tline);
    7288            2 :         }
    7289            2 : 
    7290            2 :         let (tenant, _) = harness.load().await;
    7291            2 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7292            2 :             Ok(_) => panic!("timeline should've been removed during load"),
    7293            2 :             Err(e) => {
    7294            2 :                 assert_eq!(
    7295            2 :                     e,
    7296            2 :                     GetTimelineError::NotFound {
    7297            2 :                         tenant_id: tenant.tenant_shard_id,
    7298            2 :                         timeline_id: TIMELINE_ID,
    7299            2 :                     }
    7300            2 :                 )
    7301            2 :             }
    7302            2 :         }
    7303            2 : 
    7304            2 :         assert!(!harness
    7305            2 :             .conf
    7306            2 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7307            2 :             .exists());
    7308            2 : 
    7309            2 :         Ok(())
    7310            2 :     }
    7311              : 
    7312              :     #[tokio::test]
    7313            2 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7314            2 :         let names_algorithms = [
    7315            2 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7316            2 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7317            2 :         ];
    7318            6 :         for (name, algorithm) in names_algorithms {
    7319            4 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7320            2 :         }
    7321            2 :         Ok(())
    7322            2 :     }
    7323              : 
    7324            4 :     async fn test_read_at_max_lsn_algorithm(
    7325            4 :         name: &'static str,
    7326            4 :         compaction_algorithm: CompactionAlgorithm,
    7327            4 :     ) -> anyhow::Result<()> {
    7328            4 :         let mut harness = TenantHarness::create(name).await?;
    7329            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7330            4 :             kind: compaction_algorithm,
    7331            4 :         };
    7332            4 :         let (tenant, ctx) = harness.load().await;
    7333            4 :         let tline = tenant
    7334            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7335            4 :             .await?;
    7336              : 
    7337            4 :         let lsn = Lsn(0x10);
    7338            4 :         let compact = false;
    7339            4 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7340              : 
    7341            4 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7342            4 :         let read_lsn = Lsn(u64::MAX - 1);
    7343              : 
    7344            4 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7345            4 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7346              : 
    7347            4 :         Ok(())
    7348            4 :     }
    7349              : 
    7350              :     #[tokio::test]
    7351            2 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7352            2 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7353            2 :         let (tenant, ctx) = harness.load().await;
    7354            2 :         let tline = tenant
    7355            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7356            2 :             .await?;
    7357            2 : 
    7358            2 :         const NUM_KEYS: usize = 1000;
    7359            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7360            2 : 
    7361            2 :         let cancel = CancellationToken::new();
    7362            2 : 
    7363            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7364            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7365            2 :         let mut test_key = base_key;
    7366            2 : 
    7367            2 :         // Track when each page was last modified. Used to assert that
    7368            2 :         // a read sees the latest page version.
    7369            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7370            2 : 
    7371            2 :         let mut lsn = Lsn(0x10);
    7372            2 :         #[allow(clippy::needless_range_loop)]
    7373         2002 :         for blknum in 0..NUM_KEYS {
    7374         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7375         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7376         2000 :             let mut writer = tline.writer().await;
    7377         2000 :             writer
    7378         2000 :                 .put(
    7379         2000 :                     test_key,
    7380         2000 :                     lsn,
    7381         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7382         2000 :                     &ctx,
    7383         2000 :                 )
    7384         2000 :                 .await?;
    7385         2000 :             writer.finish_write(lsn);
    7386         2000 :             updated[blknum] = lsn;
    7387         2000 :             drop(writer);
    7388            2 :         }
    7389            2 : 
    7390            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7391            2 : 
    7392           24 :         for iter in 0..=10 {
    7393            2 :             // Read all the blocks
    7394        22000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7395        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7396        22000 :                 assert_eq!(
    7397        22000 :                     tline.get(test_key, lsn, &ctx).await?,
    7398        22000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7399            2 :                 );
    7400            2 :             }
    7401            2 : 
    7402           22 :             let mut cnt = 0;
    7403        22000 :             for (key, value) in tline
    7404           22 :                 .get_vectored_impl(
    7405           22 :                     keyspace.clone(),
    7406           22 :                     lsn,
    7407           22 :                     &mut ValuesReconstructState::default(),
    7408           22 :                     &ctx,
    7409           22 :                 )
    7410           22 :                 .await?
    7411            2 :             {
    7412        22000 :                 let blknum = key.field6 as usize;
    7413        22000 :                 let value = value?;
    7414        22000 :                 assert!(blknum % STEP == 0);
    7415        22000 :                 let blknum = blknum / STEP;
    7416        22000 :                 assert_eq!(
    7417        22000 :                     value,
    7418        22000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7419        22000 :                 );
    7420        22000 :                 cnt += 1;
    7421            2 :             }
    7422            2 : 
    7423           22 :             assert_eq!(cnt, NUM_KEYS);
    7424            2 : 
    7425        22022 :             for _ in 0..NUM_KEYS {
    7426        22000 :                 lsn = Lsn(lsn.0 + 0x10);
    7427        22000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7428        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7429        22000 :                 let mut writer = tline.writer().await;
    7430        22000 :                 writer
    7431        22000 :                     .put(
    7432        22000 :                         test_key,
    7433        22000 :                         lsn,
    7434        22000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7435        22000 :                         &ctx,
    7436        22000 :                     )
    7437        22000 :                     .await?;
    7438        22000 :                 writer.finish_write(lsn);
    7439        22000 :                 drop(writer);
    7440        22000 :                 updated[blknum] = lsn;
    7441            2 :             }
    7442            2 : 
    7443            2 :             // Perform two cycles of flush, compact, and GC
    7444           66 :             for round in 0..2 {
    7445           44 :                 tline.freeze_and_flush().await?;
    7446           44 :                 tline
    7447           44 :                     .compact(
    7448           44 :                         &cancel,
    7449           44 :                         if iter % 5 == 0 && round == 0 {
    7450            6 :                             let mut flags = EnumSet::new();
    7451            6 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7452            6 :                             flags.insert(CompactFlags::ForceRepartition);
    7453            6 :                             flags
    7454            2 :                         } else {
    7455           38 :                             EnumSet::empty()
    7456            2 :                         },
    7457           44 :                         &ctx,
    7458           44 :                     )
    7459           44 :                     .await?;
    7460           44 :                 tenant
    7461           44 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7462           44 :                     .await?;
    7463            2 :             }
    7464            2 :         }
    7465            2 : 
    7466            2 :         Ok(())
    7467            2 :     }
    7468              : 
    7469              :     #[tokio::test]
    7470            2 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7471            2 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7472            2 :         let (tenant, ctx) = harness.load().await;
    7473            2 :         let tline = tenant
    7474            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7475            2 :             .await?;
    7476            2 : 
    7477            2 :         let cancel = CancellationToken::new();
    7478            2 : 
    7479            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7480            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7481            2 :         let test_key = base_key;
    7482            2 :         let mut lsn = Lsn(0x10);
    7483            2 : 
    7484           42 :         for _ in 0..20 {
    7485           40 :             lsn = Lsn(lsn.0 + 0x10);
    7486           40 :             let mut writer = tline.writer().await;
    7487           40 :             writer
    7488           40 :                 .put(
    7489           40 :                     test_key,
    7490           40 :                     lsn,
    7491           40 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7492           40 :                     &ctx,
    7493           40 :                 )
    7494           40 :                 .await?;
    7495           40 :             writer.finish_write(lsn);
    7496           40 :             drop(writer);
    7497           40 :             tline.freeze_and_flush().await?; // force create a delta layer
    7498            2 :         }
    7499            2 : 
    7500            2 :         let before_num_l0_delta_files =
    7501            2 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7502            2 : 
    7503            2 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7504            2 : 
    7505            2 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7506            2 : 
    7507            2 :         assert!(after_num_l0_delta_files < before_num_l0_delta_files, "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}");
    7508            2 : 
    7509            2 :         assert_eq!(
    7510            2 :             tline.get(test_key, lsn, &ctx).await?,
    7511            2 :             test_img(&format!("{} at {}", 0, lsn))
    7512            2 :         );
    7513            2 : 
    7514            2 :         Ok(())
    7515            2 :     }
    7516              : 
    7517              :     #[tokio::test]
    7518            2 :     async fn test_aux_file_e2e() {
    7519            2 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7520            2 : 
    7521            2 :         let (tenant, ctx) = harness.load().await;
    7522            2 : 
    7523            2 :         let mut lsn = Lsn(0x08);
    7524            2 : 
    7525            2 :         let tline: Arc<Timeline> = tenant
    7526            2 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7527            2 :             .await
    7528            2 :             .unwrap();
    7529            2 : 
    7530            2 :         {
    7531            2 :             lsn += 8;
    7532            2 :             let mut modification = tline.begin_modification(lsn);
    7533            2 :             modification
    7534            2 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7535            2 :                 .await
    7536            2 :                 .unwrap();
    7537            2 :             modification.commit(&ctx).await.unwrap();
    7538            2 :         }
    7539            2 : 
    7540            2 :         // we can read everything from the storage
    7541            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7542            2 :         assert_eq!(
    7543            2 :             files.get("pg_logical/mappings/test1"),
    7544            2 :             Some(&bytes::Bytes::from_static(b"first"))
    7545            2 :         );
    7546            2 : 
    7547            2 :         {
    7548            2 :             lsn += 8;
    7549            2 :             let mut modification = tline.begin_modification(lsn);
    7550            2 :             modification
    7551            2 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7552            2 :                 .await
    7553            2 :                 .unwrap();
    7554            2 :             modification.commit(&ctx).await.unwrap();
    7555            2 :         }
    7556            2 : 
    7557            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7558            2 :         assert_eq!(
    7559            2 :             files.get("pg_logical/mappings/test2"),
    7560            2 :             Some(&bytes::Bytes::from_static(b"second"))
    7561            2 :         );
    7562            2 : 
    7563            2 :         let child = tenant
    7564            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7565            2 :             .await
    7566            2 :             .unwrap();
    7567            2 : 
    7568            2 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    7569            2 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7570            2 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7571            2 :     }
    7572              : 
    7573              :     #[tokio::test]
    7574            2 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7575            2 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7576            2 :         let (tenant, ctx) = harness.load().await;
    7577            2 :         let tline = tenant
    7578            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7579            2 :             .await?;
    7580            2 : 
    7581            2 :         const NUM_KEYS: usize = 1000;
    7582            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7583            2 : 
    7584            2 :         let cancel = CancellationToken::new();
    7585            2 : 
    7586            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7587            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7588            2 :         let mut test_key = base_key;
    7589            2 :         let mut lsn = Lsn(0x10);
    7590            2 : 
    7591            8 :         async fn scan_with_statistics(
    7592            8 :             tline: &Timeline,
    7593            8 :             keyspace: &KeySpace,
    7594            8 :             lsn: Lsn,
    7595            8 :             ctx: &RequestContext,
    7596            8 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7597            8 :             let mut reconstruct_state = ValuesReconstructState::default();
    7598            8 :             let res = tline
    7599            8 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7600            8 :                 .await?;
    7601            8 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7602            8 :         }
    7603            2 : 
    7604            2 :         #[allow(clippy::needless_range_loop)]
    7605         2002 :         for blknum in 0..NUM_KEYS {
    7606         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7607         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7608         2000 :             let mut writer = tline.writer().await;
    7609         2000 :             writer
    7610         2000 :                 .put(
    7611         2000 :                     test_key,
    7612         2000 :                     lsn,
    7613         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7614         2000 :                     &ctx,
    7615         2000 :                 )
    7616         2000 :                 .await?;
    7617         2000 :             writer.finish_write(lsn);
    7618         2000 :             drop(writer);
    7619            2 :         }
    7620            2 : 
    7621            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7622            2 : 
    7623           22 :         for iter in 1..=10 {
    7624        20020 :             for _ in 0..NUM_KEYS {
    7625        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7626        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7627        20000 :                 test_key.field6 = (blknum * STEP) as u32;
    7628        20000 :                 let mut writer = tline.writer().await;
    7629        20000 :                 writer
    7630        20000 :                     .put(
    7631        20000 :                         test_key,
    7632        20000 :                         lsn,
    7633        20000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7634        20000 :                         &ctx,
    7635        20000 :                     )
    7636        20000 :                     .await?;
    7637        20000 :                 writer.finish_write(lsn);
    7638        20000 :                 drop(writer);
    7639            2 :             }
    7640            2 : 
    7641           20 :             tline.freeze_and_flush().await?;
    7642            2 : 
    7643           20 :             if iter % 5 == 0 {
    7644            4 :                 let (_, before_delta_file_accessed) =
    7645            4 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7646            4 :                 tline
    7647            4 :                     .compact(
    7648            4 :                         &cancel,
    7649            4 :                         {
    7650            4 :                             let mut flags = EnumSet::new();
    7651            4 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7652            4 :                             flags.insert(CompactFlags::ForceRepartition);
    7653            4 :                             flags
    7654            4 :                         },
    7655            4 :                         &ctx,
    7656            4 :                     )
    7657            4 :                     .await?;
    7658            4 :                 let (_, after_delta_file_accessed) =
    7659            4 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7660            4 :                 assert!(after_delta_file_accessed < before_delta_file_accessed, "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}");
    7661            2 :                 // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
    7662            4 :                 assert!(
    7663            4 :                     after_delta_file_accessed <= 2,
    7664            2 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7665            2 :                 );
    7666           16 :             }
    7667            2 :         }
    7668            2 : 
    7669            2 :         Ok(())
    7670            2 :     }
    7671              : 
    7672              :     #[tokio::test]
    7673            2 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7674            2 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7675            2 :         let (tenant, ctx) = harness.load().await;
    7676            2 : 
    7677            2 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7678            2 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7679            2 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7680            2 : 
    7681            2 :         let tline = tenant
    7682            2 :             .create_test_timeline_with_layers(
    7683            2 :                 TIMELINE_ID,
    7684            2 :                 Lsn(0x10),
    7685            2 :                 DEFAULT_PG_VERSION,
    7686            2 :                 &ctx,
    7687            2 :                 Vec::new(), // delta layers
    7688            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7689            2 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7690            2 :             )
    7691            2 :             .await?;
    7692            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7693            2 : 
    7694            2 :         let child = tenant
    7695            2 :             .branch_timeline_test_with_layers(
    7696            2 :                 &tline,
    7697            2 :                 NEW_TIMELINE_ID,
    7698            2 :                 Some(Lsn(0x20)),
    7699            2 :                 &ctx,
    7700            2 :                 Vec::new(), // delta layers
    7701            2 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7702            2 :                 Lsn(0x30),
    7703            2 :             )
    7704            2 :             .await
    7705            2 :             .unwrap();
    7706            2 : 
    7707            2 :         let lsn = Lsn(0x30);
    7708            2 : 
    7709            2 :         // test vectored get on parent timeline
    7710            2 :         assert_eq!(
    7711            2 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7712            2 :             Some(test_img("data key 1"))
    7713            2 :         );
    7714            2 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7715            2 :             .await
    7716            2 :             .unwrap_err()
    7717            2 :             .is_missing_key_error());
    7718            2 :         assert!(
    7719            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7720            2 :                 .await
    7721            2 :                 .unwrap_err()
    7722            2 :                 .is_missing_key_error()
    7723            2 :         );
    7724            2 : 
    7725            2 :         // test vectored get on child timeline
    7726            2 :         assert_eq!(
    7727            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7728            2 :             Some(test_img("data key 1"))
    7729            2 :         );
    7730            2 :         assert_eq!(
    7731            2 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7732            2 :             Some(test_img("data key 2"))
    7733            2 :         );
    7734            2 :         assert!(
    7735            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7736            2 :                 .await
    7737            2 :                 .unwrap_err()
    7738            2 :                 .is_missing_key_error()
    7739            2 :         );
    7740            2 : 
    7741            2 :         Ok(())
    7742            2 :     }
    7743              : 
    7744              :     #[tokio::test]
    7745            2 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7746            2 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7747            2 :         let (tenant, ctx) = harness.load().await;
    7748            2 : 
    7749            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7750            2 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7751            2 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7752            2 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7753            2 : 
    7754            2 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    7755            2 :         let base_inherited_key_child =
    7756            2 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    7757            2 :         let base_inherited_key_nonexist =
    7758            2 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    7759            2 :         let base_inherited_key_overwrite =
    7760            2 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    7761            2 : 
    7762            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7763            2 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    7764            2 : 
    7765            2 :         let tline = tenant
    7766            2 :             .create_test_timeline_with_layers(
    7767            2 :                 TIMELINE_ID,
    7768            2 :                 Lsn(0x10),
    7769            2 :                 DEFAULT_PG_VERSION,
    7770            2 :                 &ctx,
    7771            2 :                 Vec::new(), // delta layers
    7772            2 :                 vec![(
    7773            2 :                     Lsn(0x20),
    7774            2 :                     vec![
    7775            2 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    7776            2 :                         (
    7777            2 :                             base_inherited_key_overwrite,
    7778            2 :                             test_img("metadata key overwrite 1a"),
    7779            2 :                         ),
    7780            2 :                         (base_key, test_img("metadata key 1")),
    7781            2 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7782            2 :                     ],
    7783            2 :                 )], // image layers
    7784            2 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7785            2 :             )
    7786            2 :             .await?;
    7787            2 : 
    7788            2 :         let child = tenant
    7789            2 :             .branch_timeline_test_with_layers(
    7790            2 :                 &tline,
    7791            2 :                 NEW_TIMELINE_ID,
    7792            2 :                 Some(Lsn(0x20)),
    7793            2 :                 &ctx,
    7794            2 :                 Vec::new(), // delta layers
    7795            2 :                 vec![(
    7796            2 :                     Lsn(0x30),
    7797            2 :                     vec![
    7798            2 :                         (
    7799            2 :                             base_inherited_key_child,
    7800            2 :                             test_img("metadata inherited key 2"),
    7801            2 :                         ),
    7802            2 :                         (
    7803            2 :                             base_inherited_key_overwrite,
    7804            2 :                             test_img("metadata key overwrite 2a"),
    7805            2 :                         ),
    7806            2 :                         (base_key_child, test_img("metadata key 2")),
    7807            2 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    7808            2 :                     ],
    7809            2 :                 )], // image layers
    7810            2 :                 Lsn(0x30),
    7811            2 :             )
    7812            2 :             .await
    7813            2 :             .unwrap();
    7814            2 : 
    7815            2 :         let lsn = Lsn(0x30);
    7816            2 : 
    7817            2 :         // test vectored get on parent timeline
    7818            2 :         assert_eq!(
    7819            2 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7820            2 :             Some(test_img("metadata key 1"))
    7821            2 :         );
    7822            2 :         assert_eq!(
    7823            2 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7824            2 :             None
    7825            2 :         );
    7826            2 :         assert_eq!(
    7827            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7828            2 :             None
    7829            2 :         );
    7830            2 :         assert_eq!(
    7831            2 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    7832            2 :             Some(test_img("metadata key overwrite 1b"))
    7833            2 :         );
    7834            2 :         assert_eq!(
    7835            2 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    7836            2 :             Some(test_img("metadata inherited key 1"))
    7837            2 :         );
    7838            2 :         assert_eq!(
    7839            2 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    7840            2 :             None
    7841            2 :         );
    7842            2 :         assert_eq!(
    7843            2 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    7844            2 :             None
    7845            2 :         );
    7846            2 :         assert_eq!(
    7847            2 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    7848            2 :             Some(test_img("metadata key overwrite 1a"))
    7849            2 :         );
    7850            2 : 
    7851            2 :         // test vectored get on child timeline
    7852            2 :         assert_eq!(
    7853            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7854            2 :             None
    7855            2 :         );
    7856            2 :         assert_eq!(
    7857            2 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7858            2 :             Some(test_img("metadata key 2"))
    7859            2 :         );
    7860            2 :         assert_eq!(
    7861            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7862            2 :             None
    7863            2 :         );
    7864            2 :         assert_eq!(
    7865            2 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    7866            2 :             Some(test_img("metadata inherited key 1"))
    7867            2 :         );
    7868            2 :         assert_eq!(
    7869            2 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    7870            2 :             Some(test_img("metadata inherited key 2"))
    7871            2 :         );
    7872            2 :         assert_eq!(
    7873            2 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    7874            2 :             None
    7875            2 :         );
    7876            2 :         assert_eq!(
    7877            2 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    7878            2 :             Some(test_img("metadata key overwrite 2b"))
    7879            2 :         );
    7880            2 :         assert_eq!(
    7881            2 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    7882            2 :             Some(test_img("metadata key overwrite 2a"))
    7883            2 :         );
    7884            2 : 
    7885            2 :         // test vectored scan on parent timeline
    7886            2 :         let mut reconstruct_state = ValuesReconstructState::new();
    7887            2 :         let res = tline
    7888            2 :             .get_vectored_impl(
    7889            2 :                 KeySpace::single(Key::metadata_key_range()),
    7890            2 :                 lsn,
    7891            2 :                 &mut reconstruct_state,
    7892            2 :                 &ctx,
    7893            2 :             )
    7894            2 :             .await?;
    7895            2 : 
    7896            2 :         assert_eq!(
    7897            2 :             res.into_iter()
    7898            8 :                 .map(|(k, v)| (k, v.unwrap()))
    7899            2 :                 .collect::<Vec<_>>(),
    7900            2 :             vec![
    7901            2 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    7902            2 :                 (
    7903            2 :                     base_inherited_key_overwrite,
    7904            2 :                     test_img("metadata key overwrite 1a")
    7905            2 :                 ),
    7906            2 :                 (base_key, test_img("metadata key 1")),
    7907            2 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7908            2 :             ]
    7909            2 :         );
    7910            2 : 
    7911            2 :         // test vectored scan on child timeline
    7912            2 :         let mut reconstruct_state = ValuesReconstructState::new();
    7913            2 :         let res = child
    7914            2 :             .get_vectored_impl(
    7915            2 :                 KeySpace::single(Key::metadata_key_range()),
    7916            2 :                 lsn,
    7917            2 :                 &mut reconstruct_state,
    7918            2 :                 &ctx,
    7919            2 :             )
    7920            2 :             .await?;
    7921            2 : 
    7922            2 :         assert_eq!(
    7923            2 :             res.into_iter()
    7924           10 :                 .map(|(k, v)| (k, v.unwrap()))
    7925            2 :                 .collect::<Vec<_>>(),
    7926            2 :             vec![
    7927            2 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    7928            2 :                 (
    7929            2 :                     base_inherited_key_child,
    7930            2 :                     test_img("metadata inherited key 2")
    7931            2 :                 ),
    7932            2 :                 (
    7933            2 :                     base_inherited_key_overwrite,
    7934            2 :                     test_img("metadata key overwrite 2a")
    7935            2 :                 ),
    7936            2 :                 (base_key_child, test_img("metadata key 2")),
    7937            2 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    7938            2 :             ]
    7939            2 :         );
    7940            2 : 
    7941            2 :         Ok(())
    7942            2 :     }
    7943              : 
    7944           56 :     async fn get_vectored_impl_wrapper(
    7945           56 :         tline: &Arc<Timeline>,
    7946           56 :         key: Key,
    7947           56 :         lsn: Lsn,
    7948           56 :         ctx: &RequestContext,
    7949           56 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7950           56 :         let mut reconstruct_state = ValuesReconstructState::new();
    7951           56 :         let mut res = tline
    7952           56 :             .get_vectored_impl(
    7953           56 :                 KeySpace::single(key..key.next()),
    7954           56 :                 lsn,
    7955           56 :                 &mut reconstruct_state,
    7956           56 :                 ctx,
    7957           56 :             )
    7958           56 :             .await?;
    7959           50 :         Ok(res.pop_last().map(|(k, v)| {
    7960           32 :             assert_eq!(k, key);
    7961           32 :             v.unwrap()
    7962           50 :         }))
    7963           56 :     }
    7964              : 
    7965              :     #[tokio::test]
    7966            2 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    7967            2 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    7968            2 :         let (tenant, ctx) = harness.load().await;
    7969            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7970            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7971            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7972            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7973            2 : 
    7974            2 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    7975            2 :         // Lsn 0x30 key0, key3, no key1+key2
    7976            2 :         // Lsn 0x20 key1+key2 tomestones
    7977            2 :         // Lsn 0x10 key1 in image, key2 in delta
    7978            2 :         let tline = tenant
    7979            2 :             .create_test_timeline_with_layers(
    7980            2 :                 TIMELINE_ID,
    7981            2 :                 Lsn(0x10),
    7982            2 :                 DEFAULT_PG_VERSION,
    7983            2 :                 &ctx,
    7984            2 :                 // delta layers
    7985            2 :                 vec![
    7986            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7987            2 :                         Lsn(0x10)..Lsn(0x20),
    7988            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7989            2 :                     ),
    7990            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7991            2 :                         Lsn(0x20)..Lsn(0x30),
    7992            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7993            2 :                     ),
    7994            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7995            2 :                         Lsn(0x20)..Lsn(0x30),
    7996            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7997            2 :                     ),
    7998            2 :                 ],
    7999            2 :                 // image layers
    8000            2 :                 vec![
    8001            2 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8002            2 :                     (
    8003            2 :                         Lsn(0x30),
    8004            2 :                         vec![
    8005            2 :                             (key0, test_img("metadata key 0")),
    8006            2 :                             (key3, test_img("metadata key 3")),
    8007            2 :                         ],
    8008            2 :                     ),
    8009            2 :                 ],
    8010            2 :                 Lsn(0x30),
    8011            2 :             )
    8012            2 :             .await?;
    8013            2 : 
    8014            2 :         let lsn = Lsn(0x30);
    8015            2 :         let old_lsn = Lsn(0x20);
    8016            2 : 
    8017            2 :         assert_eq!(
    8018            2 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8019            2 :             Some(test_img("metadata key 0"))
    8020            2 :         );
    8021            2 :         assert_eq!(
    8022            2 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8023            2 :             None,
    8024            2 :         );
    8025            2 :         assert_eq!(
    8026            2 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8027            2 :             None,
    8028            2 :         );
    8029            2 :         assert_eq!(
    8030            2 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8031            2 :             Some(Bytes::new()),
    8032            2 :         );
    8033            2 :         assert_eq!(
    8034            2 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8035            2 :             Some(Bytes::new()),
    8036            2 :         );
    8037            2 :         assert_eq!(
    8038            2 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8039            2 :             Some(test_img("metadata key 3"))
    8040            2 :         );
    8041            2 : 
    8042            2 :         Ok(())
    8043            2 :     }
    8044              : 
    8045              :     #[tokio::test]
    8046            2 :     async fn test_metadata_tombstone_image_creation() {
    8047            2 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8048            2 :             .await
    8049            2 :             .unwrap();
    8050            2 :         let (tenant, ctx) = harness.load().await;
    8051            2 : 
    8052            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8053            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8054            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8055            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8056            2 : 
    8057            2 :         let tline = tenant
    8058            2 :             .create_test_timeline_with_layers(
    8059            2 :                 TIMELINE_ID,
    8060            2 :                 Lsn(0x10),
    8061            2 :                 DEFAULT_PG_VERSION,
    8062            2 :                 &ctx,
    8063            2 :                 // delta layers
    8064            2 :                 vec![
    8065            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8066            2 :                         Lsn(0x10)..Lsn(0x20),
    8067            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8068            2 :                     ),
    8069            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8070            2 :                         Lsn(0x20)..Lsn(0x30),
    8071            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8072            2 :                     ),
    8073            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8074            2 :                         Lsn(0x20)..Lsn(0x30),
    8075            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8076            2 :                     ),
    8077            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8078            2 :                         Lsn(0x30)..Lsn(0x40),
    8079            2 :                         vec![
    8080            2 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8081            2 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8082            2 :                         ],
    8083            2 :                     ),
    8084            2 :                 ],
    8085            2 :                 // image layers
    8086            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8087            2 :                 Lsn(0x40),
    8088            2 :             )
    8089            2 :             .await
    8090            2 :             .unwrap();
    8091            2 : 
    8092            2 :         let cancel = CancellationToken::new();
    8093            2 : 
    8094            2 :         tline
    8095            2 :             .compact(
    8096            2 :                 &cancel,
    8097            2 :                 {
    8098            2 :                     let mut flags = EnumSet::new();
    8099            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8100            2 :                     flags.insert(CompactFlags::ForceRepartition);
    8101            2 :                     flags
    8102            2 :                 },
    8103            2 :                 &ctx,
    8104            2 :             )
    8105            2 :             .await
    8106            2 :             .unwrap();
    8107            2 : 
    8108            2 :         // Image layers are created at last_record_lsn
    8109            2 :         let images = tline
    8110            2 :             .inspect_image_layers(Lsn(0x40), &ctx)
    8111            2 :             .await
    8112            2 :             .unwrap()
    8113            2 :             .into_iter()
    8114           18 :             .filter(|(k, _)| k.is_metadata_key())
    8115            2 :             .collect::<Vec<_>>();
    8116            2 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8117            2 :     }
    8118              : 
    8119              :     #[tokio::test]
    8120            2 :     async fn test_metadata_tombstone_empty_image_creation() {
    8121            2 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8122            2 :             .await
    8123            2 :             .unwrap();
    8124            2 :         let (tenant, ctx) = harness.load().await;
    8125            2 : 
    8126            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8127            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8128            2 : 
    8129            2 :         let tline = tenant
    8130            2 :             .create_test_timeline_with_layers(
    8131            2 :                 TIMELINE_ID,
    8132            2 :                 Lsn(0x10),
    8133            2 :                 DEFAULT_PG_VERSION,
    8134            2 :                 &ctx,
    8135            2 :                 // delta layers
    8136            2 :                 vec![
    8137            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8138            2 :                         Lsn(0x10)..Lsn(0x20),
    8139            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8140            2 :                     ),
    8141            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8142            2 :                         Lsn(0x20)..Lsn(0x30),
    8143            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8144            2 :                     ),
    8145            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8146            2 :                         Lsn(0x20)..Lsn(0x30),
    8147            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8148            2 :                     ),
    8149            2 :                 ],
    8150            2 :                 // image layers
    8151            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8152            2 :                 Lsn(0x30),
    8153            2 :             )
    8154            2 :             .await
    8155            2 :             .unwrap();
    8156            2 : 
    8157            2 :         let cancel = CancellationToken::new();
    8158            2 : 
    8159            2 :         tline
    8160            2 :             .compact(
    8161            2 :                 &cancel,
    8162            2 :                 {
    8163            2 :                     let mut flags = EnumSet::new();
    8164            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8165            2 :                     flags.insert(CompactFlags::ForceRepartition);
    8166            2 :                     flags
    8167            2 :                 },
    8168            2 :                 &ctx,
    8169            2 :             )
    8170            2 :             .await
    8171            2 :             .unwrap();
    8172            2 : 
    8173            2 :         // Image layers are created at last_record_lsn
    8174            2 :         let images = tline
    8175            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8176            2 :             .await
    8177            2 :             .unwrap()
    8178            2 :             .into_iter()
    8179           14 :             .filter(|(k, _)| k.is_metadata_key())
    8180            2 :             .collect::<Vec<_>>();
    8181            2 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8182            2 :     }
    8183              : 
    8184              :     #[tokio::test]
    8185            2 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8186            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8187            2 :         let (tenant, ctx) = harness.load().await;
    8188            2 : 
    8189          102 :         fn get_key(id: u32) -> Key {
    8190          102 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8191          102 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8192          102 :             key.field6 = id;
    8193          102 :             key
    8194          102 :         }
    8195            2 : 
    8196            2 :         // We create
    8197            2 :         // - one bottom-most image layer,
    8198            2 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8199            2 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8200            2 :         // - a delta layer D3 above the horizon.
    8201            2 :         //
    8202            2 :         //                             | D3 |
    8203            2 :         //  | D1 |
    8204            2 :         // -|    |-- gc horizon -----------------
    8205            2 :         //  |    |                | D2 |
    8206            2 :         // --------- img layer ------------------
    8207            2 :         //
    8208            2 :         // What we should expact from this compaction is:
    8209            2 :         //                             | D3 |
    8210            2 :         //  | Part of D1 |
    8211            2 :         // --------- img layer with D1+D2 at GC horizon------------------
    8212            2 : 
    8213            2 :         // img layer at 0x10
    8214            2 :         let img_layer = (0..10)
    8215           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8216            2 :             .collect_vec();
    8217            2 : 
    8218            2 :         let delta1 = vec![
    8219            2 :             (
    8220            2 :                 get_key(1),
    8221            2 :                 Lsn(0x20),
    8222            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    8223            2 :             ),
    8224            2 :             (
    8225            2 :                 get_key(2),
    8226            2 :                 Lsn(0x30),
    8227            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    8228            2 :             ),
    8229            2 :             (
    8230            2 :                 get_key(3),
    8231            2 :                 Lsn(0x40),
    8232            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    8233            2 :             ),
    8234            2 :         ];
    8235            2 :         let delta2 = vec![
    8236            2 :             (
    8237            2 :                 get_key(5),
    8238            2 :                 Lsn(0x20),
    8239            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    8240            2 :             ),
    8241            2 :             (
    8242            2 :                 get_key(6),
    8243            2 :                 Lsn(0x20),
    8244            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    8245            2 :             ),
    8246            2 :         ];
    8247            2 :         let delta3 = vec![
    8248            2 :             (
    8249            2 :                 get_key(8),
    8250            2 :                 Lsn(0x48),
    8251            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    8252            2 :             ),
    8253            2 :             (
    8254            2 :                 get_key(9),
    8255            2 :                 Lsn(0x48),
    8256            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    8257            2 :             ),
    8258            2 :         ];
    8259            2 : 
    8260            2 :         let tline = tenant
    8261            2 :             .create_test_timeline_with_layers(
    8262            2 :                 TIMELINE_ID,
    8263            2 :                 Lsn(0x10),
    8264            2 :                 DEFAULT_PG_VERSION,
    8265            2 :                 &ctx,
    8266            2 :                 vec![
    8267            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8268            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8269            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8270            2 :                 ], // delta layers
    8271            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8272            2 :                 Lsn(0x50),
    8273            2 :             )
    8274            2 :             .await?;
    8275            2 :         {
    8276            2 :             tline
    8277            2 :                 .latest_gc_cutoff_lsn
    8278            2 :                 .lock_for_write()
    8279            2 :                 .store_and_unlock(Lsn(0x30))
    8280            2 :                 .wait()
    8281            2 :                 .await;
    8282            2 :             // Update GC info
    8283            2 :             let mut guard = tline.gc_info.write().unwrap();
    8284            2 :             guard.cutoffs.time = Lsn(0x30);
    8285            2 :             guard.cutoffs.space = Lsn(0x30);
    8286            2 :         }
    8287            2 : 
    8288            2 :         let expected_result = [
    8289            2 :             Bytes::from_static(b"value 0@0x10"),
    8290            2 :             Bytes::from_static(b"value 1@0x20"),
    8291            2 :             Bytes::from_static(b"value 2@0x30"),
    8292            2 :             Bytes::from_static(b"value 3@0x40"),
    8293            2 :             Bytes::from_static(b"value 4@0x10"),
    8294            2 :             Bytes::from_static(b"value 5@0x20"),
    8295            2 :             Bytes::from_static(b"value 6@0x20"),
    8296            2 :             Bytes::from_static(b"value 7@0x10"),
    8297            2 :             Bytes::from_static(b"value 8@0x48"),
    8298            2 :             Bytes::from_static(b"value 9@0x48"),
    8299            2 :         ];
    8300            2 : 
    8301           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8302           20 :             assert_eq!(
    8303           20 :                 tline
    8304           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8305           20 :                     .await
    8306           20 :                     .unwrap(),
    8307            2 :                 expected
    8308            2 :             );
    8309            2 :         }
    8310            2 : 
    8311            2 :         let cancel = CancellationToken::new();
    8312            2 :         tline
    8313            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8314            2 :             .await
    8315            2 :             .unwrap();
    8316            2 : 
    8317           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8318           20 :             assert_eq!(
    8319           20 :                 tline
    8320           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8321           20 :                     .await
    8322           20 :                     .unwrap(),
    8323            2 :                 expected
    8324            2 :             );
    8325            2 :         }
    8326            2 : 
    8327            2 :         // Check if the image layer at the GC horizon contains exactly what we want
    8328            2 :         let image_at_gc_horizon = tline
    8329            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8330            2 :             .await
    8331            2 :             .unwrap()
    8332            2 :             .into_iter()
    8333           34 :             .filter(|(k, _)| k.is_metadata_key())
    8334            2 :             .collect::<Vec<_>>();
    8335            2 : 
    8336            2 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8337            2 :         let expected_result = [
    8338            2 :             Bytes::from_static(b"value 0@0x10"),
    8339            2 :             Bytes::from_static(b"value 1@0x20"),
    8340            2 :             Bytes::from_static(b"value 2@0x30"),
    8341            2 :             Bytes::from_static(b"value 3@0x10"),
    8342            2 :             Bytes::from_static(b"value 4@0x10"),
    8343            2 :             Bytes::from_static(b"value 5@0x20"),
    8344            2 :             Bytes::from_static(b"value 6@0x20"),
    8345            2 :             Bytes::from_static(b"value 7@0x10"),
    8346            2 :             Bytes::from_static(b"value 8@0x10"),
    8347            2 :             Bytes::from_static(b"value 9@0x10"),
    8348            2 :         ];
    8349           22 :         for idx in 0..10 {
    8350           20 :             assert_eq!(
    8351           20 :                 image_at_gc_horizon[idx],
    8352           20 :                 (get_key(idx as u32), expected_result[idx].clone())
    8353           20 :             );
    8354            2 :         }
    8355            2 : 
    8356            2 :         // Check if old layers are removed / new layers have the expected LSN
    8357            2 :         let all_layers = inspect_and_sort(&tline, None).await;
    8358            2 :         assert_eq!(
    8359            2 :             all_layers,
    8360            2 :             vec![
    8361            2 :                 // Image layer at GC horizon
    8362            2 :                 PersistentLayerKey {
    8363            2 :                     key_range: Key::MIN..Key::MAX,
    8364            2 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8365            2 :                     is_delta: false
    8366            2 :                 },
    8367            2 :                 // The delta layer below the horizon
    8368            2 :                 PersistentLayerKey {
    8369            2 :                     key_range: get_key(3)..get_key(4),
    8370            2 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8371            2 :                     is_delta: true
    8372            2 :                 },
    8373            2 :                 // The delta3 layer that should not be picked for the compaction
    8374            2 :                 PersistentLayerKey {
    8375            2 :                     key_range: get_key(8)..get_key(10),
    8376            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8377            2 :                     is_delta: true
    8378            2 :                 }
    8379            2 :             ]
    8380            2 :         );
    8381            2 : 
    8382            2 :         // increase GC horizon and compact again
    8383            2 :         {
    8384            2 :             tline
    8385            2 :                 .latest_gc_cutoff_lsn
    8386            2 :                 .lock_for_write()
    8387            2 :                 .store_and_unlock(Lsn(0x40))
    8388            2 :                 .wait()
    8389            2 :                 .await;
    8390            2 :             // Update GC info
    8391            2 :             let mut guard = tline.gc_info.write().unwrap();
    8392            2 :             guard.cutoffs.time = Lsn(0x40);
    8393            2 :             guard.cutoffs.space = Lsn(0x40);
    8394            2 :         }
    8395            2 :         tline
    8396            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8397            2 :             .await
    8398            2 :             .unwrap();
    8399            2 : 
    8400            2 :         Ok(())
    8401            2 :     }
    8402              : 
    8403              :     #[cfg(feature = "testing")]
    8404              :     #[tokio::test]
    8405            2 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8406            2 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8407            2 :         let (tenant, ctx) = harness.load().await;
    8408            2 : 
    8409           24 :         fn get_key(id: u32) -> Key {
    8410           24 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8411           24 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8412           24 :             key.field6 = id;
    8413           24 :             key
    8414           24 :         }
    8415            2 : 
    8416            2 :         let delta1 = vec![
    8417            2 :             (
    8418            2 :                 get_key(1),
    8419            2 :                 Lsn(0x20),
    8420            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8421            2 :             ),
    8422            2 :             (
    8423            2 :                 get_key(1),
    8424            2 :                 Lsn(0x30),
    8425            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8426            2 :             ),
    8427            2 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8428            2 :             (
    8429            2 :                 get_key(2),
    8430            2 :                 Lsn(0x20),
    8431            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8432            2 :             ),
    8433            2 :             (
    8434            2 :                 get_key(2),
    8435            2 :                 Lsn(0x30),
    8436            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8437            2 :             ),
    8438            2 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8439            2 :             (
    8440            2 :                 get_key(3),
    8441            2 :                 Lsn(0x20),
    8442            2 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8443            2 :             ),
    8444            2 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8445            2 :             (
    8446            2 :                 get_key(4),
    8447            2 :                 Lsn(0x20),
    8448            2 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8449            2 :             ),
    8450            2 :         ];
    8451            2 :         let image1 = vec![(get_key(1), "0x10".into())];
    8452            2 : 
    8453            2 :         let tline = tenant
    8454            2 :             .create_test_timeline_with_layers(
    8455            2 :                 TIMELINE_ID,
    8456            2 :                 Lsn(0x10),
    8457            2 :                 DEFAULT_PG_VERSION,
    8458            2 :                 &ctx,
    8459            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8460            2 :                     Lsn(0x10)..Lsn(0x40),
    8461            2 :                     delta1,
    8462            2 :                 )], // delta layers
    8463            2 :                 vec![(Lsn(0x10), image1)], // image layers
    8464            2 :                 Lsn(0x50),
    8465            2 :             )
    8466            2 :             .await?;
    8467            2 : 
    8468            2 :         assert_eq!(
    8469            2 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8470            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8471            2 :         );
    8472            2 :         assert_eq!(
    8473            2 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8474            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8475            2 :         );
    8476            2 : 
    8477            2 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8478            2 : 
    8479            2 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8480            2 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8481            2 : 
    8482            2 :         Ok(())
    8483            2 :     }
    8484              : 
    8485              :     #[tokio::test(start_paused = true)]
    8486            2 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8487            2 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8488            2 :             .await
    8489            2 :             .unwrap()
    8490            2 :             .load()
    8491            2 :             .await;
    8492            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8493            2 :         // initial transition into AttachedSingle.
    8494            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8495            2 :         tokio::time::resume();
    8496            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8497            2 : 
    8498            2 :         let end_lsn = Lsn(0x100);
    8499            2 :         let image_layers = (0x20..=0x90)
    8500            2 :             .step_by(0x10)
    8501           16 :             .map(|n| {
    8502           16 :                 (
    8503           16 :                     Lsn(n),
    8504           16 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8505           16 :                 )
    8506           16 :             })
    8507            2 :             .collect();
    8508            2 : 
    8509            2 :         let timeline = tenant
    8510            2 :             .create_test_timeline_with_layers(
    8511            2 :                 TIMELINE_ID,
    8512            2 :                 Lsn(0x10),
    8513            2 :                 DEFAULT_PG_VERSION,
    8514            2 :                 &ctx,
    8515            2 :                 Vec::new(),
    8516            2 :                 image_layers,
    8517            2 :                 end_lsn,
    8518            2 :             )
    8519            2 :             .await?;
    8520            2 : 
    8521            2 :         let leased_lsns = [0x30, 0x50, 0x70];
    8522            2 :         let mut leases = Vec::new();
    8523            6 :         leased_lsns.iter().for_each(|n| {
    8524            6 :             leases.push(
    8525            6 :                 timeline
    8526            6 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8527            6 :                     .expect("lease request should succeed"),
    8528            6 :             );
    8529            6 :         });
    8530            2 : 
    8531            2 :         let updated_lease_0 = timeline
    8532            2 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8533            2 :             .expect("lease renewal should succeed");
    8534            2 :         assert_eq!(
    8535            2 :             updated_lease_0.valid_until, leases[0].valid_until,
    8536            2 :             " Renewing with shorter lease should not change the lease."
    8537            2 :         );
    8538            2 : 
    8539            2 :         let updated_lease_1 = timeline
    8540            2 :             .renew_lsn_lease(
    8541            2 :                 Lsn(leased_lsns[1]),
    8542            2 :                 timeline.get_lsn_lease_length() * 2,
    8543            2 :                 &ctx,
    8544            2 :             )
    8545            2 :             .expect("lease renewal should succeed");
    8546            2 :         assert!(
    8547            2 :             updated_lease_1.valid_until > leases[1].valid_until,
    8548            2 :             "Renewing with a long lease should renew lease with later expiration time."
    8549            2 :         );
    8550            2 : 
    8551            2 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8552            2 :         info!(
    8553            2 :             "latest_gc_cutoff_lsn: {}",
    8554            0 :             *timeline.get_latest_gc_cutoff_lsn()
    8555            2 :         );
    8556            2 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8557            2 : 
    8558            2 :         let res = tenant
    8559            2 :             .gc_iteration(
    8560            2 :                 Some(TIMELINE_ID),
    8561            2 :                 0,
    8562            2 :                 Duration::ZERO,
    8563            2 :                 &CancellationToken::new(),
    8564            2 :                 &ctx,
    8565            2 :             )
    8566            2 :             .await
    8567            2 :             .unwrap();
    8568            2 : 
    8569            2 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8570            2 :         // 0/10: initdb layer
    8571            2 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8572            2 :         assert_eq!(res.layers_needed_by_leases, 7);
    8573            2 :         // Keeping 0/90 b/c it is the latest layer.
    8574            2 :         assert_eq!(res.layers_not_updated, 1);
    8575            2 :         // Removed 0/80.
    8576            2 :         assert_eq!(res.layers_removed, 1);
    8577            2 : 
    8578            2 :         // Make lease on a already GC-ed LSN.
    8579            2 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8580            2 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    8581            2 :         timeline
    8582            2 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8583            2 :             .expect_err("lease request on GC-ed LSN should fail");
    8584            2 : 
    8585            2 :         // Should still be able to renew a currently valid lease
    8586            2 :         // Assumption: original lease to is still valid for 0/50.
    8587            2 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8588            2 :         timeline
    8589            2 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8590            2 :             .expect("lease renewal with validation should succeed");
    8591            2 : 
    8592            2 :         Ok(())
    8593            2 :     }
    8594              : 
    8595              :     #[cfg(feature = "testing")]
    8596              :     #[tokio::test]
    8597            2 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8598            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8599            2 :             "test_simple_bottom_most_compaction_deltas_1",
    8600            2 :             false,
    8601            2 :         )
    8602            2 :         .await
    8603            2 :     }
    8604              : 
    8605              :     #[cfg(feature = "testing")]
    8606              :     #[tokio::test]
    8607            2 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8608            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8609            2 :             "test_simple_bottom_most_compaction_deltas_2",
    8610            2 :             true,
    8611            2 :         )
    8612            2 :         .await
    8613            2 :     }
    8614              : 
    8615              :     #[cfg(feature = "testing")]
    8616            4 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8617            4 :         test_name: &'static str,
    8618            4 :         use_delta_bottom_layer: bool,
    8619            4 :     ) -> anyhow::Result<()> {
    8620            4 :         let harness = TenantHarness::create(test_name).await?;
    8621            4 :         let (tenant, ctx) = harness.load().await;
    8622              : 
    8623          276 :         fn get_key(id: u32) -> Key {
    8624          276 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8625          276 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8626          276 :             key.field6 = id;
    8627          276 :             key
    8628          276 :         }
    8629              : 
    8630              :         // We create
    8631              :         // - one bottom-most image layer,
    8632              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8633              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8634              :         // - a delta layer D3 above the horizon.
    8635              :         //
    8636              :         //                             | D3 |
    8637              :         //  | D1 |
    8638              :         // -|    |-- gc horizon -----------------
    8639              :         //  |    |                | D2 |
    8640              :         // --------- img layer ------------------
    8641              :         //
    8642              :         // What we should expact from this compaction is:
    8643              :         //                             | D3 |
    8644              :         //  | Part of D1 |
    8645              :         // --------- img layer with D1+D2 at GC horizon------------------
    8646              : 
    8647              :         // img layer at 0x10
    8648            4 :         let img_layer = (0..10)
    8649           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8650            4 :             .collect_vec();
    8651            4 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8652            4 :         let delta4 = (0..10)
    8653           40 :             .map(|id| {
    8654           40 :                 (
    8655           40 :                     get_key(id),
    8656           40 :                     Lsn(0x08),
    8657           40 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8658           40 :                 )
    8659           40 :             })
    8660            4 :             .collect_vec();
    8661            4 : 
    8662            4 :         let delta1 = vec![
    8663            4 :             (
    8664            4 :                 get_key(1),
    8665            4 :                 Lsn(0x20),
    8666            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8667            4 :             ),
    8668            4 :             (
    8669            4 :                 get_key(2),
    8670            4 :                 Lsn(0x30),
    8671            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8672            4 :             ),
    8673            4 :             (
    8674            4 :                 get_key(3),
    8675            4 :                 Lsn(0x28),
    8676            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8677            4 :             ),
    8678            4 :             (
    8679            4 :                 get_key(3),
    8680            4 :                 Lsn(0x30),
    8681            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8682            4 :             ),
    8683            4 :             (
    8684            4 :                 get_key(3),
    8685            4 :                 Lsn(0x40),
    8686            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8687            4 :             ),
    8688            4 :         ];
    8689            4 :         let delta2 = vec![
    8690            4 :             (
    8691            4 :                 get_key(5),
    8692            4 :                 Lsn(0x20),
    8693            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8694            4 :             ),
    8695            4 :             (
    8696            4 :                 get_key(6),
    8697            4 :                 Lsn(0x20),
    8698            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8699            4 :             ),
    8700            4 :         ];
    8701            4 :         let delta3 = vec![
    8702            4 :             (
    8703            4 :                 get_key(8),
    8704            4 :                 Lsn(0x48),
    8705            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8706            4 :             ),
    8707            4 :             (
    8708            4 :                 get_key(9),
    8709            4 :                 Lsn(0x48),
    8710            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8711            4 :             ),
    8712            4 :         ];
    8713              : 
    8714            4 :         let tline = if use_delta_bottom_layer {
    8715            2 :             tenant
    8716            2 :                 .create_test_timeline_with_layers(
    8717            2 :                     TIMELINE_ID,
    8718            2 :                     Lsn(0x08),
    8719            2 :                     DEFAULT_PG_VERSION,
    8720            2 :                     &ctx,
    8721            2 :                     vec![
    8722            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8723            2 :                             Lsn(0x08)..Lsn(0x10),
    8724            2 :                             delta4,
    8725            2 :                         ),
    8726            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8727            2 :                             Lsn(0x20)..Lsn(0x48),
    8728            2 :                             delta1,
    8729            2 :                         ),
    8730            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8731            2 :                             Lsn(0x20)..Lsn(0x48),
    8732            2 :                             delta2,
    8733            2 :                         ),
    8734            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8735            2 :                             Lsn(0x48)..Lsn(0x50),
    8736            2 :                             delta3,
    8737            2 :                         ),
    8738            2 :                     ], // delta layers
    8739            2 :                     vec![], // image layers
    8740            2 :                     Lsn(0x50),
    8741            2 :                 )
    8742            2 :                 .await?
    8743              :         } else {
    8744            2 :             tenant
    8745            2 :                 .create_test_timeline_with_layers(
    8746            2 :                     TIMELINE_ID,
    8747            2 :                     Lsn(0x10),
    8748            2 :                     DEFAULT_PG_VERSION,
    8749            2 :                     &ctx,
    8750            2 :                     vec![
    8751            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8752            2 :                             Lsn(0x10)..Lsn(0x48),
    8753            2 :                             delta1,
    8754            2 :                         ),
    8755            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8756            2 :                             Lsn(0x10)..Lsn(0x48),
    8757            2 :                             delta2,
    8758            2 :                         ),
    8759            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8760            2 :                             Lsn(0x48)..Lsn(0x50),
    8761            2 :                             delta3,
    8762            2 :                         ),
    8763            2 :                     ], // delta layers
    8764            2 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8765            2 :                     Lsn(0x50),
    8766            2 :                 )
    8767            2 :                 .await?
    8768              :         };
    8769              :         {
    8770            4 :             tline
    8771            4 :                 .latest_gc_cutoff_lsn
    8772            4 :                 .lock_for_write()
    8773            4 :                 .store_and_unlock(Lsn(0x30))
    8774            4 :                 .wait()
    8775            4 :                 .await;
    8776              :             // Update GC info
    8777            4 :             let mut guard = tline.gc_info.write().unwrap();
    8778            4 :             *guard = GcInfo {
    8779            4 :                 retain_lsns: vec![],
    8780            4 :                 cutoffs: GcCutoffs {
    8781            4 :                     time: Lsn(0x30),
    8782            4 :                     space: Lsn(0x30),
    8783            4 :                 },
    8784            4 :                 leases: Default::default(),
    8785            4 :                 within_ancestor_pitr: false,
    8786            4 :             };
    8787            4 :         }
    8788            4 : 
    8789            4 :         let expected_result = [
    8790            4 :             Bytes::from_static(b"value 0@0x10"),
    8791            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8792            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8793            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8794            4 :             Bytes::from_static(b"value 4@0x10"),
    8795            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8796            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8797            4 :             Bytes::from_static(b"value 7@0x10"),
    8798            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8799            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8800            4 :         ];
    8801            4 : 
    8802            4 :         let expected_result_at_gc_horizon = [
    8803            4 :             Bytes::from_static(b"value 0@0x10"),
    8804            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8805            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8806            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8807            4 :             Bytes::from_static(b"value 4@0x10"),
    8808            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8809            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8810            4 :             Bytes::from_static(b"value 7@0x10"),
    8811            4 :             Bytes::from_static(b"value 8@0x10"),
    8812            4 :             Bytes::from_static(b"value 9@0x10"),
    8813            4 :         ];
    8814              : 
    8815           44 :         for idx in 0..10 {
    8816           40 :             assert_eq!(
    8817           40 :                 tline
    8818           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8819           40 :                     .await
    8820           40 :                     .unwrap(),
    8821           40 :                 &expected_result[idx]
    8822              :             );
    8823           40 :             assert_eq!(
    8824           40 :                 tline
    8825           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8826           40 :                     .await
    8827           40 :                     .unwrap(),
    8828           40 :                 &expected_result_at_gc_horizon[idx]
    8829              :             );
    8830              :         }
    8831              : 
    8832            4 :         let cancel = CancellationToken::new();
    8833            4 :         tline
    8834            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8835            4 :             .await
    8836            4 :             .unwrap();
    8837              : 
    8838           44 :         for idx in 0..10 {
    8839           40 :             assert_eq!(
    8840           40 :                 tline
    8841           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8842           40 :                     .await
    8843           40 :                     .unwrap(),
    8844           40 :                 &expected_result[idx]
    8845              :             );
    8846           40 :             assert_eq!(
    8847           40 :                 tline
    8848           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8849           40 :                     .await
    8850           40 :                     .unwrap(),
    8851           40 :                 &expected_result_at_gc_horizon[idx]
    8852              :             );
    8853              :         }
    8854              : 
    8855              :         // increase GC horizon and compact again
    8856              :         {
    8857            4 :             tline
    8858            4 :                 .latest_gc_cutoff_lsn
    8859            4 :                 .lock_for_write()
    8860            4 :                 .store_and_unlock(Lsn(0x40))
    8861            4 :                 .wait()
    8862            4 :                 .await;
    8863              :             // Update GC info
    8864            4 :             let mut guard = tline.gc_info.write().unwrap();
    8865            4 :             guard.cutoffs.time = Lsn(0x40);
    8866            4 :             guard.cutoffs.space = Lsn(0x40);
    8867            4 :         }
    8868            4 :         tline
    8869            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8870            4 :             .await
    8871            4 :             .unwrap();
    8872            4 : 
    8873            4 :         Ok(())
    8874            4 :     }
    8875              : 
    8876              :     #[cfg(feature = "testing")]
    8877              :     #[tokio::test]
    8878            2 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8879            2 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8880            2 :         let (tenant, ctx) = harness.load().await;
    8881            2 :         let tline = tenant
    8882            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8883            2 :             .await?;
    8884            2 :         tline.force_advance_lsn(Lsn(0x70));
    8885            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8886            2 :         let history = vec![
    8887            2 :             (
    8888            2 :                 key,
    8889            2 :                 Lsn(0x10),
    8890            2 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8891            2 :             ),
    8892            2 :             (
    8893            2 :                 key,
    8894            2 :                 Lsn(0x20),
    8895            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8896            2 :             ),
    8897            2 :             (
    8898            2 :                 key,
    8899            2 :                 Lsn(0x30),
    8900            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8901            2 :             ),
    8902            2 :             (
    8903            2 :                 key,
    8904            2 :                 Lsn(0x40),
    8905            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8906            2 :             ),
    8907            2 :             (
    8908            2 :                 key,
    8909            2 :                 Lsn(0x50),
    8910            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8911            2 :             ),
    8912            2 :             (
    8913            2 :                 key,
    8914            2 :                 Lsn(0x60),
    8915            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8916            2 :             ),
    8917            2 :             (
    8918            2 :                 key,
    8919            2 :                 Lsn(0x70),
    8920            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8921            2 :             ),
    8922            2 :             (
    8923            2 :                 key,
    8924            2 :                 Lsn(0x80),
    8925            2 :                 Value::Image(Bytes::copy_from_slice(
    8926            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8927            2 :                 )),
    8928            2 :             ),
    8929            2 :             (
    8930            2 :                 key,
    8931            2 :                 Lsn(0x90),
    8932            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8933            2 :             ),
    8934            2 :         ];
    8935            2 :         let res = tline
    8936            2 :             .generate_key_retention(
    8937            2 :                 key,
    8938            2 :                 &history,
    8939            2 :                 Lsn(0x60),
    8940            2 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8941            2 :                 3,
    8942            2 :                 None,
    8943            2 :             )
    8944            2 :             .await
    8945            2 :             .unwrap();
    8946            2 :         let expected_res = KeyHistoryRetention {
    8947            2 :             below_horizon: vec![
    8948            2 :                 (
    8949            2 :                     Lsn(0x20),
    8950            2 :                     KeyLogAtLsn(vec![(
    8951            2 :                         Lsn(0x20),
    8952            2 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8953            2 :                     )]),
    8954            2 :                 ),
    8955            2 :                 (
    8956            2 :                     Lsn(0x40),
    8957            2 :                     KeyLogAtLsn(vec![
    8958            2 :                         (
    8959            2 :                             Lsn(0x30),
    8960            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8961            2 :                         ),
    8962            2 :                         (
    8963            2 :                             Lsn(0x40),
    8964            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8965            2 :                         ),
    8966            2 :                     ]),
    8967            2 :                 ),
    8968            2 :                 (
    8969            2 :                     Lsn(0x50),
    8970            2 :                     KeyLogAtLsn(vec![(
    8971            2 :                         Lsn(0x50),
    8972            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    8973            2 :                     )]),
    8974            2 :                 ),
    8975            2 :                 (
    8976            2 :                     Lsn(0x60),
    8977            2 :                     KeyLogAtLsn(vec![(
    8978            2 :                         Lsn(0x60),
    8979            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8980            2 :                     )]),
    8981            2 :                 ),
    8982            2 :             ],
    8983            2 :             above_horizon: KeyLogAtLsn(vec![
    8984            2 :                 (
    8985            2 :                     Lsn(0x70),
    8986            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8987            2 :                 ),
    8988            2 :                 (
    8989            2 :                     Lsn(0x80),
    8990            2 :                     Value::Image(Bytes::copy_from_slice(
    8991            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8992            2 :                     )),
    8993            2 :                 ),
    8994            2 :                 (
    8995            2 :                     Lsn(0x90),
    8996            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8997            2 :                 ),
    8998            2 :             ]),
    8999            2 :         };
    9000            2 :         assert_eq!(res, expected_res);
    9001            2 : 
    9002            2 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9003            2 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9004            2 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9005            2 :         // For example, we have
    9006            2 :         // ```plain
    9007            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9008            2 :         // ```
    9009            2 :         // Now the GC horizon moves up, and we have
    9010            2 :         // ```plain
    9011            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9012            2 :         // ```
    9013            2 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9014            2 :         // We will end up with
    9015            2 :         // ```plain
    9016            2 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9017            2 :         // ```
    9018            2 :         // Now we run the GC-compaction, and this key does not have a full history.
    9019            2 :         // We should be able to handle this partial history and drop everything before the
    9020            2 :         // gc_horizon image.
    9021            2 : 
    9022            2 :         let history = vec![
    9023            2 :             (
    9024            2 :                 key,
    9025            2 :                 Lsn(0x20),
    9026            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9027            2 :             ),
    9028            2 :             (
    9029            2 :                 key,
    9030            2 :                 Lsn(0x30),
    9031            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9032            2 :             ),
    9033            2 :             (
    9034            2 :                 key,
    9035            2 :                 Lsn(0x40),
    9036            2 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9037            2 :             ),
    9038            2 :             (
    9039            2 :                 key,
    9040            2 :                 Lsn(0x50),
    9041            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9042            2 :             ),
    9043            2 :             (
    9044            2 :                 key,
    9045            2 :                 Lsn(0x60),
    9046            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9047            2 :             ),
    9048            2 :             (
    9049            2 :                 key,
    9050            2 :                 Lsn(0x70),
    9051            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9052            2 :             ),
    9053            2 :             (
    9054            2 :                 key,
    9055            2 :                 Lsn(0x80),
    9056            2 :                 Value::Image(Bytes::copy_from_slice(
    9057            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9058            2 :                 )),
    9059            2 :             ),
    9060            2 :             (
    9061            2 :                 key,
    9062            2 :                 Lsn(0x90),
    9063            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9064            2 :             ),
    9065            2 :         ];
    9066            2 :         let res = tline
    9067            2 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9068            2 :             .await
    9069            2 :             .unwrap();
    9070            2 :         let expected_res = KeyHistoryRetention {
    9071            2 :             below_horizon: vec![
    9072            2 :                 (
    9073            2 :                     Lsn(0x40),
    9074            2 :                     KeyLogAtLsn(vec![(
    9075            2 :                         Lsn(0x40),
    9076            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9077            2 :                     )]),
    9078            2 :                 ),
    9079            2 :                 (
    9080            2 :                     Lsn(0x50),
    9081            2 :                     KeyLogAtLsn(vec![(
    9082            2 :                         Lsn(0x50),
    9083            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9084            2 :                     )]),
    9085            2 :                 ),
    9086            2 :                 (
    9087            2 :                     Lsn(0x60),
    9088            2 :                     KeyLogAtLsn(vec![(
    9089            2 :                         Lsn(0x60),
    9090            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9091            2 :                     )]),
    9092            2 :                 ),
    9093            2 :             ],
    9094            2 :             above_horizon: KeyLogAtLsn(vec![
    9095            2 :                 (
    9096            2 :                     Lsn(0x70),
    9097            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9098            2 :                 ),
    9099            2 :                 (
    9100            2 :                     Lsn(0x80),
    9101            2 :                     Value::Image(Bytes::copy_from_slice(
    9102            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9103            2 :                     )),
    9104            2 :                 ),
    9105            2 :                 (
    9106            2 :                     Lsn(0x90),
    9107            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9108            2 :                 ),
    9109            2 :             ]),
    9110            2 :         };
    9111            2 :         assert_eq!(res, expected_res);
    9112            2 : 
    9113            2 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9114            2 :         // the ancestor image in the test case.
    9115            2 : 
    9116            2 :         let history = vec![
    9117            2 :             (
    9118            2 :                 key,
    9119            2 :                 Lsn(0x20),
    9120            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9121            2 :             ),
    9122            2 :             (
    9123            2 :                 key,
    9124            2 :                 Lsn(0x30),
    9125            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9126            2 :             ),
    9127            2 :             (
    9128            2 :                 key,
    9129            2 :                 Lsn(0x40),
    9130            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9131            2 :             ),
    9132            2 :             (
    9133            2 :                 key,
    9134            2 :                 Lsn(0x70),
    9135            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9136            2 :             ),
    9137            2 :         ];
    9138            2 :         let res = tline
    9139            2 :             .generate_key_retention(
    9140            2 :                 key,
    9141            2 :                 &history,
    9142            2 :                 Lsn(0x60),
    9143            2 :                 &[],
    9144            2 :                 3,
    9145            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9146            2 :             )
    9147            2 :             .await
    9148            2 :             .unwrap();
    9149            2 :         let expected_res = KeyHistoryRetention {
    9150            2 :             below_horizon: vec![(
    9151            2 :                 Lsn(0x60),
    9152            2 :                 KeyLogAtLsn(vec![(
    9153            2 :                     Lsn(0x60),
    9154            2 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9155            2 :                 )]),
    9156            2 :             )],
    9157            2 :             above_horizon: KeyLogAtLsn(vec![(
    9158            2 :                 Lsn(0x70),
    9159            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9160            2 :             )]),
    9161            2 :         };
    9162            2 :         assert_eq!(res, expected_res);
    9163            2 : 
    9164            2 :         let history = vec![
    9165            2 :             (
    9166            2 :                 key,
    9167            2 :                 Lsn(0x20),
    9168            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9169            2 :             ),
    9170            2 :             (
    9171            2 :                 key,
    9172            2 :                 Lsn(0x40),
    9173            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9174            2 :             ),
    9175            2 :             (
    9176            2 :                 key,
    9177            2 :                 Lsn(0x60),
    9178            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9179            2 :             ),
    9180            2 :             (
    9181            2 :                 key,
    9182            2 :                 Lsn(0x70),
    9183            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9184            2 :             ),
    9185            2 :         ];
    9186            2 :         let res = tline
    9187            2 :             .generate_key_retention(
    9188            2 :                 key,
    9189            2 :                 &history,
    9190            2 :                 Lsn(0x60),
    9191            2 :                 &[Lsn(0x30)],
    9192            2 :                 3,
    9193            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9194            2 :             )
    9195            2 :             .await
    9196            2 :             .unwrap();
    9197            2 :         let expected_res = KeyHistoryRetention {
    9198            2 :             below_horizon: vec![
    9199            2 :                 (
    9200            2 :                     Lsn(0x30),
    9201            2 :                     KeyLogAtLsn(vec![(
    9202            2 :                         Lsn(0x20),
    9203            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9204            2 :                     )]),
    9205            2 :                 ),
    9206            2 :                 (
    9207            2 :                     Lsn(0x60),
    9208            2 :                     KeyLogAtLsn(vec![(
    9209            2 :                         Lsn(0x60),
    9210            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9211            2 :                     )]),
    9212            2 :                 ),
    9213            2 :             ],
    9214            2 :             above_horizon: KeyLogAtLsn(vec![(
    9215            2 :                 Lsn(0x70),
    9216            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9217            2 :             )]),
    9218            2 :         };
    9219            2 :         assert_eq!(res, expected_res);
    9220            2 : 
    9221            2 :         Ok(())
    9222            2 :     }
    9223              : 
    9224              :     #[cfg(feature = "testing")]
    9225              :     #[tokio::test]
    9226            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9227            2 :         let harness =
    9228            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9229            2 :         let (tenant, ctx) = harness.load().await;
    9230            2 : 
    9231          518 :         fn get_key(id: u32) -> Key {
    9232          518 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9233          518 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9234          518 :             key.field6 = id;
    9235          518 :             key
    9236          518 :         }
    9237            2 : 
    9238            2 :         let img_layer = (0..10)
    9239           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9240            2 :             .collect_vec();
    9241            2 : 
    9242            2 :         let delta1 = vec![
    9243            2 :             (
    9244            2 :                 get_key(1),
    9245            2 :                 Lsn(0x20),
    9246            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9247            2 :             ),
    9248            2 :             (
    9249            2 :                 get_key(2),
    9250            2 :                 Lsn(0x30),
    9251            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9252            2 :             ),
    9253            2 :             (
    9254            2 :                 get_key(3),
    9255            2 :                 Lsn(0x28),
    9256            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9257            2 :             ),
    9258            2 :             (
    9259            2 :                 get_key(3),
    9260            2 :                 Lsn(0x30),
    9261            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9262            2 :             ),
    9263            2 :             (
    9264            2 :                 get_key(3),
    9265            2 :                 Lsn(0x40),
    9266            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9267            2 :             ),
    9268            2 :         ];
    9269            2 :         let delta2 = vec![
    9270            2 :             (
    9271            2 :                 get_key(5),
    9272            2 :                 Lsn(0x20),
    9273            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9274            2 :             ),
    9275            2 :             (
    9276            2 :                 get_key(6),
    9277            2 :                 Lsn(0x20),
    9278            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9279            2 :             ),
    9280            2 :         ];
    9281            2 :         let delta3 = vec![
    9282            2 :             (
    9283            2 :                 get_key(8),
    9284            2 :                 Lsn(0x48),
    9285            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9286            2 :             ),
    9287            2 :             (
    9288            2 :                 get_key(9),
    9289            2 :                 Lsn(0x48),
    9290            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9291            2 :             ),
    9292            2 :         ];
    9293            2 : 
    9294            2 :         let tline = tenant
    9295            2 :             .create_test_timeline_with_layers(
    9296            2 :                 TIMELINE_ID,
    9297            2 :                 Lsn(0x10),
    9298            2 :                 DEFAULT_PG_VERSION,
    9299            2 :                 &ctx,
    9300            2 :                 vec![
    9301            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9302            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9303            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9304            2 :                 ], // delta layers
    9305            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9306            2 :                 Lsn(0x50),
    9307            2 :             )
    9308            2 :             .await?;
    9309            2 :         {
    9310            2 :             tline
    9311            2 :                 .latest_gc_cutoff_lsn
    9312            2 :                 .lock_for_write()
    9313            2 :                 .store_and_unlock(Lsn(0x30))
    9314            2 :                 .wait()
    9315            2 :                 .await;
    9316            2 :             // Update GC info
    9317            2 :             let mut guard = tline.gc_info.write().unwrap();
    9318            2 :             *guard = GcInfo {
    9319            2 :                 retain_lsns: vec![
    9320            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9321            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9322            2 :                 ],
    9323            2 :                 cutoffs: GcCutoffs {
    9324            2 :                     time: Lsn(0x30),
    9325            2 :                     space: Lsn(0x30),
    9326            2 :                 },
    9327            2 :                 leases: Default::default(),
    9328            2 :                 within_ancestor_pitr: false,
    9329            2 :             };
    9330            2 :         }
    9331            2 : 
    9332            2 :         let expected_result = [
    9333            2 :             Bytes::from_static(b"value 0@0x10"),
    9334            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9335            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9336            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9337            2 :             Bytes::from_static(b"value 4@0x10"),
    9338            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9339            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9340            2 :             Bytes::from_static(b"value 7@0x10"),
    9341            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9342            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9343            2 :         ];
    9344            2 : 
    9345            2 :         let expected_result_at_gc_horizon = [
    9346            2 :             Bytes::from_static(b"value 0@0x10"),
    9347            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9348            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9349            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9350            2 :             Bytes::from_static(b"value 4@0x10"),
    9351            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9352            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9353            2 :             Bytes::from_static(b"value 7@0x10"),
    9354            2 :             Bytes::from_static(b"value 8@0x10"),
    9355            2 :             Bytes::from_static(b"value 9@0x10"),
    9356            2 :         ];
    9357            2 : 
    9358            2 :         let expected_result_at_lsn_20 = [
    9359            2 :             Bytes::from_static(b"value 0@0x10"),
    9360            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9361            2 :             Bytes::from_static(b"value 2@0x10"),
    9362            2 :             Bytes::from_static(b"value 3@0x10"),
    9363            2 :             Bytes::from_static(b"value 4@0x10"),
    9364            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9365            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9366            2 :             Bytes::from_static(b"value 7@0x10"),
    9367            2 :             Bytes::from_static(b"value 8@0x10"),
    9368            2 :             Bytes::from_static(b"value 9@0x10"),
    9369            2 :         ];
    9370            2 : 
    9371            2 :         let expected_result_at_lsn_10 = [
    9372            2 :             Bytes::from_static(b"value 0@0x10"),
    9373            2 :             Bytes::from_static(b"value 1@0x10"),
    9374            2 :             Bytes::from_static(b"value 2@0x10"),
    9375            2 :             Bytes::from_static(b"value 3@0x10"),
    9376            2 :             Bytes::from_static(b"value 4@0x10"),
    9377            2 :             Bytes::from_static(b"value 5@0x10"),
    9378            2 :             Bytes::from_static(b"value 6@0x10"),
    9379            2 :             Bytes::from_static(b"value 7@0x10"),
    9380            2 :             Bytes::from_static(b"value 8@0x10"),
    9381            2 :             Bytes::from_static(b"value 9@0x10"),
    9382            2 :         ];
    9383            2 : 
    9384           12 :         let verify_result = || async {
    9385           12 :             let gc_horizon = {
    9386           12 :                 let gc_info = tline.gc_info.read().unwrap();
    9387           12 :                 gc_info.cutoffs.time
    9388            2 :             };
    9389          132 :             for idx in 0..10 {
    9390          120 :                 assert_eq!(
    9391          120 :                     tline
    9392          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9393          120 :                         .await
    9394          120 :                         .unwrap(),
    9395          120 :                     &expected_result[idx]
    9396            2 :                 );
    9397          120 :                 assert_eq!(
    9398          120 :                     tline
    9399          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9400          120 :                         .await
    9401          120 :                         .unwrap(),
    9402          120 :                     &expected_result_at_gc_horizon[idx]
    9403            2 :                 );
    9404          120 :                 assert_eq!(
    9405          120 :                     tline
    9406          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9407          120 :                         .await
    9408          120 :                         .unwrap(),
    9409          120 :                     &expected_result_at_lsn_20[idx]
    9410            2 :                 );
    9411          120 :                 assert_eq!(
    9412          120 :                     tline
    9413          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9414          120 :                         .await
    9415          120 :                         .unwrap(),
    9416          120 :                     &expected_result_at_lsn_10[idx]
    9417            2 :                 );
    9418            2 :             }
    9419           24 :         };
    9420            2 : 
    9421            2 :         verify_result().await;
    9422            2 : 
    9423            2 :         let cancel = CancellationToken::new();
    9424            2 :         let mut dryrun_flags = EnumSet::new();
    9425            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9426            2 : 
    9427            2 :         tline
    9428            2 :             .compact_with_gc(
    9429            2 :                 &cancel,
    9430            2 :                 CompactOptions {
    9431            2 :                     flags: dryrun_flags,
    9432            2 :                     ..Default::default()
    9433            2 :                 },
    9434            2 :                 &ctx,
    9435            2 :             )
    9436            2 :             .await
    9437            2 :             .unwrap();
    9438            2 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9439            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9440            2 :         verify_result().await;
    9441            2 : 
    9442            2 :         tline
    9443            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9444            2 :             .await
    9445            2 :             .unwrap();
    9446            2 :         verify_result().await;
    9447            2 : 
    9448            2 :         // compact again
    9449            2 :         tline
    9450            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9451            2 :             .await
    9452            2 :             .unwrap();
    9453            2 :         verify_result().await;
    9454            2 : 
    9455            2 :         // increase GC horizon and compact again
    9456            2 :         {
    9457            2 :             tline
    9458            2 :                 .latest_gc_cutoff_lsn
    9459            2 :                 .lock_for_write()
    9460            2 :                 .store_and_unlock(Lsn(0x38))
    9461            2 :                 .wait()
    9462            2 :                 .await;
    9463            2 :             // Update GC info
    9464            2 :             let mut guard = tline.gc_info.write().unwrap();
    9465            2 :             guard.cutoffs.time = Lsn(0x38);
    9466            2 :             guard.cutoffs.space = Lsn(0x38);
    9467            2 :         }
    9468            2 :         tline
    9469            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9470            2 :             .await
    9471            2 :             .unwrap();
    9472            2 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9473            2 : 
    9474            2 :         // not increasing the GC horizon and compact again
    9475            2 :         tline
    9476            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9477            2 :             .await
    9478            2 :             .unwrap();
    9479            2 :         verify_result().await;
    9480            2 : 
    9481            2 :         Ok(())
    9482            2 :     }
    9483              : 
    9484              :     #[cfg(feature = "testing")]
    9485              :     #[tokio::test]
    9486            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9487            2 :     {
    9488            2 :         let harness =
    9489            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9490            2 :                 .await?;
    9491            2 :         let (tenant, ctx) = harness.load().await;
    9492            2 : 
    9493          352 :         fn get_key(id: u32) -> Key {
    9494          352 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9495          352 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9496          352 :             key.field6 = id;
    9497          352 :             key
    9498          352 :         }
    9499            2 : 
    9500            2 :         let img_layer = (0..10)
    9501           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9502            2 :             .collect_vec();
    9503            2 : 
    9504            2 :         let delta1 = vec![
    9505            2 :             (
    9506            2 :                 get_key(1),
    9507            2 :                 Lsn(0x20),
    9508            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9509            2 :             ),
    9510            2 :             (
    9511            2 :                 get_key(1),
    9512            2 :                 Lsn(0x28),
    9513            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9514            2 :             ),
    9515            2 :         ];
    9516            2 :         let delta2 = vec![
    9517            2 :             (
    9518            2 :                 get_key(1),
    9519            2 :                 Lsn(0x30),
    9520            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9521            2 :             ),
    9522            2 :             (
    9523            2 :                 get_key(1),
    9524            2 :                 Lsn(0x38),
    9525            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9526            2 :             ),
    9527            2 :         ];
    9528            2 :         let delta3 = vec![
    9529            2 :             (
    9530            2 :                 get_key(8),
    9531            2 :                 Lsn(0x48),
    9532            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9533            2 :             ),
    9534            2 :             (
    9535            2 :                 get_key(9),
    9536            2 :                 Lsn(0x48),
    9537            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9538            2 :             ),
    9539            2 :         ];
    9540            2 : 
    9541            2 :         let tline = tenant
    9542            2 :             .create_test_timeline_with_layers(
    9543            2 :                 TIMELINE_ID,
    9544            2 :                 Lsn(0x10),
    9545            2 :                 DEFAULT_PG_VERSION,
    9546            2 :                 &ctx,
    9547            2 :                 vec![
    9548            2 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9549            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9550            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9551            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9552            2 :                 ], // delta layers
    9553            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9554            2 :                 Lsn(0x50),
    9555            2 :             )
    9556            2 :             .await?;
    9557            2 :         {
    9558            2 :             tline
    9559            2 :                 .latest_gc_cutoff_lsn
    9560            2 :                 .lock_for_write()
    9561            2 :                 .store_and_unlock(Lsn(0x30))
    9562            2 :                 .wait()
    9563            2 :                 .await;
    9564            2 :             // Update GC info
    9565            2 :             let mut guard = tline.gc_info.write().unwrap();
    9566            2 :             *guard = GcInfo {
    9567            2 :                 retain_lsns: vec![
    9568            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9569            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9570            2 :                 ],
    9571            2 :                 cutoffs: GcCutoffs {
    9572            2 :                     time: Lsn(0x30),
    9573            2 :                     space: Lsn(0x30),
    9574            2 :                 },
    9575            2 :                 leases: Default::default(),
    9576            2 :                 within_ancestor_pitr: false,
    9577            2 :             };
    9578            2 :         }
    9579            2 : 
    9580            2 :         let expected_result = [
    9581            2 :             Bytes::from_static(b"value 0@0x10"),
    9582            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9583            2 :             Bytes::from_static(b"value 2@0x10"),
    9584            2 :             Bytes::from_static(b"value 3@0x10"),
    9585            2 :             Bytes::from_static(b"value 4@0x10"),
    9586            2 :             Bytes::from_static(b"value 5@0x10"),
    9587            2 :             Bytes::from_static(b"value 6@0x10"),
    9588            2 :             Bytes::from_static(b"value 7@0x10"),
    9589            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9590            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9591            2 :         ];
    9592            2 : 
    9593            2 :         let expected_result_at_gc_horizon = [
    9594            2 :             Bytes::from_static(b"value 0@0x10"),
    9595            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9596            2 :             Bytes::from_static(b"value 2@0x10"),
    9597            2 :             Bytes::from_static(b"value 3@0x10"),
    9598            2 :             Bytes::from_static(b"value 4@0x10"),
    9599            2 :             Bytes::from_static(b"value 5@0x10"),
    9600            2 :             Bytes::from_static(b"value 6@0x10"),
    9601            2 :             Bytes::from_static(b"value 7@0x10"),
    9602            2 :             Bytes::from_static(b"value 8@0x10"),
    9603            2 :             Bytes::from_static(b"value 9@0x10"),
    9604            2 :         ];
    9605            2 : 
    9606            2 :         let expected_result_at_lsn_20 = [
    9607            2 :             Bytes::from_static(b"value 0@0x10"),
    9608            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9609            2 :             Bytes::from_static(b"value 2@0x10"),
    9610            2 :             Bytes::from_static(b"value 3@0x10"),
    9611            2 :             Bytes::from_static(b"value 4@0x10"),
    9612            2 :             Bytes::from_static(b"value 5@0x10"),
    9613            2 :             Bytes::from_static(b"value 6@0x10"),
    9614            2 :             Bytes::from_static(b"value 7@0x10"),
    9615            2 :             Bytes::from_static(b"value 8@0x10"),
    9616            2 :             Bytes::from_static(b"value 9@0x10"),
    9617            2 :         ];
    9618            2 : 
    9619            2 :         let expected_result_at_lsn_10 = [
    9620            2 :             Bytes::from_static(b"value 0@0x10"),
    9621            2 :             Bytes::from_static(b"value 1@0x10"),
    9622            2 :             Bytes::from_static(b"value 2@0x10"),
    9623            2 :             Bytes::from_static(b"value 3@0x10"),
    9624            2 :             Bytes::from_static(b"value 4@0x10"),
    9625            2 :             Bytes::from_static(b"value 5@0x10"),
    9626            2 :             Bytes::from_static(b"value 6@0x10"),
    9627            2 :             Bytes::from_static(b"value 7@0x10"),
    9628            2 :             Bytes::from_static(b"value 8@0x10"),
    9629            2 :             Bytes::from_static(b"value 9@0x10"),
    9630            2 :         ];
    9631            2 : 
    9632            8 :         let verify_result = || async {
    9633            8 :             let gc_horizon = {
    9634            8 :                 let gc_info = tline.gc_info.read().unwrap();
    9635            8 :                 gc_info.cutoffs.time
    9636            2 :             };
    9637           88 :             for idx in 0..10 {
    9638           80 :                 assert_eq!(
    9639           80 :                     tline
    9640           80 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9641           80 :                         .await
    9642           80 :                         .unwrap(),
    9643           80 :                     &expected_result[idx]
    9644            2 :                 );
    9645           80 :                 assert_eq!(
    9646           80 :                     tline
    9647           80 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9648           80 :                         .await
    9649           80 :                         .unwrap(),
    9650           80 :                     &expected_result_at_gc_horizon[idx]
    9651            2 :                 );
    9652           80 :                 assert_eq!(
    9653           80 :                     tline
    9654           80 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9655           80 :                         .await
    9656           80 :                         .unwrap(),
    9657           80 :                     &expected_result_at_lsn_20[idx]
    9658            2 :                 );
    9659           80 :                 assert_eq!(
    9660           80 :                     tline
    9661           80 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9662           80 :                         .await
    9663           80 :                         .unwrap(),
    9664           80 :                     &expected_result_at_lsn_10[idx]
    9665            2 :                 );
    9666            2 :             }
    9667           16 :         };
    9668            2 : 
    9669            2 :         verify_result().await;
    9670            2 : 
    9671            2 :         let cancel = CancellationToken::new();
    9672            2 :         let mut dryrun_flags = EnumSet::new();
    9673            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9674            2 : 
    9675            2 :         tline
    9676            2 :             .compact_with_gc(
    9677            2 :                 &cancel,
    9678            2 :                 CompactOptions {
    9679            2 :                     flags: dryrun_flags,
    9680            2 :                     ..Default::default()
    9681            2 :                 },
    9682            2 :                 &ctx,
    9683            2 :             )
    9684            2 :             .await
    9685            2 :             .unwrap();
    9686            2 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9687            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9688            2 :         verify_result().await;
    9689            2 : 
    9690            2 :         tline
    9691            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9692            2 :             .await
    9693            2 :             .unwrap();
    9694            2 :         verify_result().await;
    9695            2 : 
    9696            2 :         // compact again
    9697            2 :         tline
    9698            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9699            2 :             .await
    9700            2 :             .unwrap();
    9701            2 :         verify_result().await;
    9702            2 : 
    9703            2 :         Ok(())
    9704            2 :     }
    9705              : 
    9706              :     #[cfg(feature = "testing")]
    9707              :     #[tokio::test]
    9708            2 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9709            2 :         use models::CompactLsnRange;
    9710            2 : 
    9711            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9712            2 :         let (tenant, ctx) = harness.load().await;
    9713            2 : 
    9714          166 :         fn get_key(id: u32) -> Key {
    9715          166 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9716          166 :             key.field6 = id;
    9717          166 :             key
    9718          166 :         }
    9719            2 : 
    9720            2 :         let img_layer = (0..10)
    9721           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9722            2 :             .collect_vec();
    9723            2 : 
    9724            2 :         let delta1 = vec![
    9725            2 :             (
    9726            2 :                 get_key(1),
    9727            2 :                 Lsn(0x20),
    9728            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9729            2 :             ),
    9730            2 :             (
    9731            2 :                 get_key(2),
    9732            2 :                 Lsn(0x30),
    9733            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9734            2 :             ),
    9735            2 :             (
    9736            2 :                 get_key(3),
    9737            2 :                 Lsn(0x28),
    9738            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9739            2 :             ),
    9740            2 :             (
    9741            2 :                 get_key(3),
    9742            2 :                 Lsn(0x30),
    9743            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9744            2 :             ),
    9745            2 :             (
    9746            2 :                 get_key(3),
    9747            2 :                 Lsn(0x40),
    9748            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9749            2 :             ),
    9750            2 :         ];
    9751            2 :         let delta2 = vec![
    9752            2 :             (
    9753            2 :                 get_key(5),
    9754            2 :                 Lsn(0x20),
    9755            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9756            2 :             ),
    9757            2 :             (
    9758            2 :                 get_key(6),
    9759            2 :                 Lsn(0x20),
    9760            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9761            2 :             ),
    9762            2 :         ];
    9763            2 :         let delta3 = vec![
    9764            2 :             (
    9765            2 :                 get_key(8),
    9766            2 :                 Lsn(0x48),
    9767            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9768            2 :             ),
    9769            2 :             (
    9770            2 :                 get_key(9),
    9771            2 :                 Lsn(0x48),
    9772            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9773            2 :             ),
    9774            2 :         ];
    9775            2 : 
    9776            2 :         let parent_tline = tenant
    9777            2 :             .create_test_timeline_with_layers(
    9778            2 :                 TIMELINE_ID,
    9779            2 :                 Lsn(0x10),
    9780            2 :                 DEFAULT_PG_VERSION,
    9781            2 :                 &ctx,
    9782            2 :                 vec![],                       // delta layers
    9783            2 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9784            2 :                 Lsn(0x18),
    9785            2 :             )
    9786            2 :             .await?;
    9787            2 : 
    9788            2 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9789            2 : 
    9790            2 :         let branch_tline = tenant
    9791            2 :             .branch_timeline_test_with_layers(
    9792            2 :                 &parent_tline,
    9793            2 :                 NEW_TIMELINE_ID,
    9794            2 :                 Some(Lsn(0x18)),
    9795            2 :                 &ctx,
    9796            2 :                 vec![
    9797            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9798            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9799            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9800            2 :                 ], // delta layers
    9801            2 :                 vec![], // image layers
    9802            2 :                 Lsn(0x50),
    9803            2 :             )
    9804            2 :             .await?;
    9805            2 : 
    9806            2 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9807            2 : 
    9808            2 :         {
    9809            2 :             parent_tline
    9810            2 :                 .latest_gc_cutoff_lsn
    9811            2 :                 .lock_for_write()
    9812            2 :                 .store_and_unlock(Lsn(0x10))
    9813            2 :                 .wait()
    9814            2 :                 .await;
    9815            2 :             // Update GC info
    9816            2 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9817            2 :             *guard = GcInfo {
    9818            2 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9819            2 :                 cutoffs: GcCutoffs {
    9820            2 :                     time: Lsn(0x10),
    9821            2 :                     space: Lsn(0x10),
    9822            2 :                 },
    9823            2 :                 leases: Default::default(),
    9824            2 :                 within_ancestor_pitr: false,
    9825            2 :             };
    9826            2 :         }
    9827            2 : 
    9828            2 :         {
    9829            2 :             branch_tline
    9830            2 :                 .latest_gc_cutoff_lsn
    9831            2 :                 .lock_for_write()
    9832            2 :                 .store_and_unlock(Lsn(0x50))
    9833            2 :                 .wait()
    9834            2 :                 .await;
    9835            2 :             // Update GC info
    9836            2 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9837            2 :             *guard = GcInfo {
    9838            2 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9839            2 :                 cutoffs: GcCutoffs {
    9840            2 :                     time: Lsn(0x50),
    9841            2 :                     space: Lsn(0x50),
    9842            2 :                 },
    9843            2 :                 leases: Default::default(),
    9844            2 :                 within_ancestor_pitr: false,
    9845            2 :             };
    9846            2 :         }
    9847            2 : 
    9848            2 :         let expected_result_at_gc_horizon = [
    9849            2 :             Bytes::from_static(b"value 0@0x10"),
    9850            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9851            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9852            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9853            2 :             Bytes::from_static(b"value 4@0x10"),
    9854            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9855            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9856            2 :             Bytes::from_static(b"value 7@0x10"),
    9857            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9858            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9859            2 :         ];
    9860            2 : 
    9861            2 :         let expected_result_at_lsn_40 = [
    9862            2 :             Bytes::from_static(b"value 0@0x10"),
    9863            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9864            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9865            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9866            2 :             Bytes::from_static(b"value 4@0x10"),
    9867            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9868            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9869            2 :             Bytes::from_static(b"value 7@0x10"),
    9870            2 :             Bytes::from_static(b"value 8@0x10"),
    9871            2 :             Bytes::from_static(b"value 9@0x10"),
    9872            2 :         ];
    9873            2 : 
    9874            6 :         let verify_result = || async {
    9875           66 :             for idx in 0..10 {
    9876           60 :                 assert_eq!(
    9877           60 :                     branch_tline
    9878           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9879           60 :                         .await
    9880           60 :                         .unwrap(),
    9881           60 :                     &expected_result_at_gc_horizon[idx]
    9882            2 :                 );
    9883           60 :                 assert_eq!(
    9884           60 :                     branch_tline
    9885           60 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9886           60 :                         .await
    9887           60 :                         .unwrap(),
    9888           60 :                     &expected_result_at_lsn_40[idx]
    9889            2 :                 );
    9890            2 :             }
    9891           12 :         };
    9892            2 : 
    9893            2 :         verify_result().await;
    9894            2 : 
    9895            2 :         let cancel = CancellationToken::new();
    9896            2 :         branch_tline
    9897            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9898            2 :             .await
    9899            2 :             .unwrap();
    9900            2 : 
    9901            2 :         verify_result().await;
    9902            2 : 
    9903            2 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
    9904            2 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
    9905            2 :         branch_tline
    9906            2 :             .compact_with_gc(
    9907            2 :                 &cancel,
    9908            2 :                 CompactOptions {
    9909            2 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
    9910            2 :                     ..Default::default()
    9911            2 :                 },
    9912            2 :                 &ctx,
    9913            2 :             )
    9914            2 :             .await
    9915            2 :             .unwrap();
    9916            2 : 
    9917            2 :         verify_result().await;
    9918            2 : 
    9919            2 :         Ok(())
    9920            2 :     }
    9921              : 
    9922              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9923              :     // Create an image arrangement where we have to read at different LSN ranges
    9924              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9925              :     // a delta layer. Like so:
    9926              :     //
    9927              :     //     A      B
    9928              :     // +----------------+ -> delta_layer
    9929              :     // |                |                           ^ lsn
    9930              :     // |       =========|-> nested_image_layer      |
    9931              :     // |       C        |                           |
    9932              :     // +----------------+                           |
    9933              :     // ======== -> baseline_image_layer             +-------> key
    9934              :     //
    9935              :     //
    9936              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9937              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9938              :     #[cfg(feature = "testing")]
    9939              :     #[tokio::test]
    9940            2 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9941            2 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9942            2 :         let (tenant, ctx) = harness.load().await;
    9943            2 : 
    9944            2 :         let will_init_keys = [2, 6];
    9945           44 :         fn get_key(id: u32) -> Key {
    9946           44 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9947           44 :             key.field6 = id;
    9948           44 :             key
    9949           44 :         }
    9950            2 : 
    9951            2 :         let mut expected_key_values = HashMap::new();
    9952            2 : 
    9953            2 :         let baseline_image_layer_lsn = Lsn(0x10);
    9954            2 :         let mut baseline_img_layer = Vec::new();
    9955           12 :         for i in 0..5 {
    9956           10 :             let key = get_key(i);
    9957           10 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
    9958           10 : 
    9959           10 :             let removed = expected_key_values.insert(key, value.clone());
    9960           10 :             assert!(removed.is_none());
    9961            2 : 
    9962           10 :             baseline_img_layer.push((key, Bytes::from(value)));
    9963            2 :         }
    9964            2 : 
    9965            2 :         let nested_image_layer_lsn = Lsn(0x50);
    9966            2 :         let mut nested_img_layer = Vec::new();
    9967           12 :         for i in 5..10 {
    9968           10 :             let key = get_key(i);
    9969           10 :             let value = format!("value {i}@{nested_image_layer_lsn}");
    9970           10 : 
    9971           10 :             let removed = expected_key_values.insert(key, value.clone());
    9972           10 :             assert!(removed.is_none());
    9973            2 : 
    9974           10 :             nested_img_layer.push((key, Bytes::from(value)));
    9975            2 :         }
    9976            2 : 
    9977            2 :         let mut delta_layer_spec = Vec::default();
    9978            2 :         let delta_layer_start_lsn = Lsn(0x20);
    9979            2 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
    9980            2 : 
    9981           22 :         for i in 0..10 {
    9982           20 :             let key = get_key(i);
    9983           20 :             let key_in_nested = nested_img_layer
    9984           20 :                 .iter()
    9985           80 :                 .any(|(key_with_img, _)| *key_with_img == key);
    9986           20 :             let lsn = {
    9987           20 :                 if key_in_nested {
    9988           10 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
    9989            2 :                 } else {
    9990           10 :                     delta_layer_start_lsn
    9991            2 :                 }
    9992            2 :             };
    9993            2 : 
    9994           20 :             let will_init = will_init_keys.contains(&i);
    9995           20 :             if will_init {
    9996            4 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
    9997            4 : 
    9998            4 :                 expected_key_values.insert(key, "".to_string());
    9999           16 :             } else {
   10000           16 :                 let delta = format!("@{lsn}");
   10001           16 :                 delta_layer_spec.push((
   10002           16 :                     key,
   10003           16 :                     lsn,
   10004           16 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10005           16 :                 ));
   10006           16 : 
   10007           16 :                 expected_key_values
   10008           16 :                     .get_mut(&key)
   10009           16 :                     .expect("An image exists for each key")
   10010           16 :                     .push_str(delta.as_str());
   10011           16 :             }
   10012           20 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10013            2 :         }
   10014            2 : 
   10015            2 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10016            2 : 
   10017            2 :         assert!(
   10018            2 :             nested_image_layer_lsn > delta_layer_start_lsn
   10019            2 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10020            2 :         );
   10021            2 : 
   10022            2 :         let tline = tenant
   10023            2 :             .create_test_timeline_with_layers(
   10024            2 :                 TIMELINE_ID,
   10025            2 :                 baseline_image_layer_lsn,
   10026            2 :                 DEFAULT_PG_VERSION,
   10027            2 :                 &ctx,
   10028            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10029            2 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10030            2 :                     delta_layer_spec,
   10031            2 :                 )], // delta layers
   10032            2 :                 vec![
   10033            2 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10034            2 :                     (nested_image_layer_lsn, nested_img_layer),
   10035            2 :                 ], // image layers
   10036            2 :                 delta_layer_end_lsn,
   10037            2 :             )
   10038            2 :             .await?;
   10039            2 : 
   10040            2 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10041            2 :         let results = tline
   10042            2 :             .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
   10043            2 :             .await
   10044            2 :             .expect("No vectored errors");
   10045           22 :         for (key, res) in results {
   10046           20 :             let value = res.expect("No key errors");
   10047           20 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10048           20 :             assert_eq!(value, Bytes::from(expected_value));
   10049            2 :         }
   10050            2 : 
   10051            2 :         Ok(())
   10052            2 :     }
   10053              : 
   10054          214 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10055          214 :         (
   10056          214 :             k1.is_delta,
   10057          214 :             k1.key_range.start,
   10058          214 :             k1.key_range.end,
   10059          214 :             k1.lsn_range.start,
   10060          214 :             k1.lsn_range.end,
   10061          214 :         )
   10062          214 :             .cmp(&(
   10063          214 :                 k2.is_delta,
   10064          214 :                 k2.key_range.start,
   10065          214 :                 k2.key_range.end,
   10066          214 :                 k2.lsn_range.start,
   10067          214 :                 k2.lsn_range.end,
   10068          214 :             ))
   10069          214 :     }
   10070              : 
   10071           24 :     async fn inspect_and_sort(
   10072           24 :         tline: &Arc<Timeline>,
   10073           24 :         filter: Option<std::ops::Range<Key>>,
   10074           24 :     ) -> Vec<PersistentLayerKey> {
   10075           24 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10076           24 :         if let Some(filter) = filter {
   10077          108 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10078           22 :         }
   10079           24 :         all_layers.sort_by(sort_layer_key);
   10080           24 :         all_layers
   10081           24 :     }
   10082              : 
   10083              :     #[cfg(feature = "testing")]
   10084           22 :     fn check_layer_map_key_eq(
   10085           22 :         mut left: Vec<PersistentLayerKey>,
   10086           22 :         mut right: Vec<PersistentLayerKey>,
   10087           22 :     ) {
   10088           22 :         left.sort_by(sort_layer_key);
   10089           22 :         right.sort_by(sort_layer_key);
   10090           22 :         if left != right {
   10091            0 :             eprintln!("---LEFT---");
   10092            0 :             for left in left.iter() {
   10093            0 :                 eprintln!("{}", left);
   10094            0 :             }
   10095            0 :             eprintln!("---RIGHT---");
   10096            0 :             for right in right.iter() {
   10097            0 :                 eprintln!("{}", right);
   10098            0 :             }
   10099            0 :             assert_eq!(left, right);
   10100           22 :         }
   10101           22 :     }
   10102              : 
   10103              :     #[cfg(feature = "testing")]
   10104              :     #[tokio::test]
   10105            2 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10106            2 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10107            2 :         let (tenant, ctx) = harness.load().await;
   10108            2 : 
   10109          182 :         fn get_key(id: u32) -> Key {
   10110          182 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10111          182 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10112          182 :             key.field6 = id;
   10113          182 :             key
   10114          182 :         }
   10115            2 : 
   10116            2 :         // img layer at 0x10
   10117            2 :         let img_layer = (0..10)
   10118           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10119            2 :             .collect_vec();
   10120            2 : 
   10121            2 :         let delta1 = vec![
   10122            2 :             (
   10123            2 :                 get_key(1),
   10124            2 :                 Lsn(0x20),
   10125            2 :                 Value::Image(Bytes::from("value 1@0x20")),
   10126            2 :             ),
   10127            2 :             (
   10128            2 :                 get_key(2),
   10129            2 :                 Lsn(0x30),
   10130            2 :                 Value::Image(Bytes::from("value 2@0x30")),
   10131            2 :             ),
   10132            2 :             (
   10133            2 :                 get_key(3),
   10134            2 :                 Lsn(0x40),
   10135            2 :                 Value::Image(Bytes::from("value 3@0x40")),
   10136            2 :             ),
   10137            2 :         ];
   10138            2 :         let delta2 = vec![
   10139            2 :             (
   10140            2 :                 get_key(5),
   10141            2 :                 Lsn(0x20),
   10142            2 :                 Value::Image(Bytes::from("value 5@0x20")),
   10143            2 :             ),
   10144            2 :             (
   10145            2 :                 get_key(6),
   10146            2 :                 Lsn(0x20),
   10147            2 :                 Value::Image(Bytes::from("value 6@0x20")),
   10148            2 :             ),
   10149            2 :         ];
   10150            2 :         let delta3 = vec![
   10151            2 :             (
   10152            2 :                 get_key(8),
   10153            2 :                 Lsn(0x48),
   10154            2 :                 Value::Image(Bytes::from("value 8@0x48")),
   10155            2 :             ),
   10156            2 :             (
   10157            2 :                 get_key(9),
   10158            2 :                 Lsn(0x48),
   10159            2 :                 Value::Image(Bytes::from("value 9@0x48")),
   10160            2 :             ),
   10161            2 :         ];
   10162            2 : 
   10163            2 :         let tline = tenant
   10164            2 :             .create_test_timeline_with_layers(
   10165            2 :                 TIMELINE_ID,
   10166            2 :                 Lsn(0x10),
   10167            2 :                 DEFAULT_PG_VERSION,
   10168            2 :                 &ctx,
   10169            2 :                 vec![
   10170            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10171            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10172            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10173            2 :                 ], // delta layers
   10174            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10175            2 :                 Lsn(0x50),
   10176            2 :             )
   10177            2 :             .await?;
   10178            2 : 
   10179            2 :         {
   10180            2 :             tline
   10181            2 :                 .latest_gc_cutoff_lsn
   10182            2 :                 .lock_for_write()
   10183            2 :                 .store_and_unlock(Lsn(0x30))
   10184            2 :                 .wait()
   10185            2 :                 .await;
   10186            2 :             // Update GC info
   10187            2 :             let mut guard = tline.gc_info.write().unwrap();
   10188            2 :             *guard = GcInfo {
   10189            2 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10190            2 :                 cutoffs: GcCutoffs {
   10191            2 :                     time: Lsn(0x30),
   10192            2 :                     space: Lsn(0x30),
   10193            2 :                 },
   10194            2 :                 leases: Default::default(),
   10195            2 :                 within_ancestor_pitr: false,
   10196            2 :             };
   10197            2 :         }
   10198            2 : 
   10199            2 :         let cancel = CancellationToken::new();
   10200            2 : 
   10201            2 :         // Do a partial compaction on key range 0..2
   10202            2 :         tline
   10203            2 :             .compact_with_gc(
   10204            2 :                 &cancel,
   10205            2 :                 CompactOptions {
   10206            2 :                     flags: EnumSet::new(),
   10207            2 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10208            2 :                     ..Default::default()
   10209            2 :                 },
   10210            2 :                 &ctx,
   10211            2 :             )
   10212            2 :             .await
   10213            2 :             .unwrap();
   10214            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10215            2 :         check_layer_map_key_eq(
   10216            2 :             all_layers,
   10217            2 :             vec![
   10218            2 :                 // newly-generated image layer for the partial compaction range 0-2
   10219            2 :                 PersistentLayerKey {
   10220            2 :                     key_range: get_key(0)..get_key(2),
   10221            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10222            2 :                     is_delta: false,
   10223            2 :                 },
   10224            2 :                 PersistentLayerKey {
   10225            2 :                     key_range: get_key(0)..get_key(10),
   10226            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10227            2 :                     is_delta: false,
   10228            2 :                 },
   10229            2 :                 // delta1 is split and the second part is rewritten
   10230            2 :                 PersistentLayerKey {
   10231            2 :                     key_range: get_key(2)..get_key(4),
   10232            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10233            2 :                     is_delta: true,
   10234            2 :                 },
   10235            2 :                 PersistentLayerKey {
   10236            2 :                     key_range: get_key(5)..get_key(7),
   10237            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10238            2 :                     is_delta: true,
   10239            2 :                 },
   10240            2 :                 PersistentLayerKey {
   10241            2 :                     key_range: get_key(8)..get_key(10),
   10242            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10243            2 :                     is_delta: true,
   10244            2 :                 },
   10245            2 :             ],
   10246            2 :         );
   10247            2 : 
   10248            2 :         // Do a partial compaction on key range 2..4
   10249            2 :         tline
   10250            2 :             .compact_with_gc(
   10251            2 :                 &cancel,
   10252            2 :                 CompactOptions {
   10253            2 :                     flags: EnumSet::new(),
   10254            2 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10255            2 :                     ..Default::default()
   10256            2 :                 },
   10257            2 :                 &ctx,
   10258            2 :             )
   10259            2 :             .await
   10260            2 :             .unwrap();
   10261            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10262            2 :         check_layer_map_key_eq(
   10263            2 :             all_layers,
   10264            2 :             vec![
   10265            2 :                 PersistentLayerKey {
   10266            2 :                     key_range: get_key(0)..get_key(2),
   10267            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10268            2 :                     is_delta: false,
   10269            2 :                 },
   10270            2 :                 PersistentLayerKey {
   10271            2 :                     key_range: get_key(0)..get_key(10),
   10272            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10273            2 :                     is_delta: false,
   10274            2 :                 },
   10275            2 :                 // image layer generated for the compaction range 2-4
   10276            2 :                 PersistentLayerKey {
   10277            2 :                     key_range: get_key(2)..get_key(4),
   10278            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10279            2 :                     is_delta: false,
   10280            2 :                 },
   10281            2 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10282            2 :                 PersistentLayerKey {
   10283            2 :                     key_range: get_key(2)..get_key(4),
   10284            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10285            2 :                     is_delta: true,
   10286            2 :                 },
   10287            2 :                 PersistentLayerKey {
   10288            2 :                     key_range: get_key(5)..get_key(7),
   10289            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10290            2 :                     is_delta: true,
   10291            2 :                 },
   10292            2 :                 PersistentLayerKey {
   10293            2 :                     key_range: get_key(8)..get_key(10),
   10294            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10295            2 :                     is_delta: true,
   10296            2 :                 },
   10297            2 :             ],
   10298            2 :         );
   10299            2 : 
   10300            2 :         // Do a partial compaction on key range 4..9
   10301            2 :         tline
   10302            2 :             .compact_with_gc(
   10303            2 :                 &cancel,
   10304            2 :                 CompactOptions {
   10305            2 :                     flags: EnumSet::new(),
   10306            2 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10307            2 :                     ..Default::default()
   10308            2 :                 },
   10309            2 :                 &ctx,
   10310            2 :             )
   10311            2 :             .await
   10312            2 :             .unwrap();
   10313            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10314            2 :         check_layer_map_key_eq(
   10315            2 :             all_layers,
   10316            2 :             vec![
   10317            2 :                 PersistentLayerKey {
   10318            2 :                     key_range: get_key(0)..get_key(2),
   10319            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10320            2 :                     is_delta: false,
   10321            2 :                 },
   10322            2 :                 PersistentLayerKey {
   10323            2 :                     key_range: get_key(0)..get_key(10),
   10324            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10325            2 :                     is_delta: false,
   10326            2 :                 },
   10327            2 :                 PersistentLayerKey {
   10328            2 :                     key_range: get_key(2)..get_key(4),
   10329            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10330            2 :                     is_delta: false,
   10331            2 :                 },
   10332            2 :                 PersistentLayerKey {
   10333            2 :                     key_range: get_key(2)..get_key(4),
   10334            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10335            2 :                     is_delta: true,
   10336            2 :                 },
   10337            2 :                 // image layer generated for this compaction range
   10338            2 :                 PersistentLayerKey {
   10339            2 :                     key_range: get_key(4)..get_key(9),
   10340            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10341            2 :                     is_delta: false,
   10342            2 :                 },
   10343            2 :                 PersistentLayerKey {
   10344            2 :                     key_range: get_key(8)..get_key(10),
   10345            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10346            2 :                     is_delta: true,
   10347            2 :                 },
   10348            2 :             ],
   10349            2 :         );
   10350            2 : 
   10351            2 :         // Do a partial compaction on key range 9..10
   10352            2 :         tline
   10353            2 :             .compact_with_gc(
   10354            2 :                 &cancel,
   10355            2 :                 CompactOptions {
   10356            2 :                     flags: EnumSet::new(),
   10357            2 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10358            2 :                     ..Default::default()
   10359            2 :                 },
   10360            2 :                 &ctx,
   10361            2 :             )
   10362            2 :             .await
   10363            2 :             .unwrap();
   10364            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10365            2 :         check_layer_map_key_eq(
   10366            2 :             all_layers,
   10367            2 :             vec![
   10368            2 :                 PersistentLayerKey {
   10369            2 :                     key_range: get_key(0)..get_key(2),
   10370            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10371            2 :                     is_delta: false,
   10372            2 :                 },
   10373            2 :                 PersistentLayerKey {
   10374            2 :                     key_range: get_key(0)..get_key(10),
   10375            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10376            2 :                     is_delta: false,
   10377            2 :                 },
   10378            2 :                 PersistentLayerKey {
   10379            2 :                     key_range: get_key(2)..get_key(4),
   10380            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10381            2 :                     is_delta: false,
   10382            2 :                 },
   10383            2 :                 PersistentLayerKey {
   10384            2 :                     key_range: get_key(2)..get_key(4),
   10385            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10386            2 :                     is_delta: true,
   10387            2 :                 },
   10388            2 :                 PersistentLayerKey {
   10389            2 :                     key_range: get_key(4)..get_key(9),
   10390            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10391            2 :                     is_delta: false,
   10392            2 :                 },
   10393            2 :                 // image layer generated for the compaction range
   10394            2 :                 PersistentLayerKey {
   10395            2 :                     key_range: get_key(9)..get_key(10),
   10396            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10397            2 :                     is_delta: false,
   10398            2 :                 },
   10399            2 :                 PersistentLayerKey {
   10400            2 :                     key_range: get_key(8)..get_key(10),
   10401            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10402            2 :                     is_delta: true,
   10403            2 :                 },
   10404            2 :             ],
   10405            2 :         );
   10406            2 : 
   10407            2 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10408            2 :         tline
   10409            2 :             .compact_with_gc(
   10410            2 :                 &cancel,
   10411            2 :                 CompactOptions {
   10412            2 :                     flags: EnumSet::new(),
   10413            2 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10414            2 :                     ..Default::default()
   10415            2 :                 },
   10416            2 :                 &ctx,
   10417            2 :             )
   10418            2 :             .await
   10419            2 :             .unwrap();
   10420            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10421            2 :         check_layer_map_key_eq(
   10422            2 :             all_layers,
   10423            2 :             vec![
   10424            2 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10425            2 :                 PersistentLayerKey {
   10426            2 :                     key_range: get_key(0)..get_key(10),
   10427            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10428            2 :                     is_delta: false,
   10429            2 :                 },
   10430            2 :                 PersistentLayerKey {
   10431            2 :                     key_range: get_key(2)..get_key(4),
   10432            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10433            2 :                     is_delta: true,
   10434            2 :                 },
   10435            2 :                 PersistentLayerKey {
   10436            2 :                     key_range: get_key(8)..get_key(10),
   10437            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10438            2 :                     is_delta: true,
   10439            2 :                 },
   10440            2 :             ],
   10441            2 :         );
   10442            2 :         Ok(())
   10443            2 :     }
   10444              : 
   10445              :     #[cfg(feature = "testing")]
   10446              :     #[tokio::test]
   10447            2 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10448            2 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10449            2 :             .await
   10450            2 :             .unwrap();
   10451            2 :         let (tenant, ctx) = harness.load().await;
   10452            2 :         let tline_parent = tenant
   10453            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10454            2 :             .await
   10455            2 :             .unwrap();
   10456            2 :         let tline_child = tenant
   10457            2 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10458            2 :             .await
   10459            2 :             .unwrap();
   10460            2 :         {
   10461            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10462            2 :             assert_eq!(
   10463            2 :                 gc_info_parent.retain_lsns,
   10464            2 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10465            2 :             );
   10466            2 :         }
   10467            2 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10468            2 :         tline_child
   10469            2 :             .remote_client
   10470            2 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10471            2 :             .unwrap();
   10472            2 :         tline_child.remote_client.wait_completion().await.unwrap();
   10473            2 :         offload_timeline(&tenant, &tline_child)
   10474            2 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10475            2 :             .await.unwrap();
   10476            2 :         let child_timeline_id = tline_child.timeline_id;
   10477            2 :         Arc::try_unwrap(tline_child).unwrap();
   10478            2 : 
   10479            2 :         {
   10480            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10481            2 :             assert_eq!(
   10482            2 :                 gc_info_parent.retain_lsns,
   10483            2 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10484            2 :             );
   10485            2 :         }
   10486            2 : 
   10487            2 :         tenant
   10488            2 :             .get_offloaded_timeline(child_timeline_id)
   10489            2 :             .unwrap()
   10490            2 :             .defuse_for_tenant_drop();
   10491            2 : 
   10492            2 :         Ok(())
   10493            2 :     }
   10494              : 
   10495              :     #[cfg(feature = "testing")]
   10496              :     #[tokio::test]
   10497            2 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10498            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10499            2 :         let (tenant, ctx) = harness.load().await;
   10500            2 : 
   10501          296 :         fn get_key(id: u32) -> Key {
   10502          296 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10503          296 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10504          296 :             key.field6 = id;
   10505          296 :             key
   10506          296 :         }
   10507            2 : 
   10508            2 :         let img_layer = (0..10)
   10509           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10510            2 :             .collect_vec();
   10511            2 : 
   10512            2 :         let delta1 = vec![(
   10513            2 :             get_key(1),
   10514            2 :             Lsn(0x20),
   10515            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10516            2 :         )];
   10517            2 :         let delta4 = vec![(
   10518            2 :             get_key(1),
   10519            2 :             Lsn(0x28),
   10520            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10521            2 :         )];
   10522            2 :         let delta2 = vec![
   10523            2 :             (
   10524            2 :                 get_key(1),
   10525            2 :                 Lsn(0x30),
   10526            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10527            2 :             ),
   10528            2 :             (
   10529            2 :                 get_key(1),
   10530            2 :                 Lsn(0x38),
   10531            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10532            2 :             ),
   10533            2 :         ];
   10534            2 :         let delta3 = vec![
   10535            2 :             (
   10536            2 :                 get_key(8),
   10537            2 :                 Lsn(0x48),
   10538            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10539            2 :             ),
   10540            2 :             (
   10541            2 :                 get_key(9),
   10542            2 :                 Lsn(0x48),
   10543            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10544            2 :             ),
   10545            2 :         ];
   10546            2 : 
   10547            2 :         let tline = tenant
   10548            2 :             .create_test_timeline_with_layers(
   10549            2 :                 TIMELINE_ID,
   10550            2 :                 Lsn(0x10),
   10551            2 :                 DEFAULT_PG_VERSION,
   10552            2 :                 &ctx,
   10553            2 :                 vec![
   10554            2 :                     // delta1/2/4 only contain a single key but multiple updates
   10555            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10556            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10557            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10558            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10559            2 :                 ], // delta layers
   10560            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10561            2 :                 Lsn(0x50),
   10562            2 :             )
   10563            2 :             .await?;
   10564            2 :         {
   10565            2 :             tline
   10566            2 :                 .latest_gc_cutoff_lsn
   10567            2 :                 .lock_for_write()
   10568            2 :                 .store_and_unlock(Lsn(0x30))
   10569            2 :                 .wait()
   10570            2 :                 .await;
   10571            2 :             // Update GC info
   10572            2 :             let mut guard = tline.gc_info.write().unwrap();
   10573            2 :             *guard = GcInfo {
   10574            2 :                 retain_lsns: vec![
   10575            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10576            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10577            2 :                 ],
   10578            2 :                 cutoffs: GcCutoffs {
   10579            2 :                     time: Lsn(0x30),
   10580            2 :                     space: Lsn(0x30),
   10581            2 :                 },
   10582            2 :                 leases: Default::default(),
   10583            2 :                 within_ancestor_pitr: false,
   10584            2 :             };
   10585            2 :         }
   10586            2 : 
   10587            2 :         let expected_result = [
   10588            2 :             Bytes::from_static(b"value 0@0x10"),
   10589            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10590            2 :             Bytes::from_static(b"value 2@0x10"),
   10591            2 :             Bytes::from_static(b"value 3@0x10"),
   10592            2 :             Bytes::from_static(b"value 4@0x10"),
   10593            2 :             Bytes::from_static(b"value 5@0x10"),
   10594            2 :             Bytes::from_static(b"value 6@0x10"),
   10595            2 :             Bytes::from_static(b"value 7@0x10"),
   10596            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10597            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10598            2 :         ];
   10599            2 : 
   10600            2 :         let expected_result_at_gc_horizon = [
   10601            2 :             Bytes::from_static(b"value 0@0x10"),
   10602            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10603            2 :             Bytes::from_static(b"value 2@0x10"),
   10604            2 :             Bytes::from_static(b"value 3@0x10"),
   10605            2 :             Bytes::from_static(b"value 4@0x10"),
   10606            2 :             Bytes::from_static(b"value 5@0x10"),
   10607            2 :             Bytes::from_static(b"value 6@0x10"),
   10608            2 :             Bytes::from_static(b"value 7@0x10"),
   10609            2 :             Bytes::from_static(b"value 8@0x10"),
   10610            2 :             Bytes::from_static(b"value 9@0x10"),
   10611            2 :         ];
   10612            2 : 
   10613            2 :         let expected_result_at_lsn_20 = [
   10614            2 :             Bytes::from_static(b"value 0@0x10"),
   10615            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10616            2 :             Bytes::from_static(b"value 2@0x10"),
   10617            2 :             Bytes::from_static(b"value 3@0x10"),
   10618            2 :             Bytes::from_static(b"value 4@0x10"),
   10619            2 :             Bytes::from_static(b"value 5@0x10"),
   10620            2 :             Bytes::from_static(b"value 6@0x10"),
   10621            2 :             Bytes::from_static(b"value 7@0x10"),
   10622            2 :             Bytes::from_static(b"value 8@0x10"),
   10623            2 :             Bytes::from_static(b"value 9@0x10"),
   10624            2 :         ];
   10625            2 : 
   10626            2 :         let expected_result_at_lsn_10 = [
   10627            2 :             Bytes::from_static(b"value 0@0x10"),
   10628            2 :             Bytes::from_static(b"value 1@0x10"),
   10629            2 :             Bytes::from_static(b"value 2@0x10"),
   10630            2 :             Bytes::from_static(b"value 3@0x10"),
   10631            2 :             Bytes::from_static(b"value 4@0x10"),
   10632            2 :             Bytes::from_static(b"value 5@0x10"),
   10633            2 :             Bytes::from_static(b"value 6@0x10"),
   10634            2 :             Bytes::from_static(b"value 7@0x10"),
   10635            2 :             Bytes::from_static(b"value 8@0x10"),
   10636            2 :             Bytes::from_static(b"value 9@0x10"),
   10637            2 :         ];
   10638            2 : 
   10639            6 :         let verify_result = || async {
   10640            6 :             let gc_horizon = {
   10641            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10642            6 :                 gc_info.cutoffs.time
   10643            2 :             };
   10644           66 :             for idx in 0..10 {
   10645           60 :                 assert_eq!(
   10646           60 :                     tline
   10647           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10648           60 :                         .await
   10649           60 :                         .unwrap(),
   10650           60 :                     &expected_result[idx]
   10651            2 :                 );
   10652           60 :                 assert_eq!(
   10653           60 :                     tline
   10654           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10655           60 :                         .await
   10656           60 :                         .unwrap(),
   10657           60 :                     &expected_result_at_gc_horizon[idx]
   10658            2 :                 );
   10659           60 :                 assert_eq!(
   10660           60 :                     tline
   10661           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10662           60 :                         .await
   10663           60 :                         .unwrap(),
   10664           60 :                     &expected_result_at_lsn_20[idx]
   10665            2 :                 );
   10666           60 :                 assert_eq!(
   10667           60 :                     tline
   10668           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10669           60 :                         .await
   10670           60 :                         .unwrap(),
   10671           60 :                     &expected_result_at_lsn_10[idx]
   10672            2 :                 );
   10673            2 :             }
   10674           12 :         };
   10675            2 : 
   10676            2 :         verify_result().await;
   10677            2 : 
   10678            2 :         let cancel = CancellationToken::new();
   10679            2 :         tline
   10680            2 :             .compact_with_gc(
   10681            2 :                 &cancel,
   10682            2 :                 CompactOptions {
   10683            2 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10684            2 :                     ..Default::default()
   10685            2 :                 },
   10686            2 :                 &ctx,
   10687            2 :             )
   10688            2 :             .await
   10689            2 :             .unwrap();
   10690            2 :         verify_result().await;
   10691            2 : 
   10692            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10693            2 :         check_layer_map_key_eq(
   10694            2 :             all_layers,
   10695            2 :             vec![
   10696            2 :                 // The original image layer, not compacted
   10697            2 :                 PersistentLayerKey {
   10698            2 :                     key_range: get_key(0)..get_key(10),
   10699            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10700            2 :                     is_delta: false,
   10701            2 :                 },
   10702            2 :                 // Delta layer below the specified above_lsn not compacted
   10703            2 :                 PersistentLayerKey {
   10704            2 :                     key_range: get_key(1)..get_key(2),
   10705            2 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10706            2 :                     is_delta: true,
   10707            2 :                 },
   10708            2 :                 // Delta layer compacted above the LSN
   10709            2 :                 PersistentLayerKey {
   10710            2 :                     key_range: get_key(1)..get_key(10),
   10711            2 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10712            2 :                     is_delta: true,
   10713            2 :                 },
   10714            2 :             ],
   10715            2 :         );
   10716            2 : 
   10717            2 :         // compact again
   10718            2 :         tline
   10719            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10720            2 :             .await
   10721            2 :             .unwrap();
   10722            2 :         verify_result().await;
   10723            2 : 
   10724            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10725            2 :         check_layer_map_key_eq(
   10726            2 :             all_layers,
   10727            2 :             vec![
   10728            2 :                 // The compacted image layer (full key range)
   10729            2 :                 PersistentLayerKey {
   10730            2 :                     key_range: Key::MIN..Key::MAX,
   10731            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10732            2 :                     is_delta: false,
   10733            2 :                 },
   10734            2 :                 // All other data in the delta layer
   10735            2 :                 PersistentLayerKey {
   10736            2 :                     key_range: get_key(1)..get_key(10),
   10737            2 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10738            2 :                     is_delta: true,
   10739            2 :                 },
   10740            2 :             ],
   10741            2 :         );
   10742            2 : 
   10743            2 :         Ok(())
   10744            2 :     }
   10745              : 
   10746              :     #[cfg(feature = "testing")]
   10747              :     #[tokio::test]
   10748            2 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   10749            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   10750            2 :         let (tenant, ctx) = harness.load().await;
   10751            2 : 
   10752          508 :         fn get_key(id: u32) -> Key {
   10753          508 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10754          508 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10755          508 :             key.field6 = id;
   10756          508 :             key
   10757          508 :         }
   10758            2 : 
   10759            2 :         let img_layer = (0..10)
   10760           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10761            2 :             .collect_vec();
   10762            2 : 
   10763            2 :         let delta1 = vec![(
   10764            2 :             get_key(1),
   10765            2 :             Lsn(0x20),
   10766            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10767            2 :         )];
   10768            2 :         let delta4 = vec![(
   10769            2 :             get_key(1),
   10770            2 :             Lsn(0x28),
   10771            2 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10772            2 :         )];
   10773            2 :         let delta2 = vec![
   10774            2 :             (
   10775            2 :                 get_key(1),
   10776            2 :                 Lsn(0x30),
   10777            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10778            2 :             ),
   10779            2 :             (
   10780            2 :                 get_key(1),
   10781            2 :                 Lsn(0x38),
   10782            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10783            2 :             ),
   10784            2 :         ];
   10785            2 :         let delta3 = vec![
   10786            2 :             (
   10787            2 :                 get_key(8),
   10788            2 :                 Lsn(0x48),
   10789            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10790            2 :             ),
   10791            2 :             (
   10792            2 :                 get_key(9),
   10793            2 :                 Lsn(0x48),
   10794            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10795            2 :             ),
   10796            2 :         ];
   10797            2 : 
   10798            2 :         let tline = tenant
   10799            2 :             .create_test_timeline_with_layers(
   10800            2 :                 TIMELINE_ID,
   10801            2 :                 Lsn(0x10),
   10802            2 :                 DEFAULT_PG_VERSION,
   10803            2 :                 &ctx,
   10804            2 :                 vec![
   10805            2 :                     // delta1/2/4 only contain a single key but multiple updates
   10806            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10807            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10808            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10809            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10810            2 :                 ], // delta layers
   10811            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10812            2 :                 Lsn(0x50),
   10813            2 :             )
   10814            2 :             .await?;
   10815            2 :         {
   10816            2 :             tline
   10817            2 :                 .latest_gc_cutoff_lsn
   10818            2 :                 .lock_for_write()
   10819            2 :                 .store_and_unlock(Lsn(0x30))
   10820            2 :                 .wait()
   10821            2 :                 .await;
   10822            2 :             // Update GC info
   10823            2 :             let mut guard = tline.gc_info.write().unwrap();
   10824            2 :             *guard = GcInfo {
   10825            2 :                 retain_lsns: vec![
   10826            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10827            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10828            2 :                 ],
   10829            2 :                 cutoffs: GcCutoffs {
   10830            2 :                     time: Lsn(0x30),
   10831            2 :                     space: Lsn(0x30),
   10832            2 :                 },
   10833            2 :                 leases: Default::default(),
   10834            2 :                 within_ancestor_pitr: false,
   10835            2 :             };
   10836            2 :         }
   10837            2 : 
   10838            2 :         let expected_result = [
   10839            2 :             Bytes::from_static(b"value 0@0x10"),
   10840            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10841            2 :             Bytes::from_static(b"value 2@0x10"),
   10842            2 :             Bytes::from_static(b"value 3@0x10"),
   10843            2 :             Bytes::from_static(b"value 4@0x10"),
   10844            2 :             Bytes::from_static(b"value 5@0x10"),
   10845            2 :             Bytes::from_static(b"value 6@0x10"),
   10846            2 :             Bytes::from_static(b"value 7@0x10"),
   10847            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10848            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10849            2 :         ];
   10850            2 : 
   10851            2 :         let expected_result_at_gc_horizon = [
   10852            2 :             Bytes::from_static(b"value 0@0x10"),
   10853            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10854            2 :             Bytes::from_static(b"value 2@0x10"),
   10855            2 :             Bytes::from_static(b"value 3@0x10"),
   10856            2 :             Bytes::from_static(b"value 4@0x10"),
   10857            2 :             Bytes::from_static(b"value 5@0x10"),
   10858            2 :             Bytes::from_static(b"value 6@0x10"),
   10859            2 :             Bytes::from_static(b"value 7@0x10"),
   10860            2 :             Bytes::from_static(b"value 8@0x10"),
   10861            2 :             Bytes::from_static(b"value 9@0x10"),
   10862            2 :         ];
   10863            2 : 
   10864            2 :         let expected_result_at_lsn_20 = [
   10865            2 :             Bytes::from_static(b"value 0@0x10"),
   10866            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10867            2 :             Bytes::from_static(b"value 2@0x10"),
   10868            2 :             Bytes::from_static(b"value 3@0x10"),
   10869            2 :             Bytes::from_static(b"value 4@0x10"),
   10870            2 :             Bytes::from_static(b"value 5@0x10"),
   10871            2 :             Bytes::from_static(b"value 6@0x10"),
   10872            2 :             Bytes::from_static(b"value 7@0x10"),
   10873            2 :             Bytes::from_static(b"value 8@0x10"),
   10874            2 :             Bytes::from_static(b"value 9@0x10"),
   10875            2 :         ];
   10876            2 : 
   10877            2 :         let expected_result_at_lsn_10 = [
   10878            2 :             Bytes::from_static(b"value 0@0x10"),
   10879            2 :             Bytes::from_static(b"value 1@0x10"),
   10880            2 :             Bytes::from_static(b"value 2@0x10"),
   10881            2 :             Bytes::from_static(b"value 3@0x10"),
   10882            2 :             Bytes::from_static(b"value 4@0x10"),
   10883            2 :             Bytes::from_static(b"value 5@0x10"),
   10884            2 :             Bytes::from_static(b"value 6@0x10"),
   10885            2 :             Bytes::from_static(b"value 7@0x10"),
   10886            2 :             Bytes::from_static(b"value 8@0x10"),
   10887            2 :             Bytes::from_static(b"value 9@0x10"),
   10888            2 :         ];
   10889            2 : 
   10890           10 :         let verify_result = || async {
   10891           10 :             let gc_horizon = {
   10892           10 :                 let gc_info = tline.gc_info.read().unwrap();
   10893           10 :                 gc_info.cutoffs.time
   10894            2 :             };
   10895          110 :             for idx in 0..10 {
   10896          100 :                 assert_eq!(
   10897          100 :                     tline
   10898          100 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10899          100 :                         .await
   10900          100 :                         .unwrap(),
   10901          100 :                     &expected_result[idx]
   10902            2 :                 );
   10903          100 :                 assert_eq!(
   10904          100 :                     tline
   10905          100 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10906          100 :                         .await
   10907          100 :                         .unwrap(),
   10908          100 :                     &expected_result_at_gc_horizon[idx]
   10909            2 :                 );
   10910          100 :                 assert_eq!(
   10911          100 :                     tline
   10912          100 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10913          100 :                         .await
   10914          100 :                         .unwrap(),
   10915          100 :                     &expected_result_at_lsn_20[idx]
   10916            2 :                 );
   10917          100 :                 assert_eq!(
   10918          100 :                     tline
   10919          100 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10920          100 :                         .await
   10921          100 :                         .unwrap(),
   10922          100 :                     &expected_result_at_lsn_10[idx]
   10923            2 :                 );
   10924            2 :             }
   10925           20 :         };
   10926            2 : 
   10927            2 :         verify_result().await;
   10928            2 : 
   10929            2 :         let cancel = CancellationToken::new();
   10930            2 : 
   10931            2 :         tline
   10932            2 :             .compact_with_gc(
   10933            2 :                 &cancel,
   10934            2 :                 CompactOptions {
   10935            2 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10936            2 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   10937            2 :                     ..Default::default()
   10938            2 :                 },
   10939            2 :                 &ctx,
   10940            2 :             )
   10941            2 :             .await
   10942            2 :             .unwrap();
   10943            2 :         verify_result().await;
   10944            2 : 
   10945            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10946            2 :         check_layer_map_key_eq(
   10947            2 :             all_layers,
   10948            2 :             vec![
   10949            2 :                 // The original image layer, not compacted
   10950            2 :                 PersistentLayerKey {
   10951            2 :                     key_range: get_key(0)..get_key(10),
   10952            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10953            2 :                     is_delta: false,
   10954            2 :                 },
   10955            2 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   10956            2 :                 // the layer 0x28-0x30 into one.
   10957            2 :                 PersistentLayerKey {
   10958            2 :                     key_range: get_key(1)..get_key(2),
   10959            2 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   10960            2 :                     is_delta: true,
   10961            2 :                 },
   10962            2 :                 // Above the upper bound and untouched
   10963            2 :                 PersistentLayerKey {
   10964            2 :                     key_range: get_key(1)..get_key(2),
   10965            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   10966            2 :                     is_delta: true,
   10967            2 :                 },
   10968            2 :                 // This layer is untouched
   10969            2 :                 PersistentLayerKey {
   10970            2 :                     key_range: get_key(8)..get_key(10),
   10971            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   10972            2 :                     is_delta: true,
   10973            2 :                 },
   10974            2 :             ],
   10975            2 :         );
   10976            2 : 
   10977            2 :         tline
   10978            2 :             .compact_with_gc(
   10979            2 :                 &cancel,
   10980            2 :                 CompactOptions {
   10981            2 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   10982            2 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   10983            2 :                     ..Default::default()
   10984            2 :                 },
   10985            2 :                 &ctx,
   10986            2 :             )
   10987            2 :             .await
   10988            2 :             .unwrap();
   10989            2 :         verify_result().await;
   10990            2 : 
   10991            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10992            2 :         check_layer_map_key_eq(
   10993            2 :             all_layers,
   10994            2 :             vec![
   10995            2 :                 // The original image layer, not compacted
   10996            2 :                 PersistentLayerKey {
   10997            2 :                     key_range: get_key(0)..get_key(10),
   10998            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10999            2 :                     is_delta: false,
   11000            2 :                 },
   11001            2 :                 // Not in the compaction key range, uncompacted
   11002            2 :                 PersistentLayerKey {
   11003            2 :                     key_range: get_key(1)..get_key(2),
   11004            2 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11005            2 :                     is_delta: true,
   11006            2 :                 },
   11007            2 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11008            2 :                 PersistentLayerKey {
   11009            2 :                     key_range: get_key(1)..get_key(2),
   11010            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11011            2 :                     is_delta: true,
   11012            2 :                 },
   11013            2 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11014            2 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11015            2 :                 // becomes 0x50.
   11016            2 :                 PersistentLayerKey {
   11017            2 :                     key_range: get_key(8)..get_key(10),
   11018            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11019            2 :                     is_delta: true,
   11020            2 :                 },
   11021            2 :             ],
   11022            2 :         );
   11023            2 : 
   11024            2 :         // compact again
   11025            2 :         tline
   11026            2 :             .compact_with_gc(
   11027            2 :                 &cancel,
   11028            2 :                 CompactOptions {
   11029            2 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11030            2 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11031            2 :                     ..Default::default()
   11032            2 :                 },
   11033            2 :                 &ctx,
   11034            2 :             )
   11035            2 :             .await
   11036            2 :             .unwrap();
   11037            2 :         verify_result().await;
   11038            2 : 
   11039            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11040            2 :         check_layer_map_key_eq(
   11041            2 :             all_layers,
   11042            2 :             vec![
   11043            2 :                 // The original image layer, not compacted
   11044            2 :                 PersistentLayerKey {
   11045            2 :                     key_range: get_key(0)..get_key(10),
   11046            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11047            2 :                     is_delta: false,
   11048            2 :                 },
   11049            2 :                 // The range gets compacted
   11050            2 :                 PersistentLayerKey {
   11051            2 :                     key_range: get_key(1)..get_key(2),
   11052            2 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11053            2 :                     is_delta: true,
   11054            2 :                 },
   11055            2 :                 // Not touched during this iteration of compaction
   11056            2 :                 PersistentLayerKey {
   11057            2 :                     key_range: get_key(8)..get_key(10),
   11058            2 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11059            2 :                     is_delta: true,
   11060            2 :                 },
   11061            2 :             ],
   11062            2 :         );
   11063            2 : 
   11064            2 :         // final full compaction
   11065            2 :         tline
   11066            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11067            2 :             .await
   11068            2 :             .unwrap();
   11069            2 :         verify_result().await;
   11070            2 : 
   11071            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11072            2 :         check_layer_map_key_eq(
   11073            2 :             all_layers,
   11074            2 :             vec![
   11075            2 :                 // The compacted image layer (full key range)
   11076            2 :                 PersistentLayerKey {
   11077            2 :                     key_range: Key::MIN..Key::MAX,
   11078            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11079            2 :                     is_delta: false,
   11080            2 :                 },
   11081            2 :                 // All other data in the delta layer
   11082            2 :                 PersistentLayerKey {
   11083            2 :                     key_range: get_key(1)..get_key(10),
   11084            2 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11085            2 :                     is_delta: true,
   11086            2 :                 },
   11087            2 :             ],
   11088            2 :         );
   11089            2 : 
   11090            2 :         Ok(())
   11091            2 :     }
   11092              : }
        

Generated by: LCOV version 2.1-beta