LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 727bdccc1d7d53837da843959afb612f56da4e79.info Lines: 76.8 % 8465 6497
Test Date: 2025-01-30 15:18:43 Functions: 60.6 % 432 262

            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 remote_timeline_client::FAILED_REMOTE_OP_RETRIES;
      41              : use remote_timeline_client::FAILED_UPLOAD_WARN_THRESHOLD;
      42              : use std::collections::BTreeMap;
      43              : use std::fmt;
      44              : use std::future::Future;
      45              : use std::sync::atomic::AtomicBool;
      46              : use std::sync::Weak;
      47              : use std::time::SystemTime;
      48              : use storage_broker::BrokerClientChannel;
      49              : use timeline::compaction::GcCompactionQueue;
      50              : use timeline::import_pgdata;
      51              : use timeline::offload::offload_timeline;
      52              : use timeline::offload::OffloadError;
      53              : use timeline::CompactOptions;
      54              : use timeline::ShutdownMode;
      55              : use tokio::io::BufReader;
      56              : use tokio::sync::watch;
      57              : use tokio::task::JoinSet;
      58              : use tokio_util::sync::CancellationToken;
      59              : use tracing::*;
      60              : use upload_queue::NotInitialized;
      61              : use utils::backoff;
      62              : use utils::circuit_breaker::CircuitBreaker;
      63              : use utils::completion;
      64              : use utils::crashsafe::path_with_suffix_extension;
      65              : use utils::failpoint_support;
      66              : use utils::fs_ext;
      67              : use utils::pausable_failpoint;
      68              : use utils::sync::gate::Gate;
      69              : use utils::sync::gate::GateGuard;
      70              : use utils::timeout::timeout_cancellable;
      71              : use utils::timeout::TimeoutCancellableError;
      72              : use utils::try_rcu::ArcSwapExt;
      73              : use utils::zstd::create_zst_tarball;
      74              : use utils::zstd::extract_zst_tarball;
      75              : 
      76              : use self::config::AttachedLocationConfig;
      77              : use self::config::AttachmentMode;
      78              : use self::config::LocationConf;
      79              : use self::config::TenantConf;
      80              : use self::metadata::TimelineMetadata;
      81              : use self::mgr::GetActiveTenantError;
      82              : use self::mgr::GetTenantError;
      83              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      84              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      85              : use self::timeline::uninit::TimelineCreateGuard;
      86              : use self::timeline::uninit::TimelineExclusionError;
      87              : use self::timeline::uninit::UninitializedTimeline;
      88              : use self::timeline::EvictionTaskTenantState;
      89              : use self::timeline::GcCutoffs;
      90              : use self::timeline::TimelineDeleteProgress;
      91              : use self::timeline::TimelineResources;
      92              : use self::timeline::WaitLsnError;
      93              : use crate::config::PageServerConf;
      94              : use crate::context::{DownloadBehavior, RequestContext};
      95              : use crate::deletion_queue::DeletionQueueClient;
      96              : use crate::deletion_queue::DeletionQueueError;
      97              : use crate::import_datadir;
      98              : use crate::is_uninit_mark;
      99              : use crate::l0_flush::L0FlushGlobalState;
     100              : use crate::metrics::CONCURRENT_INITDBS;
     101              : use crate::metrics::INITDB_RUN_TIME;
     102              : use crate::metrics::INITDB_SEMAPHORE_ACQUISITION_TIME;
     103              : use crate::metrics::TENANT;
     104              : use crate::metrics::{
     105              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
     106              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
     107              : };
     108              : use crate::task_mgr;
     109              : use crate::task_mgr::TaskKind;
     110              : use crate::tenant::config::LocationMode;
     111              : use crate::tenant::config::TenantConfOpt;
     112              : use crate::tenant::gc_result::GcResult;
     113              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     114              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     115              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     116              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     117              : use crate::tenant::storage_layer::DeltaLayer;
     118              : use crate::tenant::storage_layer::ImageLayer;
     119              : use crate::walingest::WalLagCooldown;
     120              : use crate::walredo;
     121              : use crate::InitializationOrder;
     122              : use std::collections::hash_map::Entry;
     123              : use std::collections::HashMap;
     124              : use std::collections::HashSet;
     125              : use std::fmt::Debug;
     126              : use std::fmt::Display;
     127              : use std::fs;
     128              : use std::fs::File;
     129              : use std::sync::atomic::{AtomicU64, Ordering};
     130              : use std::sync::Arc;
     131              : use std::sync::Mutex;
     132              : use std::time::{Duration, Instant};
     133              : 
     134              : use crate::span;
     135              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     136              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     137              : use crate::virtual_file::VirtualFile;
     138              : use crate::walredo::PostgresRedoManager;
     139              : use crate::TEMP_FILE_SUFFIX;
     140              : use once_cell::sync::Lazy;
     141              : pub use pageserver_api::models::TenantState;
     142              : use tokio::sync::Semaphore;
     143              : 
     144            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     145              : use utils::{
     146              :     crashsafe,
     147              :     generation::Generation,
     148              :     id::TimelineId,
     149              :     lsn::{Lsn, RecordLsn},
     150              : };
     151              : 
     152              : pub mod blob_io;
     153              : pub mod block_io;
     154              : pub mod vectored_blob_io;
     155              : 
     156              : pub mod disk_btree;
     157              : pub(crate) mod ephemeral_file;
     158              : pub mod layer_map;
     159              : 
     160              : pub mod metadata;
     161              : pub mod remote_timeline_client;
     162              : pub mod storage_layer;
     163              : 
     164              : pub mod checks;
     165              : pub mod config;
     166              : pub mod mgr;
     167              : pub mod secondary;
     168              : pub mod tasks;
     169              : pub mod upload_queue;
     170              : 
     171              : pub(crate) mod timeline;
     172              : 
     173              : pub mod size;
     174              : 
     175              : mod gc_block;
     176              : mod gc_result;
     177              : pub(crate) mod throttle;
     178              : 
     179              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     180              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     181              : 
     182              : // re-export for use in walreceiver
     183              : pub use crate::tenant::timeline::WalReceiverInfo;
     184              : 
     185              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     186              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     187              : 
     188              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     189              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     190              : 
     191              : /// References to shared objects that are passed into each tenant, such
     192              : /// as the shared remote storage client and process initialization state.
     193              : #[derive(Clone)]
     194              : pub struct TenantSharedResources {
     195              :     pub broker_client: storage_broker::BrokerClientChannel,
     196              :     pub remote_storage: GenericRemoteStorage,
     197              :     pub deletion_queue_client: DeletionQueueClient,
     198              :     pub l0_flush_global_state: L0FlushGlobalState,
     199              : }
     200              : 
     201              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     202              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     203              : /// in this struct.
     204              : #[derive(Clone)]
     205              : pub(super) struct AttachedTenantConf {
     206              :     tenant_conf: TenantConfOpt,
     207              :     location: AttachedLocationConfig,
     208              :     /// The deadline before which we are blocked from GC so that
     209              :     /// leases have a chance to be renewed.
     210              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     211              : }
     212              : 
     213              : impl AttachedTenantConf {
     214          440 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     215              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     216              :         //
     217              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     218              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     219              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     220          440 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     221          440 :             Some(
     222          440 :                 tokio::time::Instant::now()
     223          440 :                     + tenant_conf
     224          440 :                         .lsn_lease_length
     225          440 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     226          440 :             )
     227              :         } else {
     228              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     229              :             // because we don't do GC in these modes.
     230            0 :             None
     231              :         };
     232              : 
     233          440 :         Self {
     234          440 :             tenant_conf,
     235          440 :             location,
     236          440 :             lsn_lease_deadline,
     237          440 :         }
     238          440 :     }
     239              : 
     240          440 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     241          440 :         match &location_conf.mode {
     242          440 :             LocationMode::Attached(attach_conf) => {
     243          440 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     244              :             }
     245              :             LocationMode::Secondary(_) => {
     246            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     247              :             }
     248              :         }
     249          440 :     }
     250              : 
     251         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     252         1524 :         self.lsn_lease_deadline
     253         1524 :             .map(|d| tokio::time::Instant::now() < d)
     254         1524 :             .unwrap_or(false)
     255         1524 :     }
     256              : }
     257              : struct TimelinePreload {
     258              :     timeline_id: TimelineId,
     259              :     client: RemoteTimelineClient,
     260              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     261              : }
     262              : 
     263              : pub(crate) struct TenantPreload {
     264              :     tenant_manifest: TenantManifest,
     265              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     266              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     267              : }
     268              : 
     269              : /// When we spawn a tenant, there is a special mode for tenant creation that
     270              : /// avoids trying to read anything from remote storage.
     271              : pub(crate) enum SpawnMode {
     272              :     /// Activate as soon as possible
     273              :     Eager,
     274              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     275              :     Lazy,
     276              : }
     277              : 
     278              : ///
     279              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     280              : ///
     281              : pub struct Tenant {
     282              :     // Global pageserver config parameters
     283              :     pub conf: &'static PageServerConf,
     284              : 
     285              :     /// The value creation timestamp, used to measure activation delay, see:
     286              :     /// <https://github.com/neondatabase/neon/issues/4025>
     287              :     constructed_at: Instant,
     288              : 
     289              :     state: watch::Sender<TenantState>,
     290              : 
     291              :     // Overridden tenant-specific config parameters.
     292              :     // We keep TenantConfOpt sturct here to preserve the information
     293              :     // about parameters that are not set.
     294              :     // This is necessary to allow global config updates.
     295              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     296              : 
     297              :     tenant_shard_id: TenantShardId,
     298              : 
     299              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     300              :     shard_identity: ShardIdentity,
     301              : 
     302              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     303              :     /// Does not change over the lifetime of the [`Tenant`] object.
     304              :     ///
     305              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     306              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     307              :     generation: Generation,
     308              : 
     309              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     310              : 
     311              :     /// During timeline creation, we first insert the TimelineId to the
     312              :     /// creating map, then `timelines`, then remove it from the creating map.
     313              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     314              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     315              : 
     316              :     /// Possibly offloaded and archived timelines
     317              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     318              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     319              : 
     320              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     321              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     322              :     /// each other (this could be optimized to coalesce writes if necessary).
     323              :     ///
     324              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     325              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     326              : 
     327              :     // This mutex prevents creation of new timelines during GC.
     328              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     329              :     // `timelines` mutex during all GC iteration
     330              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     331              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     332              :     // timeout...
     333              :     gc_cs: tokio::sync::Mutex<()>,
     334              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     335              : 
     336              :     // provides access to timeline data sitting in the remote storage
     337              :     pub(crate) remote_storage: GenericRemoteStorage,
     338              : 
     339              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     340              :     deletion_queue_client: DeletionQueueClient,
     341              : 
     342              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     343              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     344              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     345              : 
     346              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     347              : 
     348              :     /// Track repeated failures to compact, so that we can back off.
     349              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     350              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     351              : 
     352              :     /// Scheduled gc-compaction tasks.
     353              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     354              : 
     355              :     /// If the tenant is in Activating state, notify this to encourage it
     356              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     357              :     /// background warmup.
     358              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     359              : 
     360              :     /// Time it took for the tenant to activate. Zero if not active yet.
     361              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     362              : 
     363              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     364              :     // Timelines' cancellation token.
     365              :     pub(crate) cancel: CancellationToken,
     366              : 
     367              :     // Users of the Tenant such as the page service must take this Gate to avoid
     368              :     // trying to use a Tenant which is shutting down.
     369              :     pub(crate) gate: Gate,
     370              : 
     371              :     /// Throttle applied at the top of [`Timeline::get`].
     372              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     373              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     374              : 
     375              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     376              : 
     377              :     /// An ongoing timeline detach concurrency limiter.
     378              :     ///
     379              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     380              :     /// to have two running at the same time. A different one can be started if an earlier one
     381              :     /// has failed for whatever reason.
     382              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     383              : 
     384              :     /// `index_part.json` based gc blocking reason tracking.
     385              :     ///
     386              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     387              :     /// proceeding.
     388              :     pub(crate) gc_block: gc_block::GcBlock,
     389              : 
     390              :     l0_flush_global_state: L0FlushGlobalState,
     391              : }
     392              : impl std::fmt::Debug for Tenant {
     393            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     394            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     395            0 :     }
     396              : }
     397              : 
     398              : pub(crate) enum WalRedoManager {
     399              :     Prod(WalredoManagerId, PostgresRedoManager),
     400              :     #[cfg(test)]
     401              :     Test(harness::TestRedoManager),
     402              : }
     403              : 
     404              : #[derive(thiserror::Error, Debug)]
     405              : #[error("pageserver is shutting down")]
     406              : pub(crate) struct GlobalShutDown;
     407              : 
     408              : impl WalRedoManager {
     409            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     410            0 :         let id = WalredoManagerId::next();
     411            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     412            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     413            0 :         match &mut *guard {
     414            0 :             Some(map) => {
     415            0 :                 map.insert(id, Arc::downgrade(&arc));
     416            0 :                 Ok(arc)
     417              :             }
     418            0 :             None => Err(GlobalShutDown),
     419              :         }
     420            0 :     }
     421              : }
     422              : 
     423              : impl Drop for WalRedoManager {
     424           20 :     fn drop(&mut self) {
     425           20 :         match self {
     426            0 :             Self::Prod(id, _) => {
     427            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     428            0 :                 if let Some(map) = &mut *guard {
     429            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     430            0 :                 }
     431              :             }
     432              :             #[cfg(test)]
     433           20 :             Self::Test(_) => {
     434           20 :                 // Not applicable to test redo manager
     435           20 :             }
     436              :         }
     437           20 :     }
     438              : }
     439              : 
     440              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     441              : /// the walredo processes outside of the regular order.
     442              : ///
     443              : /// This is necessary to work around a systemd bug where it freezes if there are
     444              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     445              : #[allow(clippy::type_complexity)]
     446              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     447              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     448            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     449              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     450              : pub(crate) struct WalredoManagerId(u64);
     451              : impl WalredoManagerId {
     452            0 :     pub fn next() -> Self {
     453              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     454            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     455            0 :         if id == 0 {
     456            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     457            0 :         }
     458            0 :         Self(id)
     459            0 :     }
     460              : }
     461              : 
     462              : #[cfg(test)]
     463              : impl From<harness::TestRedoManager> for WalRedoManager {
     464          440 :     fn from(mgr: harness::TestRedoManager) -> Self {
     465          440 :         Self::Test(mgr)
     466          440 :     }
     467              : }
     468              : 
     469              : impl WalRedoManager {
     470           12 :     pub(crate) async fn shutdown(&self) -> bool {
     471           12 :         match self {
     472            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     473              :             #[cfg(test)]
     474              :             Self::Test(_) => {
     475              :                 // Not applicable to test redo manager
     476           12 :                 true
     477              :             }
     478              :         }
     479           12 :     }
     480              : 
     481            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     482            0 :         match self {
     483            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     484            0 :             #[cfg(test)]
     485            0 :             Self::Test(_) => {
     486            0 :                 // Not applicable to test redo manager
     487            0 :             }
     488            0 :         }
     489            0 :     }
     490              : 
     491              :     /// # Cancel-Safety
     492              :     ///
     493              :     /// This method is cancellation-safe.
     494         1636 :     pub async fn request_redo(
     495         1636 :         &self,
     496         1636 :         key: pageserver_api::key::Key,
     497         1636 :         lsn: Lsn,
     498         1636 :         base_img: Option<(Lsn, bytes::Bytes)>,
     499         1636 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     500         1636 :         pg_version: u32,
     501         1636 :     ) -> Result<bytes::Bytes, walredo::Error> {
     502         1636 :         match self {
     503            0 :             Self::Prod(_, mgr) => {
     504            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     505            0 :                     .await
     506              :             }
     507              :             #[cfg(test)]
     508         1636 :             Self::Test(mgr) => {
     509         1636 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     510         1636 :                     .await
     511              :             }
     512              :         }
     513         1636 :     }
     514              : 
     515            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     516            0 :         match self {
     517            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     518            0 :             #[cfg(test)]
     519            0 :             WalRedoManager::Test(_) => None,
     520            0 :         }
     521            0 :     }
     522              : }
     523              : 
     524              : /// A very lightweight memory representation of an offloaded timeline.
     525              : ///
     526              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     527              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     528              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     529              : /// more offloaded timelines than we can manage ones that aren't.
     530              : pub struct OffloadedTimeline {
     531              :     pub tenant_shard_id: TenantShardId,
     532              :     pub timeline_id: TimelineId,
     533              :     pub ancestor_timeline_id: Option<TimelineId>,
     534              :     /// Whether to retain the branch lsn at the ancestor or not
     535              :     pub ancestor_retain_lsn: Option<Lsn>,
     536              : 
     537              :     /// When the timeline was archived.
     538              :     ///
     539              :     /// Present for future flattening deliberations.
     540              :     pub archived_at: NaiveDateTime,
     541              : 
     542              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     543              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     544              :     pub delete_progress: TimelineDeleteProgress,
     545              : 
     546              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     547              :     pub deleted_from_ancestor: AtomicBool,
     548              : }
     549              : 
     550              : impl OffloadedTimeline {
     551              :     /// Obtains an offloaded timeline from a given timeline object.
     552              :     ///
     553              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     554              :     /// the timeline is not in a stopped state.
     555              :     /// Panics if the timeline is not archived.
     556            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     557            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     558            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     559            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     560            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     561            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     562            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     563            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     564              :             } else {
     565            0 :                 (None, None)
     566              :             };
     567            4 :         let archived_at = timeline
     568            4 :             .remote_client
     569            4 :             .archived_at_stopped_queue()?
     570            4 :             .expect("must be called on an archived timeline");
     571            4 :         Ok(Self {
     572            4 :             tenant_shard_id: timeline.tenant_shard_id,
     573            4 :             timeline_id: timeline.timeline_id,
     574            4 :             ancestor_timeline_id,
     575            4 :             ancestor_retain_lsn,
     576            4 :             archived_at,
     577            4 : 
     578            4 :             delete_progress: timeline.delete_progress.clone(),
     579            4 :             deleted_from_ancestor: AtomicBool::new(false),
     580            4 :         })
     581            4 :     }
     582            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     583            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     584            0 :         // by the `initialize_gc_info` function.
     585            0 :         let OffloadedTimelineManifest {
     586            0 :             timeline_id,
     587            0 :             ancestor_timeline_id,
     588            0 :             ancestor_retain_lsn,
     589            0 :             archived_at,
     590            0 :         } = *manifest;
     591            0 :         Self {
     592            0 :             tenant_shard_id,
     593            0 :             timeline_id,
     594            0 :             ancestor_timeline_id,
     595            0 :             ancestor_retain_lsn,
     596            0 :             archived_at,
     597            0 :             delete_progress: TimelineDeleteProgress::default(),
     598            0 :             deleted_from_ancestor: AtomicBool::new(false),
     599            0 :         }
     600            0 :     }
     601            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     602            4 :         let Self {
     603            4 :             timeline_id,
     604            4 :             ancestor_timeline_id,
     605            4 :             ancestor_retain_lsn,
     606            4 :             archived_at,
     607            4 :             ..
     608            4 :         } = self;
     609            4 :         OffloadedTimelineManifest {
     610            4 :             timeline_id: *timeline_id,
     611            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     612            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     613            4 :             archived_at: *archived_at,
     614            4 :         }
     615            4 :     }
     616              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     617            0 :     fn delete_from_ancestor_with_timelines(
     618            0 :         &self,
     619            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     620            0 :     ) {
     621            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     622            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     623              :         {
     624            0 :             if let Some((_, ancestor_timeline)) = timelines
     625            0 :                 .iter()
     626            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     627              :             {
     628            0 :                 let removal_happened = ancestor_timeline
     629            0 :                     .gc_info
     630            0 :                     .write()
     631            0 :                     .unwrap()
     632            0 :                     .remove_child_offloaded(self.timeline_id);
     633            0 :                 if !removal_happened {
     634            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     635            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     636            0 :                 }
     637            0 :             }
     638            0 :         }
     639            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     640            0 :     }
     641              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     642              :     ///
     643              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     644            4 :     fn defuse_for_tenant_drop(&self) {
     645            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     646            4 :     }
     647              : }
     648              : 
     649              : impl fmt::Debug for OffloadedTimeline {
     650            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     651            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     652            0 :     }
     653              : }
     654              : 
     655              : impl Drop for OffloadedTimeline {
     656            4 :     fn drop(&mut self) {
     657            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     658            0 :             tracing::warn!(
     659            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     660              :                 self.timeline_id
     661              :             );
     662            4 :         }
     663            4 :     }
     664              : }
     665              : 
     666              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     667              : pub enum MaybeOffloaded {
     668              :     Yes,
     669              :     No,
     670              : }
     671              : 
     672              : #[derive(Clone, Debug)]
     673              : pub enum TimelineOrOffloaded {
     674              :     Timeline(Arc<Timeline>),
     675              :     Offloaded(Arc<OffloadedTimeline>),
     676              : }
     677              : 
     678              : impl TimelineOrOffloaded {
     679            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     680            0 :         match self {
     681            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     682            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     683              :             }
     684            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     685            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     686              :             }
     687              :         }
     688            0 :     }
     689            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     690            0 :         self.arc_ref().tenant_shard_id()
     691            0 :     }
     692            0 :     pub fn timeline_id(&self) -> TimelineId {
     693            0 :         self.arc_ref().timeline_id()
     694            0 :     }
     695            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     696            4 :         match self {
     697            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     698            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     699              :         }
     700            4 :     }
     701            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     702            0 :         match self {
     703            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     704            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     705              :         }
     706            0 :     }
     707              : }
     708              : 
     709              : pub enum TimelineOrOffloadedArcRef<'a> {
     710              :     Timeline(&'a Arc<Timeline>),
     711              :     Offloaded(&'a Arc<OffloadedTimeline>),
     712              : }
     713              : 
     714              : impl TimelineOrOffloadedArcRef<'_> {
     715            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     716            0 :         match self {
     717            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     718            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     719              :         }
     720            0 :     }
     721            0 :     pub fn timeline_id(&self) -> TimelineId {
     722            0 :         match self {
     723            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     724            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     725              :         }
     726            0 :     }
     727              : }
     728              : 
     729              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     730            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     731            0 :         Self::Timeline(timeline)
     732            0 :     }
     733              : }
     734              : 
     735              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     736            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     737            0 :         Self::Offloaded(timeline)
     738            0 :     }
     739              : }
     740              : 
     741              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     742              : pub enum GetTimelineError {
     743              :     #[error("Timeline is shutting down")]
     744              :     ShuttingDown,
     745              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     746              :     NotActive {
     747              :         tenant_id: TenantShardId,
     748              :         timeline_id: TimelineId,
     749              :         state: TimelineState,
     750              :     },
     751              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     752              :     NotFound {
     753              :         tenant_id: TenantShardId,
     754              :         timeline_id: TimelineId,
     755              :     },
     756              : }
     757              : 
     758              : #[derive(Debug, thiserror::Error)]
     759              : pub enum LoadLocalTimelineError {
     760              :     #[error("FailedToLoad")]
     761              :     Load(#[source] anyhow::Error),
     762              :     #[error("FailedToResumeDeletion")]
     763              :     ResumeDeletion(#[source] anyhow::Error),
     764              : }
     765              : 
     766              : #[derive(thiserror::Error)]
     767              : pub enum DeleteTimelineError {
     768              :     #[error("NotFound")]
     769              :     NotFound,
     770              : 
     771              :     #[error("HasChildren")]
     772              :     HasChildren(Vec<TimelineId>),
     773              : 
     774              :     #[error("Timeline deletion is already in progress")]
     775              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     776              : 
     777              :     #[error("Cancelled")]
     778              :     Cancelled,
     779              : 
     780              :     #[error(transparent)]
     781              :     Other(#[from] anyhow::Error),
     782              : }
     783              : 
     784              : impl Debug for DeleteTimelineError {
     785            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     786            0 :         match self {
     787            0 :             Self::NotFound => write!(f, "NotFound"),
     788            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     789            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     790            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     791            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     792              :         }
     793            0 :     }
     794              : }
     795              : 
     796              : #[derive(thiserror::Error)]
     797              : pub enum TimelineArchivalError {
     798              :     #[error("NotFound")]
     799              :     NotFound,
     800              : 
     801              :     #[error("Timeout")]
     802              :     Timeout,
     803              : 
     804              :     #[error("Cancelled")]
     805              :     Cancelled,
     806              : 
     807              :     #[error("ancestor is archived: {}", .0)]
     808              :     HasArchivedParent(TimelineId),
     809              : 
     810              :     #[error("HasUnarchivedChildren")]
     811              :     HasUnarchivedChildren(Vec<TimelineId>),
     812              : 
     813              :     #[error("Timeline archival is already in progress")]
     814              :     AlreadyInProgress,
     815              : 
     816              :     #[error(transparent)]
     817              :     Other(anyhow::Error),
     818              : }
     819              : 
     820              : #[derive(thiserror::Error, Debug)]
     821              : pub(crate) enum TenantManifestError {
     822              :     #[error("Remote storage error: {0}")]
     823              :     RemoteStorage(anyhow::Error),
     824              : 
     825              :     #[error("Cancelled")]
     826              :     Cancelled,
     827              : }
     828              : 
     829              : impl From<TenantManifestError> for TimelineArchivalError {
     830            0 :     fn from(e: TenantManifestError) -> Self {
     831            0 :         match e {
     832            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     833            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     834              :         }
     835            0 :     }
     836              : }
     837              : 
     838              : impl Debug for TimelineArchivalError {
     839            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     840            0 :         match self {
     841            0 :             Self::NotFound => write!(f, "NotFound"),
     842            0 :             Self::Timeout => write!(f, "Timeout"),
     843            0 :             Self::Cancelled => write!(f, "Cancelled"),
     844            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     845            0 :             Self::HasUnarchivedChildren(c) => {
     846            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     847              :             }
     848            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     849            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     850              :         }
     851            0 :     }
     852              : }
     853              : 
     854              : pub enum SetStoppingError {
     855              :     AlreadyStopping(completion::Barrier),
     856              :     Broken,
     857              : }
     858              : 
     859              : impl Debug for SetStoppingError {
     860            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     861            0 :         match self {
     862            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     863            0 :             Self::Broken => write!(f, "Broken"),
     864              :         }
     865            0 :     }
     866              : }
     867              : 
     868              : /// Arguments to [`Tenant::create_timeline`].
     869              : ///
     870              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     871              : /// is `None`, the result of the timeline create call is not deterministic.
     872              : ///
     873              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     874              : #[derive(Debug)]
     875              : pub(crate) enum CreateTimelineParams {
     876              :     Bootstrap(CreateTimelineParamsBootstrap),
     877              :     Branch(CreateTimelineParamsBranch),
     878              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     879              : }
     880              : 
     881              : #[derive(Debug)]
     882              : pub(crate) struct CreateTimelineParamsBootstrap {
     883              :     pub(crate) new_timeline_id: TimelineId,
     884              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     885              :     pub(crate) pg_version: u32,
     886              : }
     887              : 
     888              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     889              : #[derive(Debug)]
     890              : pub(crate) struct CreateTimelineParamsBranch {
     891              :     pub(crate) new_timeline_id: TimelineId,
     892              :     pub(crate) ancestor_timeline_id: TimelineId,
     893              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     894              : }
     895              : 
     896              : #[derive(Debug)]
     897              : pub(crate) struct CreateTimelineParamsImportPgdata {
     898              :     pub(crate) new_timeline_id: TimelineId,
     899              :     pub(crate) location: import_pgdata::index_part_format::Location,
     900              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     901              : }
     902              : 
     903              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     904              : ///
     905              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     906              : ///
     907              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     908              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     909              : ///
     910              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     911              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     912              : ///
     913              : /// Notes:
     914              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     915              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     916              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     917              : ///
     918              : #[derive(Debug, Clone, PartialEq, Eq)]
     919              : pub(crate) enum CreateTimelineIdempotency {
     920              :     /// NB: special treatment, see comment in [`Self`].
     921              :     FailWithConflict,
     922              :     Bootstrap {
     923              :         pg_version: u32,
     924              :     },
     925              :     /// NB: branches always have the same `pg_version` as their ancestor.
     926              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     927              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     928              :     /// determining the child branch pg_version.
     929              :     Branch {
     930              :         ancestor_timeline_id: TimelineId,
     931              :         ancestor_start_lsn: Lsn,
     932              :     },
     933              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     934              : }
     935              : 
     936              : #[derive(Debug, Clone, PartialEq, Eq)]
     937              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     938              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     939              : }
     940              : 
     941              : /// What is returned by [`Tenant::start_creating_timeline`].
     942              : #[must_use]
     943              : enum StartCreatingTimelineResult {
     944              :     CreateGuard(TimelineCreateGuard),
     945              :     Idempotent(Arc<Timeline>),
     946              : }
     947              : 
     948              : enum TimelineInitAndSyncResult {
     949              :     ReadyToActivate(Arc<Timeline>),
     950              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     951              : }
     952              : 
     953              : impl TimelineInitAndSyncResult {
     954            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     955            0 :         match self {
     956            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     957            0 :             _ => None,
     958              :         }
     959            0 :     }
     960              : }
     961              : 
     962              : #[must_use]
     963              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     964              :     timeline: Arc<Timeline>,
     965              :     import_pgdata: import_pgdata::index_part_format::Root,
     966              :     guard: TimelineCreateGuard,
     967              : }
     968              : 
     969              : /// What is returned by [`Tenant::create_timeline`].
     970              : enum CreateTimelineResult {
     971              :     Created(Arc<Timeline>),
     972              :     Idempotent(Arc<Timeline>),
     973              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     974              :     /// we return this result, nor will this concrete object ever be added there.
     975              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     976              :     ImportSpawned(Arc<Timeline>),
     977              : }
     978              : 
     979              : impl CreateTimelineResult {
     980            0 :     fn discriminant(&self) -> &'static str {
     981            0 :         match self {
     982            0 :             Self::Created(_) => "Created",
     983            0 :             Self::Idempotent(_) => "Idempotent",
     984            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     985              :         }
     986            0 :     }
     987            0 :     fn timeline(&self) -> &Arc<Timeline> {
     988            0 :         match self {
     989            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     990            0 :         }
     991            0 :     }
     992              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     993              :     #[cfg(test)]
     994          460 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     995          460 :         match self {
     996          460 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     997          460 :         }
     998          460 :     }
     999              : }
    1000              : 
    1001              : #[derive(thiserror::Error, Debug)]
    1002              : pub enum CreateTimelineError {
    1003              :     #[error("creation of timeline with the given ID is in progress")]
    1004              :     AlreadyCreating,
    1005              :     #[error("timeline already exists with different parameters")]
    1006              :     Conflict,
    1007              :     #[error(transparent)]
    1008              :     AncestorLsn(anyhow::Error),
    1009              :     #[error("ancestor timeline is not active")]
    1010              :     AncestorNotActive,
    1011              :     #[error("ancestor timeline is archived")]
    1012              :     AncestorArchived,
    1013              :     #[error("tenant shutting down")]
    1014              :     ShuttingDown,
    1015              :     #[error(transparent)]
    1016              :     Other(#[from] anyhow::Error),
    1017              : }
    1018              : 
    1019              : #[derive(thiserror::Error, Debug)]
    1020              : pub enum InitdbError {
    1021              :     #[error("Operation was cancelled")]
    1022              :     Cancelled,
    1023              :     #[error(transparent)]
    1024              :     Other(anyhow::Error),
    1025              :     #[error(transparent)]
    1026              :     Inner(postgres_initdb::Error),
    1027              : }
    1028              : 
    1029              : enum CreateTimelineCause {
    1030              :     Load,
    1031              :     Delete,
    1032              : }
    1033              : 
    1034              : enum LoadTimelineCause {
    1035              :     Attach,
    1036              :     Unoffload,
    1037              :     ImportPgdata {
    1038              :         create_guard: TimelineCreateGuard,
    1039              :         activate: ActivateTimelineArgs,
    1040              :     },
    1041              : }
    1042              : 
    1043              : #[derive(thiserror::Error, Debug)]
    1044              : pub(crate) enum GcError {
    1045              :     // The tenant is shutting down
    1046              :     #[error("tenant shutting down")]
    1047              :     TenantCancelled,
    1048              : 
    1049              :     // The tenant is shutting down
    1050              :     #[error("timeline shutting down")]
    1051              :     TimelineCancelled,
    1052              : 
    1053              :     // The tenant is in a state inelegible to run GC
    1054              :     #[error("not active")]
    1055              :     NotActive,
    1056              : 
    1057              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1058              :     #[error("not active")]
    1059              :     BadLsn { why: String },
    1060              : 
    1061              :     // A remote storage error while scheduling updates after compaction
    1062              :     #[error(transparent)]
    1063              :     Remote(anyhow::Error),
    1064              : 
    1065              :     // An error reading while calculating GC cutoffs
    1066              :     #[error(transparent)]
    1067              :     GcCutoffs(PageReconstructError),
    1068              : 
    1069              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1070              :     #[error("timeline not found")]
    1071              :     TimelineNotFound,
    1072              : }
    1073              : 
    1074              : impl From<PageReconstructError> for GcError {
    1075            0 :     fn from(value: PageReconstructError) -> Self {
    1076            0 :         match value {
    1077            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1078            0 :             other => Self::GcCutoffs(other),
    1079              :         }
    1080            0 :     }
    1081              : }
    1082              : 
    1083              : impl From<NotInitialized> for GcError {
    1084            0 :     fn from(value: NotInitialized) -> Self {
    1085            0 :         match value {
    1086            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1087            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1088              :         }
    1089            0 :     }
    1090              : }
    1091              : 
    1092              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1093            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1094            0 :         GcError::TimelineCancelled
    1095            0 :     }
    1096              : }
    1097              : 
    1098              : #[derive(thiserror::Error, Debug)]
    1099              : pub(crate) enum LoadConfigError {
    1100              :     #[error("TOML deserialization error: '{0}'")]
    1101              :     DeserializeToml(#[from] toml_edit::de::Error),
    1102              : 
    1103              :     #[error("Config not found at {0}")]
    1104              :     NotFound(Utf8PathBuf),
    1105              : }
    1106              : 
    1107              : impl Tenant {
    1108              :     /// Yet another helper for timeline initialization.
    1109              :     ///
    1110              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1111              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1112              :     /// - Downloads remote index file and adds remote files to the layer map
    1113              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1114              :     ///
    1115              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1116              :     /// it is marked as Active.
    1117              :     #[allow(clippy::too_many_arguments)]
    1118           12 :     async fn timeline_init_and_sync(
    1119           12 :         self: &Arc<Self>,
    1120           12 :         timeline_id: TimelineId,
    1121           12 :         resources: TimelineResources,
    1122           12 :         mut index_part: IndexPart,
    1123           12 :         metadata: TimelineMetadata,
    1124           12 :         ancestor: Option<Arc<Timeline>>,
    1125           12 :         cause: LoadTimelineCause,
    1126           12 :         ctx: &RequestContext,
    1127           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1128           12 :         let tenant_id = self.tenant_shard_id;
    1129           12 : 
    1130           12 :         let import_pgdata = index_part.import_pgdata.take();
    1131           12 :         let idempotency = match &import_pgdata {
    1132            0 :             Some(import_pgdata) => {
    1133            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1134            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1135            0 :                 })
    1136              :             }
    1137              :             None => {
    1138           12 :                 if metadata.ancestor_timeline().is_none() {
    1139            8 :                     CreateTimelineIdempotency::Bootstrap {
    1140            8 :                         pg_version: metadata.pg_version(),
    1141            8 :                     }
    1142              :                 } else {
    1143            4 :                     CreateTimelineIdempotency::Branch {
    1144            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1145            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1146            4 :                     }
    1147              :                 }
    1148              :             }
    1149              :         };
    1150              : 
    1151           12 :         let timeline = self.create_timeline_struct(
    1152           12 :             timeline_id,
    1153           12 :             &metadata,
    1154           12 :             ancestor.clone(),
    1155           12 :             resources,
    1156           12 :             CreateTimelineCause::Load,
    1157           12 :             idempotency.clone(),
    1158           12 :         )?;
    1159           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1160           12 :         anyhow::ensure!(
    1161           12 :             disk_consistent_lsn.is_valid(),
    1162            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1163              :         );
    1164           12 :         assert_eq!(
    1165           12 :             disk_consistent_lsn,
    1166           12 :             metadata.disk_consistent_lsn(),
    1167            0 :             "these are used interchangeably"
    1168              :         );
    1169              : 
    1170           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1171              : 
    1172           12 :         timeline
    1173           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1174           12 :             .await
    1175           12 :             .with_context(|| {
    1176            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1177           12 :             })?;
    1178              : 
    1179            0 :         match import_pgdata {
    1180            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1181            0 :                 match cause {
    1182            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1183              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1184            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1185              :                     }
    1186              :                 }
    1187            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1188            0 :                 if !guard.insert(timeline_id) {
    1189              :                     // We should never try and load the same timeline twice during startup
    1190            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1191            0 :                 }
    1192            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1193            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1194            0 :                     owning_tenant: self.clone(),
    1195            0 :                     timeline_id,
    1196            0 :                     idempotency,
    1197            0 :                     // The users of this specific return value don't need the timline_path in there.
    1198            0 :                     timeline_path: timeline
    1199            0 :                         .conf
    1200            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1201            0 :                 };
    1202            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1203            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1204            0 :                         timeline,
    1205            0 :                         import_pgdata,
    1206            0 :                         guard: timeline_create_guard,
    1207            0 :                     },
    1208            0 :                 ))
    1209              :             }
    1210              :             Some(_) | None => {
    1211              :                 {
    1212           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1213           12 :                     match timelines_accessor.entry(timeline_id) {
    1214              :                         // We should never try and load the same timeline twice during startup
    1215              :                         Entry::Occupied(_) => {
    1216            0 :                             unreachable!(
    1217            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1218            0 :                         );
    1219              :                         }
    1220           12 :                         Entry::Vacant(v) => {
    1221           12 :                             v.insert(Arc::clone(&timeline));
    1222           12 :                             timeline.maybe_spawn_flush_loop();
    1223           12 :                         }
    1224              :                     }
    1225              :                 }
    1226              : 
    1227              :                 // Sanity check: a timeline should have some content.
    1228           12 :                 anyhow::ensure!(
    1229           12 :                     ancestor.is_some()
    1230            8 :                         || timeline
    1231            8 :                             .layers
    1232            8 :                             .read()
    1233            8 :                             .await
    1234            8 :                             .layer_map()
    1235            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1236            8 :                             .iter_historic_layers()
    1237            8 :                             .next()
    1238            8 :                             .is_some(),
    1239            0 :                     "Timeline has no ancestor and no layer files"
    1240              :                 );
    1241              : 
    1242           12 :                 match cause {
    1243           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1244              :                     LoadTimelineCause::ImportPgdata {
    1245            0 :                         create_guard,
    1246            0 :                         activate,
    1247            0 :                     } => {
    1248            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1249            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1250            0 :                         match activate {
    1251            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1252            0 :                                 info!("activating timeline after reload from pgdata import task");
    1253            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1254              :                             }
    1255            0 :                             ActivateTimelineArgs::No => (),
    1256              :                         }
    1257            0 :                         drop(create_guard);
    1258              :                     }
    1259              :                 }
    1260              : 
    1261           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1262              :             }
    1263              :         }
    1264           12 :     }
    1265              : 
    1266              :     /// Attach a tenant that's available in cloud storage.
    1267              :     ///
    1268              :     /// This returns quickly, after just creating the in-memory object
    1269              :     /// Tenant struct and launching a background task to download
    1270              :     /// the remote index files.  On return, the tenant is most likely still in
    1271              :     /// Attaching state, and it will become Active once the background task
    1272              :     /// finishes. You can use wait_until_active() to wait for the task to
    1273              :     /// complete.
    1274              :     ///
    1275              :     #[allow(clippy::too_many_arguments)]
    1276            0 :     pub(crate) fn spawn(
    1277            0 :         conf: &'static PageServerConf,
    1278            0 :         tenant_shard_id: TenantShardId,
    1279            0 :         resources: TenantSharedResources,
    1280            0 :         attached_conf: AttachedTenantConf,
    1281            0 :         shard_identity: ShardIdentity,
    1282            0 :         init_order: Option<InitializationOrder>,
    1283            0 :         mode: SpawnMode,
    1284            0 :         ctx: &RequestContext,
    1285            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1286            0 :         let wal_redo_manager =
    1287            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1288              : 
    1289              :         let TenantSharedResources {
    1290            0 :             broker_client,
    1291            0 :             remote_storage,
    1292            0 :             deletion_queue_client,
    1293            0 :             l0_flush_global_state,
    1294            0 :         } = resources;
    1295            0 : 
    1296            0 :         let attach_mode = attached_conf.location.attach_mode;
    1297            0 :         let generation = attached_conf.location.generation;
    1298            0 : 
    1299            0 :         let tenant = Arc::new(Tenant::new(
    1300            0 :             TenantState::Attaching,
    1301            0 :             conf,
    1302            0 :             attached_conf,
    1303            0 :             shard_identity,
    1304            0 :             Some(wal_redo_manager),
    1305            0 :             tenant_shard_id,
    1306            0 :             remote_storage.clone(),
    1307            0 :             deletion_queue_client,
    1308            0 :             l0_flush_global_state,
    1309            0 :         ));
    1310            0 : 
    1311            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1312            0 :         // we shut down while attaching.
    1313            0 :         let attach_gate_guard = tenant
    1314            0 :             .gate
    1315            0 :             .enter()
    1316            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1317            0 : 
    1318            0 :         // Do all the hard work in the background
    1319            0 :         let tenant_clone = Arc::clone(&tenant);
    1320            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1321            0 :         task_mgr::spawn(
    1322            0 :             &tokio::runtime::Handle::current(),
    1323            0 :             TaskKind::Attach,
    1324            0 :             tenant_shard_id,
    1325            0 :             None,
    1326            0 :             "attach tenant",
    1327            0 :             async move {
    1328            0 : 
    1329            0 :                 info!(
    1330              :                     ?attach_mode,
    1331            0 :                     "Attaching tenant"
    1332              :                 );
    1333              : 
    1334            0 :                 let _gate_guard = attach_gate_guard;
    1335            0 : 
    1336            0 :                 // Is this tenant being spawned as part of process startup?
    1337            0 :                 let starting_up = init_order.is_some();
    1338            0 :                 scopeguard::defer! {
    1339            0 :                     if starting_up {
    1340            0 :                         TENANT.startup_complete.inc();
    1341            0 :                     }
    1342            0 :                 }
    1343              : 
    1344              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1345              :                 enum BrokenVerbosity {
    1346              :                     Error,
    1347              :                     Info
    1348              :                 }
    1349            0 :                 let make_broken =
    1350            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1351            0 :                         match verbosity {
    1352              :                             BrokenVerbosity::Info => {
    1353            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1354              :                             },
    1355              :                             BrokenVerbosity::Error => {
    1356            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1357              :                             }
    1358              :                         }
    1359            0 :                         t.state.send_modify(|state| {
    1360            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1361            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1362            0 :                             assert!(
    1363            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1364            0 :                                 "the attach task owns the tenant state until activation is complete"
    1365              :                             );
    1366              : 
    1367            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1368            0 :                         });
    1369            0 :                     };
    1370              : 
    1371              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1372            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1373            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1374            0 :                     return Ok(());
    1375            0 :                 }
    1376            0 : 
    1377            0 :                 let mut init_order = init_order;
    1378            0 :                 // take the completion because initial tenant loading will complete when all of
    1379            0 :                 // these tasks complete.
    1380            0 :                 let _completion = init_order
    1381            0 :                     .as_mut()
    1382            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1383            0 :                 let remote_load_completion = init_order
    1384            0 :                     .as_mut()
    1385            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1386              : 
    1387              :                 enum AttachType<'a> {
    1388              :                     /// We are attaching this tenant lazily in the background.
    1389              :                     Warmup {
    1390              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1391              :                         during_startup: bool
    1392              :                     },
    1393              :                     /// We are attaching this tenant as soon as we can, because for example an
    1394              :                     /// endpoint tried to access it.
    1395              :                     OnDemand,
    1396              :                     /// During normal operations after startup, we are attaching a tenant, and
    1397              :                     /// eager attach was requested.
    1398              :                     Normal,
    1399              :                 }
    1400              : 
    1401            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1402              :                     // Before doing any I/O, wait for at least one of:
    1403              :                     // - A client attempting to access to this tenant (on-demand loading)
    1404              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1405              : 
    1406            0 :                     tokio::select!(
    1407            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1408            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1409            0 :                             tracing::info!("Activating tenant (on-demand)");
    1410            0 :                             AttachType::OnDemand
    1411              :                         },
    1412            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1413            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1414            0 :                             tracing::info!("Activating tenant (warmup)");
    1415            0 :                             AttachType::Warmup {
    1416            0 :                                 _permit,
    1417            0 :                                 during_startup: init_order.is_some()
    1418            0 :                             }
    1419              :                         }
    1420            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1421              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1422              :                             // stayed in Activating for such a long time that shutdown found it in
    1423              :                             // that state.
    1424            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1425              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1426              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1427              :                             // just shutting down), but ensures progress.
    1428            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1429            0 :                             return Ok(());
    1430              :                         },
    1431              :                     )
    1432              :                 } else {
    1433              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1434              :                     // concurrent_tenant_warmup queue
    1435            0 :                     AttachType::Normal
    1436              :                 };
    1437              : 
    1438            0 :                 let preload = match &mode {
    1439              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1440            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1441            0 :                         let res = tenant_clone
    1442            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1443            0 :                             .await;
    1444            0 :                         match res {
    1445            0 :                             Ok(p) => Some(p),
    1446            0 :                             Err(e) => {
    1447            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1448            0 :                                 return Ok(());
    1449              :                             }
    1450              :                         }
    1451              :                     }
    1452              : 
    1453              :                 };
    1454              : 
    1455              :                 // Remote preload is complete.
    1456            0 :                 drop(remote_load_completion);
    1457            0 : 
    1458            0 : 
    1459            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1460            0 :                 let attach_start = std::time::Instant::now();
    1461            0 :                 let attached = {
    1462            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1463            0 :                     tenant_clone.attach(preload, &ctx).await
    1464              :                 };
    1465            0 :                 let attach_duration = attach_start.elapsed();
    1466            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1467            0 : 
    1468            0 :                 match attached {
    1469              :                     Ok(()) => {
    1470            0 :                         info!("attach finished, activating");
    1471            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1472              :                     }
    1473            0 :                     Err(e) => {
    1474            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1475            0 :                     }
    1476              :                 }
    1477              : 
    1478              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1479              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1480              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1481              :                 //
    1482              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1483              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1484              :                 // then warmup will wait for that before proceeding to the next tenant.
    1485            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1486            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1487            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1488            0 :                     while futs.next().await.is_some() {}
    1489            0 :                     tracing::info!("Warm-up complete");
    1490            0 :                 }
    1491              : 
    1492            0 :                 Ok(())
    1493            0 :             }
    1494            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1495              :         );
    1496            0 :         Ok(tenant)
    1497            0 :     }
    1498              : 
    1499              :     #[instrument(skip_all)]
    1500              :     pub(crate) async fn preload(
    1501              :         self: &Arc<Self>,
    1502              :         remote_storage: &GenericRemoteStorage,
    1503              :         cancel: CancellationToken,
    1504              :     ) -> anyhow::Result<TenantPreload> {
    1505              :         span::debug_assert_current_span_has_tenant_id();
    1506              :         // Get list of remote timelines
    1507              :         // download index files for every tenant timeline
    1508              :         info!("listing remote timelines");
    1509              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1510              :             remote_storage,
    1511              :             self.tenant_shard_id,
    1512              :             cancel.clone(),
    1513              :         )
    1514              :         .await?;
    1515              :         let (offloaded_add, tenant_manifest) =
    1516              :             match remote_timeline_client::download_tenant_manifest(
    1517              :                 remote_storage,
    1518              :                 &self.tenant_shard_id,
    1519              :                 self.generation,
    1520              :                 &cancel,
    1521              :             )
    1522              :             .await
    1523              :             {
    1524              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1525              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1526              :                     tenant_manifest,
    1527              :                 ),
    1528              :                 Err(DownloadError::NotFound) => {
    1529              :                     ("no manifest".to_string(), TenantManifest::empty())
    1530              :                 }
    1531              :                 Err(e) => Err(e)?,
    1532              :             };
    1533              : 
    1534              :         info!(
    1535              :             "found {} timelines, and {offloaded_add}",
    1536              :             remote_timeline_ids.len()
    1537              :         );
    1538              : 
    1539              :         for k in other_keys {
    1540              :             warn!("Unexpected non timeline key {k}");
    1541              :         }
    1542              : 
    1543              :         // Avoid downloading IndexPart of offloaded timelines.
    1544              :         let mut offloaded_with_prefix = HashSet::new();
    1545              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1546              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1547              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1548              :             } else {
    1549              :                 // We'll take care later of timelines in the manifest without a prefix
    1550              :             }
    1551              :         }
    1552              : 
    1553              :         let timelines = self
    1554              :             .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1555              :             .await?;
    1556              : 
    1557              :         Ok(TenantPreload {
    1558              :             tenant_manifest,
    1559              :             timelines: timelines
    1560              :                 .into_iter()
    1561           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1562            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1563              :                 .collect(),
    1564              :         })
    1565              :     }
    1566              : 
    1567              :     ///
    1568              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1569              :     ///
    1570              :     /// No background tasks are started as part of this routine.
    1571              :     ///
    1572          440 :     async fn attach(
    1573          440 :         self: &Arc<Tenant>,
    1574          440 :         preload: Option<TenantPreload>,
    1575          440 :         ctx: &RequestContext,
    1576          440 :     ) -> anyhow::Result<()> {
    1577          440 :         span::debug_assert_current_span_has_tenant_id();
    1578          440 : 
    1579          440 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1580              : 
    1581          440 :         let Some(preload) = preload else {
    1582            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1583              :         };
    1584              : 
    1585          440 :         let mut offloaded_timeline_ids = HashSet::new();
    1586          440 :         let mut offloaded_timelines_list = Vec::new();
    1587          440 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1588            0 :             let timeline_id = timeline_manifest.timeline_id;
    1589            0 :             let offloaded_timeline =
    1590            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1591            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1592            0 :             offloaded_timeline_ids.insert(timeline_id);
    1593            0 :         }
    1594              :         // Complete deletions for offloaded timeline id's from manifest.
    1595              :         // The manifest will be uploaded later in this function.
    1596          440 :         offloaded_timelines_list
    1597          440 :             .retain(|(offloaded_id, offloaded)| {
    1598            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1599            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1600            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1601            0 :                 if delete {
    1602            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1603            0 :                     offloaded.defuse_for_tenant_drop();
    1604            0 :                 }
    1605            0 :                 !delete
    1606          440 :         });
    1607          440 : 
    1608          440 :         let mut timelines_to_resume_deletions = vec![];
    1609          440 : 
    1610          440 :         let mut remote_index_and_client = HashMap::new();
    1611          440 :         let mut timeline_ancestors = HashMap::new();
    1612          440 :         let mut existent_timelines = HashSet::new();
    1613          452 :         for (timeline_id, preload) in preload.timelines {
    1614           12 :             let Some(preload) = preload else { continue };
    1615              :             // This is an invariant of the `preload` function's API
    1616           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1617           12 :             let index_part = match preload.index_part {
    1618           12 :                 Ok(i) => {
    1619           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1620              :                     // We found index_part on the remote, this is the standard case.
    1621           12 :                     existent_timelines.insert(timeline_id);
    1622           12 :                     i
    1623              :                 }
    1624              :                 Err(DownloadError::NotFound) => {
    1625              :                     // There is no index_part on the remote. We only get here
    1626              :                     // if there is some prefix for the timeline in the remote storage.
    1627              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1628              :                     // remnant from a prior incomplete creation or deletion attempt.
    1629              :                     // Delete the local directory as the deciding criterion for a
    1630              :                     // timeline's existence is presence of index_part.
    1631            0 :                     info!(%timeline_id, "index_part not found on remote");
    1632            0 :                     continue;
    1633              :                 }
    1634            0 :                 Err(DownloadError::Fatal(why)) => {
    1635            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1636            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1637            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1638            0 :                     anyhow::bail!(why.to_string());
    1639              :                 }
    1640            0 :                 Err(e) => {
    1641            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1642            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1643            0 :                     // as it might be a temporary issue and we don't want to re-download
    1644            0 :                     // everything after it resolves.
    1645            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1646              : 
    1647            0 :                     existent_timelines.insert(timeline_id);
    1648            0 :                     continue;
    1649              :                 }
    1650              :             };
    1651           12 :             match index_part {
    1652           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1653           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1654           12 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1655           12 :                 }
    1656            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1657            0 :                     info!(
    1658            0 :                         "timeline {} is deleted, picking to resume deletion",
    1659              :                         timeline_id
    1660              :                     );
    1661            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1662              :                 }
    1663              :             }
    1664              :         }
    1665              : 
    1666          440 :         let mut gc_blocks = HashMap::new();
    1667              : 
    1668              :         // For every timeline, download the metadata file, scan the local directory,
    1669              :         // and build a layer map that contains an entry for each remote and local
    1670              :         // layer file.
    1671          440 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1672          452 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1673           12 :             let (index_part, remote_client) = remote_index_and_client
    1674           12 :                 .remove(&timeline_id)
    1675           12 :                 .expect("just put it in above");
    1676              : 
    1677           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1678              :                 // could just filter these away, but it helps while testing
    1679            0 :                 anyhow::ensure!(
    1680            0 :                     !blocking.reasons.is_empty(),
    1681            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1682              :                 );
    1683            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1684            0 :                 assert!(prev.is_none());
    1685           12 :             }
    1686              : 
    1687              :             // TODO again handle early failure
    1688           12 :             let effect = self
    1689           12 :                 .load_remote_timeline(
    1690           12 :                     timeline_id,
    1691           12 :                     index_part,
    1692           12 :                     remote_metadata,
    1693           12 :                     TimelineResources {
    1694           12 :                         remote_client,
    1695           12 :                         pagestream_throttle: self.pagestream_throttle.clone(),
    1696           12 :                         pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    1697           12 :                         l0_flush_global_state: self.l0_flush_global_state.clone(),
    1698           12 :                     },
    1699           12 :                     LoadTimelineCause::Attach,
    1700           12 :                     ctx,
    1701           12 :                 )
    1702           12 :                 .await
    1703           12 :                 .with_context(|| {
    1704            0 :                     format!(
    1705            0 :                         "failed to load remote timeline {} for tenant {}",
    1706            0 :                         timeline_id, self.tenant_shard_id
    1707            0 :                     )
    1708           12 :                 })?;
    1709              : 
    1710           12 :             match effect {
    1711           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1712           12 :                     // activation happens later, on Tenant::activate
    1713           12 :                 }
    1714              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1715              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1716            0 :                         timeline,
    1717            0 :                         import_pgdata,
    1718            0 :                         guard,
    1719            0 :                     },
    1720            0 :                 ) => {
    1721            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1722            0 :                         timeline,
    1723            0 :                         import_pgdata,
    1724            0 :                         ActivateTimelineArgs::No,
    1725            0 :                         guard,
    1726            0 :                     ));
    1727            0 :                 }
    1728              :             }
    1729              :         }
    1730              : 
    1731              :         // Walk through deleted timelines, resume deletion
    1732          440 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1733            0 :             remote_timeline_client
    1734            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1735            0 :                 .context("init queue stopped")
    1736            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1737              : 
    1738            0 :             DeleteTimelineFlow::resume_deletion(
    1739            0 :                 Arc::clone(self),
    1740            0 :                 timeline_id,
    1741            0 :                 &index_part.metadata,
    1742            0 :                 remote_timeline_client,
    1743            0 :             )
    1744            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1745            0 :             .await
    1746            0 :             .context("resume_deletion")
    1747            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1748              :         }
    1749          440 :         let needs_manifest_upload =
    1750          440 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1751          440 :         {
    1752          440 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1753          440 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1754          440 :         }
    1755          440 :         if needs_manifest_upload {
    1756            0 :             self.store_tenant_manifest().await?;
    1757          440 :         }
    1758              : 
    1759              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1760              :         // IndexPart is the source of truth.
    1761          440 :         self.clean_up_timelines(&existent_timelines)?;
    1762              : 
    1763          440 :         self.gc_block.set_scanned(gc_blocks);
    1764          440 : 
    1765          440 :         fail::fail_point!("attach-before-activate", |_| {
    1766            0 :             anyhow::bail!("attach-before-activate");
    1767          440 :         });
    1768          440 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1769              : 
    1770          440 :         info!("Done");
    1771              : 
    1772          440 :         Ok(())
    1773          440 :     }
    1774              : 
    1775              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1776              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1777              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1778          440 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1779          440 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1780              : 
    1781          440 :         let entries = match timelines_dir.read_dir_utf8() {
    1782          440 :             Ok(d) => d,
    1783            0 :             Err(e) => {
    1784            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1785            0 :                     return Ok(());
    1786              :                 } else {
    1787            0 :                     return Err(e).context("list timelines directory for tenant");
    1788              :                 }
    1789              :             }
    1790              :         };
    1791              : 
    1792          456 :         for entry in entries {
    1793           16 :             let entry = entry.context("read timeline dir entry")?;
    1794           16 :             let entry_path = entry.path();
    1795              : 
    1796           16 :             let purge = if crate::is_temporary(entry_path)
    1797              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1798           16 :                 || is_uninit_mark(entry_path)
    1799           16 :                 || crate::is_delete_mark(entry_path)
    1800              :             {
    1801            0 :                 true
    1802              :             } else {
    1803           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1804           16 :                     Ok(i) => {
    1805           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1806           16 :                         !existent_timelines.contains(&i)
    1807              :                     }
    1808            0 :                     Err(e) => {
    1809            0 :                         tracing::warn!(
    1810            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1811              :                         );
    1812              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1813            0 :                         false
    1814              :                     }
    1815              :                 }
    1816              :             };
    1817              : 
    1818           16 :             if purge {
    1819            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1820            4 :                 if let Err(e) = match entry.file_type() {
    1821            4 :                     Ok(t) => if t.is_dir() {
    1822            4 :                         std::fs::remove_dir_all(entry_path)
    1823              :                     } else {
    1824            0 :                         std::fs::remove_file(entry_path)
    1825              :                     }
    1826            4 :                     .or_else(fs_ext::ignore_not_found),
    1827            0 :                     Err(e) => Err(e),
    1828              :                 } {
    1829            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1830            4 :                 }
    1831           12 :             }
    1832              :         }
    1833              : 
    1834          440 :         Ok(())
    1835          440 :     }
    1836              : 
    1837              :     /// Get sum of all remote timelines sizes
    1838              :     ///
    1839              :     /// This function relies on the index_part instead of listing the remote storage
    1840            0 :     pub fn remote_size(&self) -> u64 {
    1841            0 :         let mut size = 0;
    1842              : 
    1843            0 :         for timeline in self.list_timelines() {
    1844            0 :             size += timeline.remote_client.get_remote_physical_size();
    1845            0 :         }
    1846              : 
    1847            0 :         size
    1848            0 :     }
    1849              : 
    1850              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1851              :     async fn load_remote_timeline(
    1852              :         self: &Arc<Self>,
    1853              :         timeline_id: TimelineId,
    1854              :         index_part: IndexPart,
    1855              :         remote_metadata: TimelineMetadata,
    1856              :         resources: TimelineResources,
    1857              :         cause: LoadTimelineCause,
    1858              :         ctx: &RequestContext,
    1859              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1860              :         span::debug_assert_current_span_has_tenant_id();
    1861              : 
    1862              :         info!("downloading index file for timeline {}", timeline_id);
    1863              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1864              :             .await
    1865              :             .context("Failed to create new timeline directory")?;
    1866              : 
    1867              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1868              :             let timelines = self.timelines.lock().unwrap();
    1869              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1870            0 :                 || {
    1871            0 :                     anyhow::anyhow!(
    1872            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1873            0 :                     )
    1874            0 :                 },
    1875              :             )?))
    1876              :         } else {
    1877              :             None
    1878              :         };
    1879              : 
    1880              :         self.timeline_init_and_sync(
    1881              :             timeline_id,
    1882              :             resources,
    1883              :             index_part,
    1884              :             remote_metadata,
    1885              :             ancestor,
    1886              :             cause,
    1887              :             ctx,
    1888              :         )
    1889              :         .await
    1890              :     }
    1891              : 
    1892          440 :     async fn load_timelines_metadata(
    1893          440 :         self: &Arc<Tenant>,
    1894          440 :         timeline_ids: HashSet<TimelineId>,
    1895          440 :         remote_storage: &GenericRemoteStorage,
    1896          440 :         cancel: CancellationToken,
    1897          440 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1898          440 :         let mut part_downloads = JoinSet::new();
    1899          452 :         for timeline_id in timeline_ids {
    1900           12 :             let cancel_clone = cancel.clone();
    1901           12 :             part_downloads.spawn(
    1902           12 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1903           12 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1904              :             );
    1905              :         }
    1906              : 
    1907          440 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1908              : 
    1909              :         loop {
    1910          452 :             tokio::select!(
    1911          452 :                 next = part_downloads.join_next() => {
    1912          452 :                     match next {
    1913           12 :                         Some(result) => {
    1914           12 :                             let preload = result.context("join preload task")?;
    1915           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1916              :                         },
    1917              :                         None => {
    1918          440 :                             break;
    1919              :                         }
    1920              :                     }
    1921              :                 },
    1922          452 :                 _ = cancel.cancelled() => {
    1923            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1924              :                 }
    1925              :             )
    1926              :         }
    1927              : 
    1928          440 :         Ok(timeline_preloads)
    1929          440 :     }
    1930              : 
    1931           12 :     fn build_timeline_client(
    1932           12 :         &self,
    1933           12 :         timeline_id: TimelineId,
    1934           12 :         remote_storage: GenericRemoteStorage,
    1935           12 :     ) -> RemoteTimelineClient {
    1936           12 :         RemoteTimelineClient::new(
    1937           12 :             remote_storage.clone(),
    1938           12 :             self.deletion_queue_client.clone(),
    1939           12 :             self.conf,
    1940           12 :             self.tenant_shard_id,
    1941           12 :             timeline_id,
    1942           12 :             self.generation,
    1943           12 :             &self.tenant_conf.load().location,
    1944           12 :         )
    1945           12 :     }
    1946              : 
    1947           12 :     fn load_timeline_metadata(
    1948           12 :         self: &Arc<Tenant>,
    1949           12 :         timeline_id: TimelineId,
    1950           12 :         remote_storage: GenericRemoteStorage,
    1951           12 :         cancel: CancellationToken,
    1952           12 :     ) -> impl Future<Output = TimelinePreload> {
    1953           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1954           12 :         async move {
    1955           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1956           12 :             debug!("starting index part download");
    1957              : 
    1958           12 :             let index_part = client.download_index_file(&cancel).await;
    1959              : 
    1960           12 :             debug!("finished index part download");
    1961              : 
    1962           12 :             TimelinePreload {
    1963           12 :                 client,
    1964           12 :                 timeline_id,
    1965           12 :                 index_part,
    1966           12 :             }
    1967           12 :         }
    1968           12 :     }
    1969              : 
    1970            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1971            0 :         timeline_id: TimelineId,
    1972            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1973            0 :     ) -> Result<(), TimelineArchivalError> {
    1974            0 :         let children: Vec<TimelineId> = timelines
    1975            0 :             .iter()
    1976            0 :             .filter_map(|(id, entry)| {
    1977            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1978            0 :                     return None;
    1979            0 :                 }
    1980            0 :                 if entry.is_archived() == Some(true) {
    1981            0 :                     return None;
    1982            0 :                 }
    1983            0 :                 Some(*id)
    1984            0 :             })
    1985            0 :             .collect();
    1986            0 : 
    1987            0 :         if !children.is_empty() {
    1988            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1989            0 :         }
    1990            0 :         Ok(())
    1991            0 :     }
    1992              : 
    1993            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1994            0 :         ancestor_timeline_id: TimelineId,
    1995            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1996            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1997            0 :             '_,
    1998            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1999            0 :         >,
    2000            0 :     ) -> Result<(), TimelineArchivalError> {
    2001            0 :         let has_archived_parent =
    2002            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2003            0 :                 ancestor_timeline.is_archived() == Some(true)
    2004            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2005            0 :                 true
    2006              :             } else {
    2007            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2008            0 :                 if cfg!(debug_assertions) {
    2009            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2010            0 :                 }
    2011            0 :                 return Err(TimelineArchivalError::NotFound);
    2012              :             };
    2013            0 :         if has_archived_parent {
    2014            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2015            0 :                 ancestor_timeline_id,
    2016            0 :             ));
    2017            0 :         }
    2018            0 :         Ok(())
    2019            0 :     }
    2020              : 
    2021            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2022            0 :         timeline: &Arc<Timeline>,
    2023            0 :     ) -> Result<(), TimelineArchivalError> {
    2024            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2025            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2026            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2027            0 :                     ancestor_timeline.timeline_id,
    2028            0 :                 ));
    2029            0 :             }
    2030            0 :         }
    2031            0 :         Ok(())
    2032            0 :     }
    2033              : 
    2034              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2035              :     ///
    2036              :     /// Counterpart to [`offload_timeline`].
    2037            0 :     async fn unoffload_timeline(
    2038            0 :         self: &Arc<Self>,
    2039            0 :         timeline_id: TimelineId,
    2040            0 :         broker_client: storage_broker::BrokerClientChannel,
    2041            0 :         ctx: RequestContext,
    2042            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2043            0 :         info!("unoffloading timeline");
    2044              : 
    2045              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2046              :         // We expect callers of this function to ensure this.
    2047            0 :         match self.current_state() {
    2048              :             TenantState::Activating { .. }
    2049              :             | TenantState::Attaching
    2050              :             | TenantState::Broken { .. } => {
    2051            0 :                 panic!("Timeline expected to be active")
    2052              :             }
    2053            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2054            0 :             TenantState::Active => {}
    2055            0 :         }
    2056            0 :         let cancel = self.cancel.clone();
    2057            0 : 
    2058            0 :         // Protect against concurrent attempts to use this TimelineId
    2059            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2060            0 :         let allow_offloaded = true;
    2061            0 :         let _create_guard = self
    2062            0 :             .create_timeline_create_guard(
    2063            0 :                 timeline_id,
    2064            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2065            0 :                 allow_offloaded,
    2066            0 :             )
    2067            0 :             .map_err(|err| match err {
    2068            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2069              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2070            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2071              :                 }
    2072            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2073            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2074            0 :             })?;
    2075              : 
    2076            0 :         let timeline_preload = self
    2077            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    2078            0 :             .await;
    2079              : 
    2080            0 :         let index_part = match timeline_preload.index_part {
    2081            0 :             Ok(index_part) => {
    2082            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2083            0 :                 index_part
    2084              :             }
    2085              :             Err(DownloadError::NotFound) => {
    2086            0 :                 error!(%timeline_id, "index_part not found on remote");
    2087            0 :                 return Err(TimelineArchivalError::NotFound);
    2088              :             }
    2089            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2090            0 :             Err(e) => {
    2091            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2092            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2093            0 :                 return Err(TimelineArchivalError::Other(
    2094            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2095            0 :                 ));
    2096              :             }
    2097              :         };
    2098            0 :         let index_part = match index_part {
    2099            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2100            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2101            0 :                 info!("timeline is deleted according to index_part.json");
    2102            0 :                 return Err(TimelineArchivalError::NotFound);
    2103              :             }
    2104              :         };
    2105            0 :         let remote_metadata = index_part.metadata.clone();
    2106            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2107            0 :         self.load_remote_timeline(
    2108            0 :             timeline_id,
    2109            0 :             index_part,
    2110            0 :             remote_metadata,
    2111            0 :             timeline_resources,
    2112            0 :             LoadTimelineCause::Unoffload,
    2113            0 :             &ctx,
    2114            0 :         )
    2115            0 :         .await
    2116            0 :         .with_context(|| {
    2117            0 :             format!(
    2118            0 :                 "failed to load remote timeline {} for tenant {}",
    2119            0 :                 timeline_id, self.tenant_shard_id
    2120            0 :             )
    2121            0 :         })
    2122            0 :         .map_err(TimelineArchivalError::Other)?;
    2123              : 
    2124            0 :         let timeline = {
    2125            0 :             let timelines = self.timelines.lock().unwrap();
    2126            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2127            0 :                 warn!("timeline not available directly after attach");
    2128              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2129              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2130            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2131            0 :                     "timeline not available directly after attach"
    2132            0 :                 )));
    2133              :             };
    2134            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2135            0 :             match offloaded_timelines.remove(&timeline_id) {
    2136            0 :                 Some(offloaded) => {
    2137            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2138            0 :                 }
    2139            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2140              :             }
    2141              : 
    2142            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2143            0 : 
    2144            0 :             Arc::clone(timeline)
    2145            0 :         };
    2146            0 : 
    2147            0 :         // Upload new list of offloaded timelines to S3
    2148            0 :         self.store_tenant_manifest().await?;
    2149              : 
    2150              :         // Activate the timeline (if it makes sense)
    2151            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2152            0 :             let background_jobs_can_start = None;
    2153            0 :             timeline.activate(
    2154            0 :                 self.clone(),
    2155            0 :                 broker_client.clone(),
    2156            0 :                 background_jobs_can_start,
    2157            0 :                 &ctx,
    2158            0 :             );
    2159            0 :         }
    2160              : 
    2161            0 :         info!("timeline unoffloading complete");
    2162            0 :         Ok(timeline)
    2163            0 :     }
    2164              : 
    2165            0 :     pub(crate) async fn apply_timeline_archival_config(
    2166            0 :         self: &Arc<Self>,
    2167            0 :         timeline_id: TimelineId,
    2168            0 :         new_state: TimelineArchivalState,
    2169            0 :         broker_client: storage_broker::BrokerClientChannel,
    2170            0 :         ctx: RequestContext,
    2171            0 :     ) -> Result<(), TimelineArchivalError> {
    2172            0 :         info!("setting timeline archival config");
    2173              :         // First part: figure out what is needed to do, and do validation
    2174            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2175            0 :             let timelines = self.timelines.lock().unwrap();
    2176              : 
    2177            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2178            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2179            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2180            0 :                     return Err(TimelineArchivalError::NotFound);
    2181              :                 };
    2182            0 :                 if new_state == TimelineArchivalState::Archived {
    2183              :                     // It's offloaded already, so nothing to do
    2184            0 :                     return Ok(());
    2185            0 :                 }
    2186            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2187            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2188            0 :                         ancestor_timeline_id,
    2189            0 :                         &timelines,
    2190            0 :                         &offloaded_timelines,
    2191            0 :                     )?;
    2192            0 :                 }
    2193            0 :                 break 'outer None;
    2194              :             };
    2195              : 
    2196              :             // Do some validation. We release the timelines lock below, so there is potential
    2197              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2198              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2199            0 :             match new_state {
    2200              :                 TimelineArchivalState::Unarchived => {
    2201            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2202              :                 }
    2203              :                 TimelineArchivalState::Archived => {
    2204            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2205              :                 }
    2206              :             }
    2207            0 :             Some(Arc::clone(timeline))
    2208              :         };
    2209              : 
    2210              :         // Second part: unoffload timeline (if needed)
    2211            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2212            0 :             timeline
    2213              :         } else {
    2214              :             // Turn offloaded timeline into a non-offloaded one
    2215            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2216            0 :                 .await?
    2217              :         };
    2218              : 
    2219              :         // Third part: upload new timeline archival state and block until it is present in S3
    2220            0 :         let upload_needed = match timeline
    2221            0 :             .remote_client
    2222            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2223              :         {
    2224            0 :             Ok(upload_needed) => upload_needed,
    2225            0 :             Err(e) => {
    2226            0 :                 if timeline.cancel.is_cancelled() {
    2227            0 :                     return Err(TimelineArchivalError::Cancelled);
    2228              :                 } else {
    2229            0 :                     return Err(TimelineArchivalError::Other(e));
    2230              :                 }
    2231              :             }
    2232              :         };
    2233              : 
    2234            0 :         if upload_needed {
    2235            0 :             info!("Uploading new state");
    2236              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2237            0 :             let Ok(v) =
    2238            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2239              :             else {
    2240            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2241            0 :                 return Err(TimelineArchivalError::Timeout);
    2242              :             };
    2243            0 :             v.map_err(|e| match e {
    2244            0 :                 WaitCompletionError::NotInitialized(e) => {
    2245            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2246              :                 }
    2247              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2248            0 :                     TimelineArchivalError::Cancelled
    2249              :                 }
    2250            0 :             })?;
    2251            0 :         }
    2252            0 :         Ok(())
    2253            0 :     }
    2254              : 
    2255            4 :     pub fn get_offloaded_timeline(
    2256            4 :         &self,
    2257            4 :         timeline_id: TimelineId,
    2258            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2259            4 :         self.timelines_offloaded
    2260            4 :             .lock()
    2261            4 :             .unwrap()
    2262            4 :             .get(&timeline_id)
    2263            4 :             .map(Arc::clone)
    2264            4 :             .ok_or(GetTimelineError::NotFound {
    2265            4 :                 tenant_id: self.tenant_shard_id,
    2266            4 :                 timeline_id,
    2267            4 :             })
    2268            4 :     }
    2269              : 
    2270            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2271            8 :         self.tenant_shard_id
    2272            8 :     }
    2273              : 
    2274              :     /// Get Timeline handle for given Neon timeline ID.
    2275              :     /// This function is idempotent. It doesn't change internal state in any way.
    2276          444 :     pub fn get_timeline(
    2277          444 :         &self,
    2278          444 :         timeline_id: TimelineId,
    2279          444 :         active_only: bool,
    2280          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2281          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2282          444 :         let timeline = timelines_accessor
    2283          444 :             .get(&timeline_id)
    2284          444 :             .ok_or(GetTimelineError::NotFound {
    2285          444 :                 tenant_id: self.tenant_shard_id,
    2286          444 :                 timeline_id,
    2287          444 :             })?;
    2288              : 
    2289          440 :         if active_only && !timeline.is_active() {
    2290            0 :             Err(GetTimelineError::NotActive {
    2291            0 :                 tenant_id: self.tenant_shard_id,
    2292            0 :                 timeline_id,
    2293            0 :                 state: timeline.current_state(),
    2294            0 :             })
    2295              :         } else {
    2296          440 :             Ok(Arc::clone(timeline))
    2297              :         }
    2298          444 :     }
    2299              : 
    2300              :     /// Lists timelines the tenant contains.
    2301              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2302            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2303            0 :         self.timelines
    2304            0 :             .lock()
    2305            0 :             .unwrap()
    2306            0 :             .values()
    2307            0 :             .map(Arc::clone)
    2308            0 :             .collect()
    2309            0 :     }
    2310              : 
    2311              :     /// Lists timelines the tenant manages, including offloaded ones.
    2312              :     ///
    2313              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2314            0 :     pub fn list_timelines_and_offloaded(
    2315            0 :         &self,
    2316            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2317            0 :         let timelines = self
    2318            0 :             .timelines
    2319            0 :             .lock()
    2320            0 :             .unwrap()
    2321            0 :             .values()
    2322            0 :             .map(Arc::clone)
    2323            0 :             .collect();
    2324            0 :         let offloaded = self
    2325            0 :             .timelines_offloaded
    2326            0 :             .lock()
    2327            0 :             .unwrap()
    2328            0 :             .values()
    2329            0 :             .map(Arc::clone)
    2330            0 :             .collect();
    2331            0 :         (timelines, offloaded)
    2332            0 :     }
    2333              : 
    2334            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2335            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2336            0 :     }
    2337              : 
    2338              :     /// This is used by tests & import-from-basebackup.
    2339              :     ///
    2340              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2341              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2342              :     ///
    2343              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2344              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2345              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2346              :     /// to the [`Tenant::timelines`].
    2347              :     ///
    2348              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2349          424 :     pub(crate) async fn create_empty_timeline(
    2350          424 :         self: &Arc<Self>,
    2351          424 :         new_timeline_id: TimelineId,
    2352          424 :         initdb_lsn: Lsn,
    2353          424 :         pg_version: u32,
    2354          424 :         _ctx: &RequestContext,
    2355          424 :     ) -> anyhow::Result<UninitializedTimeline> {
    2356          424 :         anyhow::ensure!(
    2357          424 :             self.is_active(),
    2358            0 :             "Cannot create empty timelines on inactive tenant"
    2359              :         );
    2360              : 
    2361              :         // Protect against concurrent attempts to use this TimelineId
    2362          424 :         let create_guard = match self
    2363          424 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2364          424 :             .await?
    2365              :         {
    2366          420 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2367              :             StartCreatingTimelineResult::Idempotent(_) => {
    2368            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2369              :             }
    2370              :         };
    2371              : 
    2372          420 :         let new_metadata = TimelineMetadata::new(
    2373          420 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2374          420 :             // make it valid, before calling finish_creation()
    2375          420 :             Lsn(0),
    2376          420 :             None,
    2377          420 :             None,
    2378          420 :             Lsn(0),
    2379          420 :             initdb_lsn,
    2380          420 :             initdb_lsn,
    2381          420 :             pg_version,
    2382          420 :         );
    2383          420 :         self.prepare_new_timeline(
    2384          420 :             new_timeline_id,
    2385          420 :             &new_metadata,
    2386          420 :             create_guard,
    2387          420 :             initdb_lsn,
    2388          420 :             None,
    2389          420 :         )
    2390          420 :         .await
    2391          424 :     }
    2392              : 
    2393              :     /// Helper for unit tests to create an empty timeline.
    2394              :     ///
    2395              :     /// The timeline is has state value `Active` but its background loops are not running.
    2396              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2397              :     // Our current tests don't need the background loops.
    2398              :     #[cfg(test)]
    2399          404 :     pub async fn create_test_timeline(
    2400          404 :         self: &Arc<Self>,
    2401          404 :         new_timeline_id: TimelineId,
    2402          404 :         initdb_lsn: Lsn,
    2403          404 :         pg_version: u32,
    2404          404 :         ctx: &RequestContext,
    2405          404 :     ) -> anyhow::Result<Arc<Timeline>> {
    2406          404 :         let uninit_tl = self
    2407          404 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2408          404 :             .await?;
    2409          404 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2410          404 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2411              : 
    2412              :         // Setup minimum keys required for the timeline to be usable.
    2413          404 :         let mut modification = tline.begin_modification(initdb_lsn);
    2414          404 :         modification
    2415          404 :             .init_empty_test_timeline()
    2416          404 :             .context("init_empty_test_timeline")?;
    2417          404 :         modification
    2418          404 :             .commit(ctx)
    2419          404 :             .await
    2420          404 :             .context("commit init_empty_test_timeline modification")?;
    2421              : 
    2422              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2423          404 :         tline.maybe_spawn_flush_loop();
    2424          404 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2425              : 
    2426              :         // Make sure the freeze_and_flush reaches remote storage.
    2427          404 :         tline.remote_client.wait_completion().await.unwrap();
    2428              : 
    2429          404 :         let tl = uninit_tl.finish_creation()?;
    2430              :         // The non-test code would call tl.activate() here.
    2431          404 :         tl.set_state(TimelineState::Active);
    2432          404 :         Ok(tl)
    2433          404 :     }
    2434              : 
    2435              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2436              :     #[cfg(test)]
    2437              :     #[allow(clippy::too_many_arguments)]
    2438           76 :     pub async fn create_test_timeline_with_layers(
    2439           76 :         self: &Arc<Self>,
    2440           76 :         new_timeline_id: TimelineId,
    2441           76 :         initdb_lsn: Lsn,
    2442           76 :         pg_version: u32,
    2443           76 :         ctx: &RequestContext,
    2444           76 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2445           76 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2446           76 :         end_lsn: Lsn,
    2447           76 :     ) -> anyhow::Result<Arc<Timeline>> {
    2448              :         use checks::check_valid_layermap;
    2449              :         use itertools::Itertools;
    2450              : 
    2451           76 :         let tline = self
    2452           76 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2453           76 :             .await?;
    2454           76 :         tline.force_advance_lsn(end_lsn);
    2455          244 :         for deltas in delta_layer_desc {
    2456          168 :             tline
    2457          168 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2458          168 :                 .await?;
    2459              :         }
    2460          184 :         for (lsn, images) in image_layer_desc {
    2461          108 :             tline
    2462          108 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2463          108 :                 .await?;
    2464              :         }
    2465           76 :         let layer_names = tline
    2466           76 :             .layers
    2467           76 :             .read()
    2468           76 :             .await
    2469           76 :             .layer_map()
    2470           76 :             .unwrap()
    2471           76 :             .iter_historic_layers()
    2472          352 :             .map(|layer| layer.layer_name())
    2473           76 :             .collect_vec();
    2474           76 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2475            0 :             bail!("invalid layermap: {err}");
    2476           76 :         }
    2477           76 :         Ok(tline)
    2478           76 :     }
    2479              : 
    2480              :     /// Create a new timeline.
    2481              :     ///
    2482              :     /// Returns the new timeline ID and reference to its Timeline object.
    2483              :     ///
    2484              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2485              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2486              :     #[allow(clippy::too_many_arguments)]
    2487            0 :     pub(crate) async fn create_timeline(
    2488            0 :         self: &Arc<Tenant>,
    2489            0 :         params: CreateTimelineParams,
    2490            0 :         broker_client: storage_broker::BrokerClientChannel,
    2491            0 :         ctx: &RequestContext,
    2492            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2493            0 :         if !self.is_active() {
    2494            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2495            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2496              :             } else {
    2497            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2498            0 :                     "Cannot create timelines on inactive tenant"
    2499            0 :                 )));
    2500              :             }
    2501            0 :         }
    2502              : 
    2503            0 :         let _gate = self
    2504            0 :             .gate
    2505            0 :             .enter()
    2506            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2507              : 
    2508            0 :         let result: CreateTimelineResult = match params {
    2509              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2510            0 :                 new_timeline_id,
    2511            0 :                 existing_initdb_timeline_id,
    2512            0 :                 pg_version,
    2513            0 :             }) => {
    2514            0 :                 self.bootstrap_timeline(
    2515            0 :                     new_timeline_id,
    2516            0 :                     pg_version,
    2517            0 :                     existing_initdb_timeline_id,
    2518            0 :                     ctx,
    2519            0 :                 )
    2520            0 :                 .await?
    2521              :             }
    2522              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2523            0 :                 new_timeline_id,
    2524            0 :                 ancestor_timeline_id,
    2525            0 :                 mut ancestor_start_lsn,
    2526              :             }) => {
    2527            0 :                 let ancestor_timeline = self
    2528            0 :                     .get_timeline(ancestor_timeline_id, false)
    2529            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2530              : 
    2531              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2532              :                 // ready for other purposes either.
    2533            0 :                 if !ancestor_timeline.is_active() {
    2534            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2535            0 :                 }
    2536            0 : 
    2537            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2538            0 :                     info!("tried to branch archived timeline");
    2539            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2540            0 :                 }
    2541              : 
    2542            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2543            0 :                     *lsn = lsn.align();
    2544            0 : 
    2545            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2546            0 :                     if ancestor_ancestor_lsn > *lsn {
    2547              :                         // can we safely just branch from the ancestor instead?
    2548            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2549            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2550            0 :                             lsn,
    2551            0 :                             ancestor_timeline_id,
    2552            0 :                             ancestor_ancestor_lsn,
    2553            0 :                         )));
    2554            0 :                     }
    2555            0 : 
    2556            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2557            0 :                     // to the requested branch point. The repository code itself doesn't
    2558            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2559            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2560            0 :                     // sizes etc. and that would get confused if the previous page versions
    2561            0 :                     // are not in the repository yet.
    2562            0 :                     ancestor_timeline
    2563            0 :                         .wait_lsn(
    2564            0 :                             *lsn,
    2565            0 :                             timeline::WaitLsnWaiter::Tenant,
    2566            0 :                             timeline::WaitLsnTimeout::Default,
    2567            0 :                             ctx,
    2568            0 :                         )
    2569            0 :                         .await
    2570            0 :                         .map_err(|e| match e {
    2571            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2572            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2573              :                             }
    2574            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2575            0 :                         })?;
    2576            0 :                 }
    2577              : 
    2578            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2579            0 :                     .await?
    2580              :             }
    2581            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2582            0 :                 self.create_timeline_import_pgdata(
    2583            0 :                     params,
    2584            0 :                     ActivateTimelineArgs::Yes {
    2585            0 :                         broker_client: broker_client.clone(),
    2586            0 :                     },
    2587            0 :                     ctx,
    2588            0 :                 )
    2589            0 :                 .await?
    2590              :             }
    2591              :         };
    2592              : 
    2593              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2594              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2595              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2596              :         //
    2597              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2598              :         // assume that, because they can see the timeline via API, that the creation is done and
    2599              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2600              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2601              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2602              :         //
    2603              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2604              :         // creation API until it returns success. Only then is durability guaranteed.
    2605            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2606            0 :         result
    2607            0 :             .timeline()
    2608            0 :             .remote_client
    2609            0 :             .wait_completion()
    2610            0 :             .await
    2611            0 :             .map_err(|e| match e {
    2612              :                 WaitCompletionError::NotInitialized(
    2613            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2614            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2615              :                 WaitCompletionError::NotInitialized(_) => {
    2616              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2617            0 :                     debug_assert!(false);
    2618            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2619              :                 }
    2620              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2621            0 :                     CreateTimelineError::ShuttingDown
    2622              :                 }
    2623            0 :             })?;
    2624              : 
    2625              :         // The creating task is responsible for activating the timeline.
    2626              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2627              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2628            0 :         let activated_timeline = match result {
    2629            0 :             CreateTimelineResult::Created(timeline) => {
    2630            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2631            0 :                 timeline
    2632              :             }
    2633            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2634            0 :                 info!(
    2635            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2636              :                 );
    2637            0 :                 timeline
    2638              :             }
    2639            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2640            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2641            0 :                 timeline
    2642              :             }
    2643              :         };
    2644              : 
    2645            0 :         Ok(activated_timeline)
    2646            0 :     }
    2647              : 
    2648              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2649              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2650              :     /// [`Tenant::timelines`] map when the import completes.
    2651              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2652              :     /// for the response.
    2653            0 :     async fn create_timeline_import_pgdata(
    2654            0 :         self: &Arc<Tenant>,
    2655            0 :         params: CreateTimelineParamsImportPgdata,
    2656            0 :         activate: ActivateTimelineArgs,
    2657            0 :         ctx: &RequestContext,
    2658            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2659            0 :         let CreateTimelineParamsImportPgdata {
    2660            0 :             new_timeline_id,
    2661            0 :             location,
    2662            0 :             idempotency_key,
    2663            0 :         } = params;
    2664            0 : 
    2665            0 :         let started_at = chrono::Utc::now().naive_utc();
    2666              : 
    2667              :         //
    2668              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2669              :         // is the canonical way we do it.
    2670              :         // - create an empty timeline in-memory
    2671              :         // - use its remote_timeline_client to do the upload
    2672              :         // - dispose of the uninit timeline
    2673              :         // - keep the creation guard alive
    2674              : 
    2675            0 :         let timeline_create_guard = match self
    2676            0 :             .start_creating_timeline(
    2677            0 :                 new_timeline_id,
    2678            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2679            0 :                     idempotency_key: idempotency_key.clone(),
    2680            0 :                 }),
    2681            0 :             )
    2682            0 :             .await?
    2683              :         {
    2684            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2685            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2686            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2687              :             }
    2688              :         };
    2689              : 
    2690            0 :         let mut uninit_timeline = {
    2691            0 :             let this = &self;
    2692            0 :             let initdb_lsn = Lsn(0);
    2693            0 :             let _ctx = ctx;
    2694            0 :             async move {
    2695            0 :                 let new_metadata = TimelineMetadata::new(
    2696            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2697            0 :                     // make it valid, before calling finish_creation()
    2698            0 :                     Lsn(0),
    2699            0 :                     None,
    2700            0 :                     None,
    2701            0 :                     Lsn(0),
    2702            0 :                     initdb_lsn,
    2703            0 :                     initdb_lsn,
    2704            0 :                     15,
    2705            0 :                 );
    2706            0 :                 this.prepare_new_timeline(
    2707            0 :                     new_timeline_id,
    2708            0 :                     &new_metadata,
    2709            0 :                     timeline_create_guard,
    2710            0 :                     initdb_lsn,
    2711            0 :                     None,
    2712            0 :                 )
    2713            0 :                 .await
    2714            0 :             }
    2715            0 :         }
    2716            0 :         .await?;
    2717              : 
    2718            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2719            0 :             idempotency_key,
    2720            0 :             location,
    2721            0 :             started_at,
    2722            0 :         };
    2723            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2724            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2725            0 :         );
    2726            0 :         uninit_timeline
    2727            0 :             .raw_timeline()
    2728            0 :             .unwrap()
    2729            0 :             .remote_client
    2730            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2731              : 
    2732              :         // wait_completion happens in caller
    2733              : 
    2734            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2735            0 : 
    2736            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2737            0 :             timeline.clone(),
    2738            0 :             index_part,
    2739            0 :             activate,
    2740            0 :             timeline_create_guard,
    2741            0 :         ));
    2742            0 : 
    2743            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2744            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2745            0 :     }
    2746              : 
    2747              :     #[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))]
    2748              :     async fn create_timeline_import_pgdata_task(
    2749              :         self: Arc<Tenant>,
    2750              :         timeline: Arc<Timeline>,
    2751              :         index_part: import_pgdata::index_part_format::Root,
    2752              :         activate: ActivateTimelineArgs,
    2753              :         timeline_create_guard: TimelineCreateGuard,
    2754              :     ) {
    2755              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2756              :         info!("starting");
    2757              :         scopeguard::defer! {info!("exiting")};
    2758              : 
    2759              :         let res = self
    2760              :             .create_timeline_import_pgdata_task_impl(
    2761              :                 timeline,
    2762              :                 index_part,
    2763              :                 activate,
    2764              :                 timeline_create_guard,
    2765              :             )
    2766              :             .await;
    2767              :         if let Err(err) = &res {
    2768              :             error!(?err, "task failed");
    2769              :             // TODO sleep & retry, sensitive to tenant shutdown
    2770              :             // TODO: allow timeline deletion requests => should cancel the task
    2771              :         }
    2772              :     }
    2773              : 
    2774            0 :     async fn create_timeline_import_pgdata_task_impl(
    2775            0 :         self: Arc<Tenant>,
    2776            0 :         timeline: Arc<Timeline>,
    2777            0 :         index_part: import_pgdata::index_part_format::Root,
    2778            0 :         activate: ActivateTimelineArgs,
    2779            0 :         timeline_create_guard: TimelineCreateGuard,
    2780            0 :     ) -> Result<(), anyhow::Error> {
    2781            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2782            0 : 
    2783            0 :         info!("importing pgdata");
    2784            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2785            0 :             .await
    2786            0 :             .context("import")?;
    2787            0 :         info!("import done");
    2788              : 
    2789              :         //
    2790              :         // Reload timeline from remote.
    2791              :         // This proves that the remote state is attachable, and it reuses the code.
    2792              :         //
    2793              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2794              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2795              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2796              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2797              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2798              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2799              :         // to manifest because of the long runtime of this import task.
    2800              : 
    2801              :         //        in theory this shouldn't even .await anything except for coop yield
    2802            0 :         info!("shutting down timeline");
    2803            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2804            0 :         info!("timeline shut down, reloading from remote");
    2805              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2806              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2807              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2808              :         // };
    2809            0 :         let timeline_id = timeline.timeline_id;
    2810            0 : 
    2811            0 :         // load from object storage like Tenant::attach does
    2812            0 :         let resources = self.build_timeline_resources(timeline_id);
    2813            0 :         let index_part = resources
    2814            0 :             .remote_client
    2815            0 :             .download_index_file(&self.cancel)
    2816            0 :             .await?;
    2817            0 :         let index_part = match index_part {
    2818              :             MaybeDeletedIndexPart::Deleted(_) => {
    2819              :                 // likely concurrent delete call, cplane should prevent this
    2820            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2821              :             }
    2822            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2823            0 :         };
    2824            0 :         let metadata = index_part.metadata.clone();
    2825            0 :         self
    2826            0 :             .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
    2827            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2828            0 :             .await?
    2829            0 :             .ready_to_activate()
    2830            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2831              : 
    2832            0 :         anyhow::Ok(())
    2833            0 :     }
    2834              : 
    2835            0 :     pub(crate) async fn delete_timeline(
    2836            0 :         self: Arc<Self>,
    2837            0 :         timeline_id: TimelineId,
    2838            0 :     ) -> Result<(), DeleteTimelineError> {
    2839            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2840              : 
    2841            0 :         Ok(())
    2842            0 :     }
    2843              : 
    2844              :     /// perform one garbage collection iteration, removing old data files from disk.
    2845              :     /// this function is periodically called by gc task.
    2846              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2847              :     ///
    2848              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2849              :     ///
    2850              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2851              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2852              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2853              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2854              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2855              :     /// requires more history to be retained.
    2856              :     //
    2857         1508 :     pub(crate) async fn gc_iteration(
    2858         1508 :         &self,
    2859         1508 :         target_timeline_id: Option<TimelineId>,
    2860         1508 :         horizon: u64,
    2861         1508 :         pitr: Duration,
    2862         1508 :         cancel: &CancellationToken,
    2863         1508 :         ctx: &RequestContext,
    2864         1508 :     ) -> Result<GcResult, GcError> {
    2865         1508 :         // Don't start doing work during shutdown
    2866         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2867            0 :             return Ok(GcResult::default());
    2868         1508 :         }
    2869         1508 : 
    2870         1508 :         // there is a global allowed_error for this
    2871         1508 :         if !self.is_active() {
    2872            0 :             return Err(GcError::NotActive);
    2873         1508 :         }
    2874         1508 : 
    2875         1508 :         {
    2876         1508 :             let conf = self.tenant_conf.load();
    2877         1508 : 
    2878         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2879         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2880         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2881         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2882         1508 :             if !conf.location.may_delete_layers_hint() {
    2883            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2884            0 :                 return Ok(GcResult::default());
    2885         1508 :             }
    2886         1508 : 
    2887         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2888         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2889         1500 :                 return Ok(GcResult::default());
    2890            8 :             }
    2891              :         }
    2892              : 
    2893            8 :         let _guard = match self.gc_block.start().await {
    2894            8 :             Ok(guard) => guard,
    2895            0 :             Err(reasons) => {
    2896            0 :                 info!("Skipping GC: {reasons}");
    2897            0 :                 return Ok(GcResult::default());
    2898              :             }
    2899              :         };
    2900              : 
    2901            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2902            8 :             .await
    2903         1508 :     }
    2904              : 
    2905              :     /// Perform one compaction iteration.
    2906              :     /// This function is periodically called by compactor task.
    2907              :     /// Also it can be explicitly requested per timeline through page server
    2908              :     /// api's 'compact' command.
    2909              :     ///
    2910              :     /// Returns whether we have pending compaction task.
    2911            0 :     async fn compaction_iteration(
    2912            0 :         self: &Arc<Self>,
    2913            0 :         cancel: &CancellationToken,
    2914            0 :         ctx: &RequestContext,
    2915            0 :     ) -> Result<bool, timeline::CompactionError> {
    2916            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2917            0 :         if !self.is_active() {
    2918            0 :             return Ok(false);
    2919            0 :         }
    2920            0 : 
    2921            0 :         {
    2922            0 :             let conf = self.tenant_conf.load();
    2923            0 : 
    2924            0 :             // Note that compaction usually requires deletions, but we don't respect
    2925            0 :             // may_delete_layers_hint here: that is because tenants in AttachedMulti
    2926            0 :             // should proceed with compaction even if they can't do deletion, to avoid
    2927            0 :             // accumulating dangerously deep stacks of L0 layers.  Deletions will be
    2928            0 :             // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
    2929            0 :             // to AttachedSingle state.
    2930            0 :             if !conf.location.may_upload_layers_hint() {
    2931            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2932            0 :                 return Ok(false);
    2933            0 :             }
    2934            0 :         }
    2935            0 : 
    2936            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2937            0 :         // while holding the lock. Then drop the lock and actually perform the
    2938            0 :         // compactions.  We don't want to block everything else while the
    2939            0 :         // compaction runs.
    2940            0 :         let timelines_to_compact_or_offload;
    2941            0 :         {
    2942            0 :             let timelines = self.timelines.lock().unwrap();
    2943            0 :             timelines_to_compact_or_offload = timelines
    2944            0 :                 .iter()
    2945            0 :                 .filter_map(|(timeline_id, timeline)| {
    2946            0 :                     let (is_active, (can_offload, _)) =
    2947            0 :                         (timeline.is_active(), timeline.can_offload());
    2948            0 :                     let has_no_unoffloaded_children = {
    2949            0 :                         !timelines
    2950            0 :                             .iter()
    2951            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2952              :                     };
    2953            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2954            0 :                         || self
    2955            0 :                             .tenant_conf
    2956            0 :                             .load()
    2957            0 :                             .tenant_conf
    2958            0 :                             .timeline_offloading
    2959            0 :                             .unwrap_or_default();
    2960            0 :                     let can_offload =
    2961            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2962            0 :                     if (is_active, can_offload) == (false, false) {
    2963            0 :                         None
    2964              :                     } else {
    2965            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2966              :                     }
    2967            0 :                 })
    2968            0 :                 .collect::<Vec<_>>();
    2969            0 :             drop(timelines);
    2970            0 :         }
    2971            0 : 
    2972            0 :         // Before doing any I/O work, check our circuit breaker
    2973            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2974            0 :             info!("Skipping compaction due to previous failures");
    2975            0 :             return Ok(false);
    2976            0 :         }
    2977            0 : 
    2978            0 :         let mut has_pending_task = false;
    2979              : 
    2980            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2981              :         {
    2982              :             // pending_task_left == None: cannot compact, maybe still pending tasks
    2983              :             // pending_task_left == Some(true): compaction task left
    2984              :             // pending_task_left == Some(false): no compaction task left
    2985            0 :             let pending_task_left = if *can_compact {
    2986            0 :                 let has_pending_l0_compaction_task = timeline
    2987            0 :                     .compact(cancel, EnumSet::empty(), ctx)
    2988            0 :                     .instrument(info_span!("compact_timeline", %timeline_id))
    2989            0 :                     .await
    2990            0 :                     .inspect_err(|e| match e {
    2991            0 :                         timeline::CompactionError::ShuttingDown => (),
    2992            0 :                         timeline::CompactionError::Offload(_) => {
    2993            0 :                             // Failures to offload timelines do not trip the circuit breaker, because
    2994            0 :                             // they do not do lots of writes the way compaction itself does: it is cheap
    2995            0 :                             // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2996            0 :                         }
    2997            0 :                         timeline::CompactionError::Other(e) => {
    2998            0 :                             self.compaction_circuit_breaker
    2999            0 :                                 .lock()
    3000            0 :                                 .unwrap()
    3001            0 :                                 .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    3002            0 :                         }
    3003            0 :                     })?;
    3004            0 :                 if has_pending_l0_compaction_task {
    3005            0 :                     Some(true)
    3006              :                 } else {
    3007            0 :                     let queue = {
    3008            0 :                         let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3009            0 :                         guard.get(timeline_id).cloned()
    3010              :                     };
    3011            0 :                     if let Some(queue) = queue {
    3012            0 :                         let has_pending_tasks = queue
    3013            0 :                             .iteration(cancel, ctx, &self.gc_block, timeline)
    3014            0 :                             .await?;
    3015            0 :                         Some(has_pending_tasks)
    3016              :                     } else {
    3017            0 :                         Some(false)
    3018              :                     }
    3019              :                 }
    3020              :             } else {
    3021            0 :                 None
    3022              :             };
    3023            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    3024            0 :             if pending_task_left == Some(false) && *can_offload {
    3025            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3026            0 :                 match offload_timeline(self, timeline)
    3027            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    3028            0 :                     .await
    3029              :                 {
    3030              :                     Err(OffloadError::NotArchived) => {
    3031              :                         // Ignore this, we likely raced with unarchival
    3032            0 :                         Ok(())
    3033              :                     }
    3034            0 :                     other => other,
    3035            0 :                 }?;
    3036            0 :             }
    3037              :         }
    3038              : 
    3039            0 :         self.compaction_circuit_breaker
    3040            0 :             .lock()
    3041            0 :             .unwrap()
    3042            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3043            0 : 
    3044            0 :         Ok(has_pending_task)
    3045            0 :     }
    3046              : 
    3047              :     /// Cancel scheduled compaction tasks
    3048            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3049            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3050            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3051            0 :             q.cancel_scheduled();
    3052            0 :         }
    3053            0 :     }
    3054              : 
    3055            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3056            0 :         &self,
    3057            0 :         timeline_id: TimelineId,
    3058            0 :     ) -> Vec<CompactInfoResponse> {
    3059            0 :         let res = {
    3060            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3061            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3062              :         };
    3063            0 :         let Some((running, remaining)) = res else {
    3064            0 :             return Vec::new();
    3065              :         };
    3066            0 :         let mut result = Vec::new();
    3067            0 :         if let Some((id, running)) = running {
    3068            0 :             result.extend(running.into_compact_info_resp(id, true));
    3069            0 :         }
    3070            0 :         for (id, job) in remaining {
    3071            0 :             result.extend(job.into_compact_info_resp(id, false));
    3072            0 :         }
    3073            0 :         result
    3074            0 :     }
    3075              : 
    3076              :     /// Schedule a compaction task for a timeline.
    3077            0 :     pub(crate) async fn schedule_compaction(
    3078            0 :         &self,
    3079            0 :         timeline_id: TimelineId,
    3080            0 :         options: CompactOptions,
    3081            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3082            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3083            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3084            0 :         let q = guard
    3085            0 :             .entry(timeline_id)
    3086            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3087            0 :         q.schedule_manual_compaction(options, Some(tx));
    3088            0 :         Ok(rx)
    3089            0 :     }
    3090              : 
    3091              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    3092              :     // this happens during ingest: this background housekeeping is for freezing layers
    3093              :     // that are open but haven't been written to for some time.
    3094            0 :     async fn ingest_housekeeping(&self) {
    3095            0 :         // Scan through the hashmap and collect a list of all the timelines,
    3096            0 :         // while holding the lock. Then drop the lock and actually perform the
    3097            0 :         // compactions.  We don't want to block everything else while the
    3098            0 :         // compaction runs.
    3099            0 :         let timelines = {
    3100            0 :             self.timelines
    3101            0 :                 .lock()
    3102            0 :                 .unwrap()
    3103            0 :                 .values()
    3104            0 :                 .filter_map(|timeline| {
    3105            0 :                     if timeline.is_active() {
    3106            0 :                         Some(timeline.clone())
    3107              :                     } else {
    3108            0 :                         None
    3109              :                     }
    3110            0 :                 })
    3111            0 :                 .collect::<Vec<_>>()
    3112              :         };
    3113              : 
    3114            0 :         for timeline in &timelines {
    3115            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3116              :         }
    3117            0 :     }
    3118              : 
    3119            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3120            0 :         let timelines = self.timelines.lock().unwrap();
    3121            0 :         !timelines
    3122            0 :             .iter()
    3123            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3124            0 :     }
    3125              : 
    3126         3464 :     pub fn current_state(&self) -> TenantState {
    3127         3464 :         self.state.borrow().clone()
    3128         3464 :     }
    3129              : 
    3130         1940 :     pub fn is_active(&self) -> bool {
    3131         1940 :         self.current_state() == TenantState::Active
    3132         1940 :     }
    3133              : 
    3134            0 :     pub fn generation(&self) -> Generation {
    3135            0 :         self.generation
    3136            0 :     }
    3137              : 
    3138            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3139            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3140            0 :     }
    3141              : 
    3142              :     /// Changes tenant status to active, unless shutdown was already requested.
    3143              :     ///
    3144              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3145              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3146            0 :     fn activate(
    3147            0 :         self: &Arc<Self>,
    3148            0 :         broker_client: BrokerClientChannel,
    3149            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3150            0 :         ctx: &RequestContext,
    3151            0 :     ) {
    3152            0 :         span::debug_assert_current_span_has_tenant_id();
    3153            0 : 
    3154            0 :         let mut activating = false;
    3155            0 :         self.state.send_modify(|current_state| {
    3156              :             use pageserver_api::models::ActivatingFrom;
    3157            0 :             match &*current_state {
    3158              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3159            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3160              :                 }
    3161            0 :                 TenantState::Attaching => {
    3162            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3163            0 :                 }
    3164            0 :             }
    3165            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3166            0 :             activating = true;
    3167            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3168            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3169            0 :         });
    3170            0 : 
    3171            0 :         if activating {
    3172            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3173            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3174            0 :             let timelines_to_activate = timelines_accessor
    3175            0 :                 .values()
    3176            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3177            0 : 
    3178            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3179            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3180            0 : 
    3181            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3182            0 :             // down when they notice that the tenant is inactive.
    3183            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3184            0 : 
    3185            0 :             let mut activated_timelines = 0;
    3186              : 
    3187            0 :             for timeline in timelines_to_activate {
    3188            0 :                 timeline.activate(
    3189            0 :                     self.clone(),
    3190            0 :                     broker_client.clone(),
    3191            0 :                     background_jobs_can_start,
    3192            0 :                     ctx,
    3193            0 :                 );
    3194            0 :                 activated_timelines += 1;
    3195            0 :             }
    3196              : 
    3197            0 :             self.state.send_modify(move |current_state| {
    3198            0 :                 assert!(
    3199            0 :                     matches!(current_state, TenantState::Activating(_)),
    3200            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3201              :                 );
    3202            0 :                 *current_state = TenantState::Active;
    3203            0 : 
    3204            0 :                 let elapsed = self.constructed_at.elapsed();
    3205            0 :                 let total_timelines = timelines_accessor.len();
    3206            0 : 
    3207            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3208            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3209            0 :                 info!(
    3210            0 :                     since_creation_millis = elapsed.as_millis(),
    3211            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3212            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3213            0 :                     activated_timelines,
    3214            0 :                     total_timelines,
    3215            0 :                     post_state = <&'static str>::from(&*current_state),
    3216            0 :                     "activation attempt finished"
    3217              :                 );
    3218              : 
    3219            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3220            0 :             });
    3221            0 :         }
    3222            0 :     }
    3223              : 
    3224              :     /// Shutdown the tenant and join all of the spawned tasks.
    3225              :     ///
    3226              :     /// The method caters for all use-cases:
    3227              :     /// - pageserver shutdown (freeze_and_flush == true)
    3228              :     /// - detach + ignore (freeze_and_flush == false)
    3229              :     ///
    3230              :     /// This will attempt to shutdown even if tenant is broken.
    3231              :     ///
    3232              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3233              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3234              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3235              :     /// the ongoing shutdown.
    3236           12 :     async fn shutdown(
    3237           12 :         &self,
    3238           12 :         shutdown_progress: completion::Barrier,
    3239           12 :         shutdown_mode: timeline::ShutdownMode,
    3240           12 :     ) -> Result<(), completion::Barrier> {
    3241           12 :         span::debug_assert_current_span_has_tenant_id();
    3242              : 
    3243              :         // Set tenant (and its timlines) to Stoppping state.
    3244              :         //
    3245              :         // Since we can only transition into Stopping state after activation is complete,
    3246              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3247              :         //
    3248              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3249              :         // 1. Lock out any new requests to the tenants.
    3250              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3251              :         // 3. Signal cancellation for other tenant background loops.
    3252              :         // 4. ???
    3253              :         //
    3254              :         // The waiting for the cancellation is not done uniformly.
    3255              :         // We certainly wait for WAL receivers to shut down.
    3256              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3257              :         // But the tenant background loops are joined-on in our caller.
    3258              :         // It's mesed up.
    3259              :         // we just ignore the failure to stop
    3260              : 
    3261              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3262              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3263              :         // is very slow.
    3264           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3265            0 :             self.cancel.cancel();
    3266            0 : 
    3267            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3268            0 :             // are children of ours, so their flush loops will have shut down already
    3269            0 :             timeline::ShutdownMode::Hard
    3270              :         } else {
    3271           12 :             shutdown_mode
    3272              :         };
    3273              : 
    3274           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3275           12 :             Ok(()) => {}
    3276            0 :             Err(SetStoppingError::Broken) => {
    3277            0 :                 // assume that this is acceptable
    3278            0 :             }
    3279            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3280            0 :                 // give caller the option to wait for this this shutdown
    3281            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3282            0 :                 return Err(other);
    3283              :             }
    3284              :         };
    3285              : 
    3286           12 :         let mut js = tokio::task::JoinSet::new();
    3287           12 :         {
    3288           12 :             let timelines = self.timelines.lock().unwrap();
    3289           12 :             timelines.values().for_each(|timeline| {
    3290           12 :                 let timeline = Arc::clone(timeline);
    3291           12 :                 let timeline_id = timeline.timeline_id;
    3292           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3293           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3294           12 :             });
    3295           12 :         }
    3296           12 :         {
    3297           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3298           12 :             timelines_offloaded.values().for_each(|timeline| {
    3299            0 :                 timeline.defuse_for_tenant_drop();
    3300           12 :             });
    3301           12 :         }
    3302           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3303           12 :         tracing::info!("Waiting for timelines...");
    3304           24 :         while let Some(res) = js.join_next().await {
    3305            0 :             match res {
    3306           12 :                 Ok(()) => {}
    3307            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3308            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3309            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3310              :             }
    3311              :         }
    3312              : 
    3313           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3314            0 :             tracing::info!("Flushing deletion queue");
    3315            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3316            0 :                 match e {
    3317            0 :                     DeletionQueueError::ShuttingDown => {
    3318            0 :                         // This is the only error we expect for now. In the future, if more error
    3319            0 :                         // variants are added, we should handle them here.
    3320            0 :                     }
    3321              :                 }
    3322            0 :             }
    3323           12 :         }
    3324              : 
    3325              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3326              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3327           12 :         tracing::debug!("Cancelling CancellationToken");
    3328           12 :         self.cancel.cancel();
    3329           12 : 
    3330           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3331           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3332           12 :         //
    3333           12 :         // this will additionally shutdown and await all timeline tasks.
    3334           12 :         tracing::debug!("Waiting for tasks...");
    3335           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3336              : 
    3337           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3338           12 :             walredo_mgr.shutdown().await;
    3339            0 :         }
    3340              : 
    3341              :         // Wait for any in-flight operations to complete
    3342           12 :         self.gate.close().await;
    3343              : 
    3344           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3345           12 : 
    3346           12 :         Ok(())
    3347           12 :     }
    3348              : 
    3349              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3350              :     ///
    3351              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3352              :     ///
    3353              :     /// This function is not cancel-safe!
    3354              :     ///
    3355              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3356              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3357           12 :     async fn set_stopping(
    3358           12 :         &self,
    3359           12 :         progress: completion::Barrier,
    3360           12 :         _allow_transition_from_loading: bool,
    3361           12 :         allow_transition_from_attaching: bool,
    3362           12 :     ) -> Result<(), SetStoppingError> {
    3363           12 :         let mut rx = self.state.subscribe();
    3364           12 : 
    3365           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3366           12 :         rx.wait_for(|state| match state {
    3367            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3368              :             TenantState::Activating(_) | TenantState::Attaching => {
    3369            0 :                 info!(
    3370            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3371            0 :                     <&'static str>::from(state)
    3372              :                 );
    3373            0 :                 false
    3374              :             }
    3375           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3376           12 :         })
    3377           12 :         .await
    3378           12 :         .expect("cannot drop self.state while on a &self method");
    3379           12 : 
    3380           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3381           12 :         let mut err = None;
    3382           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3383              :             TenantState::Activating(_) => {
    3384            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3385              :             }
    3386              :             TenantState::Attaching => {
    3387            0 :                 if !allow_transition_from_attaching {
    3388            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3389            0 :                 };
    3390            0 :                 *current_state = TenantState::Stopping { progress };
    3391            0 :                 true
    3392              :             }
    3393              :             TenantState::Active => {
    3394              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3395              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3396              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3397           12 :                 *current_state = TenantState::Stopping { progress };
    3398           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3399           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3400           12 :                 true
    3401              :             }
    3402            0 :             TenantState::Broken { reason, .. } => {
    3403            0 :                 info!(
    3404            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3405              :                 );
    3406            0 :                 err = Some(SetStoppingError::Broken);
    3407            0 :                 false
    3408              :             }
    3409            0 :             TenantState::Stopping { progress } => {
    3410            0 :                 info!("Tenant is already in Stopping state");
    3411            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3412            0 :                 false
    3413              :             }
    3414           12 :         });
    3415           12 :         match (stopping, err) {
    3416           12 :             (true, None) => {} // continue
    3417            0 :             (false, Some(err)) => return Err(err),
    3418            0 :             (true, Some(_)) => unreachable!(
    3419            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3420            0 :             ),
    3421            0 :             (false, None) => unreachable!(
    3422            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3423            0 :             ),
    3424              :         }
    3425              : 
    3426           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3427           12 :         let not_broken_timelines = timelines_accessor
    3428           12 :             .values()
    3429           12 :             .filter(|timeline| !timeline.is_broken());
    3430           24 :         for timeline in not_broken_timelines {
    3431           12 :             timeline.set_state(TimelineState::Stopping);
    3432           12 :         }
    3433           12 :         Ok(())
    3434           12 :     }
    3435              : 
    3436              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3437              :     /// `remove_tenant_from_memory`
    3438              :     ///
    3439              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3440              :     ///
    3441              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3442            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3443            0 :         let mut rx = self.state.subscribe();
    3444            0 : 
    3445            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3446            0 :         // So, wait until it's done.
    3447            0 :         rx.wait_for(|state| match state {
    3448              :             TenantState::Activating(_) | TenantState::Attaching => {
    3449            0 :                 info!(
    3450            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3451            0 :                     <&'static str>::from(state)
    3452              :                 );
    3453            0 :                 false
    3454              :             }
    3455            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3456            0 :         })
    3457            0 :         .await
    3458            0 :         .expect("cannot drop self.state while on a &self method");
    3459            0 : 
    3460            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3461            0 :         self.set_broken_no_wait(reason)
    3462            0 :     }
    3463              : 
    3464            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3465            0 :         let reason = reason.to_string();
    3466            0 :         self.state.send_modify(|current_state| {
    3467            0 :             match *current_state {
    3468              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3469            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3470              :                 }
    3471              :                 TenantState::Active => {
    3472            0 :                     if cfg!(feature = "testing") {
    3473            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3474            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3475              :                     } else {
    3476            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3477              :                     }
    3478              :                 }
    3479              :                 TenantState::Broken { .. } => {
    3480            0 :                     warn!("Tenant is already in Broken state");
    3481              :                 }
    3482              :                 // This is the only "expected" path, any other path is a bug.
    3483              :                 TenantState::Stopping { .. } => {
    3484            0 :                     warn!(
    3485            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3486              :                         reason
    3487              :                     );
    3488            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3489              :                 }
    3490              :            }
    3491            0 :         });
    3492            0 :     }
    3493              : 
    3494            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3495            0 :         self.state.subscribe()
    3496            0 :     }
    3497              : 
    3498              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3499              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3500            0 :     pub(crate) fn activate_now(&self) {
    3501            0 :         self.activate_now_sem.add_permits(1);
    3502            0 :     }
    3503              : 
    3504            0 :     pub(crate) async fn wait_to_become_active(
    3505            0 :         &self,
    3506            0 :         timeout: Duration,
    3507            0 :     ) -> Result<(), GetActiveTenantError> {
    3508            0 :         let mut receiver = self.state.subscribe();
    3509              :         loop {
    3510            0 :             let current_state = receiver.borrow_and_update().clone();
    3511            0 :             match current_state {
    3512              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3513              :                     // in these states, there's a chance that we can reach ::Active
    3514            0 :                     self.activate_now();
    3515            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3516            0 :                         Ok(r) => {
    3517            0 :                             r.map_err(
    3518            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3519              :                                 // Tenant existed but was dropped: report it as non-existent
    3520            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3521            0 :                         )?
    3522              :                         }
    3523              :                         Err(TimeoutCancellableError::Cancelled) => {
    3524            0 :                             return Err(GetActiveTenantError::Cancelled);
    3525              :                         }
    3526              :                         Err(TimeoutCancellableError::Timeout) => {
    3527            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3528            0 :                                 latest_state: Some(self.current_state()),
    3529            0 :                                 wait_time: timeout,
    3530            0 :                             });
    3531              :                         }
    3532              :                     }
    3533              :                 }
    3534              :                 TenantState::Active { .. } => {
    3535            0 :                     return Ok(());
    3536              :                 }
    3537            0 :                 TenantState::Broken { reason, .. } => {
    3538            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3539            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3540            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3541              :                 }
    3542              :                 TenantState::Stopping { .. } => {
    3543              :                     // There's no chance the tenant can transition back into ::Active
    3544            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3545              :                 }
    3546              :             }
    3547              :         }
    3548            0 :     }
    3549              : 
    3550            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3551            0 :         self.tenant_conf.load().location.attach_mode
    3552            0 :     }
    3553              : 
    3554              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3555              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3556              :     /// rare external API calls, like a reconciliation at startup.
    3557            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3558            0 :         let conf = self.tenant_conf.load();
    3559              : 
    3560            0 :         let location_config_mode = match conf.location.attach_mode {
    3561            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3562            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3563            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3564              :         };
    3565              : 
    3566              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3567            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3568            0 : 
    3569            0 :         models::LocationConfig {
    3570            0 :             mode: location_config_mode,
    3571            0 :             generation: self.generation.into(),
    3572            0 :             secondary_conf: None,
    3573            0 :             shard_number: self.shard_identity.number.0,
    3574            0 :             shard_count: self.shard_identity.count.literal(),
    3575            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3576            0 :             tenant_conf: tenant_config,
    3577            0 :         }
    3578            0 :     }
    3579              : 
    3580            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3581            0 :         &self.tenant_shard_id
    3582            0 :     }
    3583              : 
    3584            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3585            0 :         self.shard_identity.stripe_size
    3586            0 :     }
    3587              : 
    3588            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3589            0 :         self.generation
    3590            0 :     }
    3591              : 
    3592              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3593              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3594              :     /// resetting this tenant to a valid state if we fail.
    3595            0 :     pub(crate) async fn split_prepare(
    3596            0 :         &self,
    3597            0 :         child_shards: &Vec<TenantShardId>,
    3598            0 :     ) -> anyhow::Result<()> {
    3599            0 :         let (timelines, offloaded) = {
    3600            0 :             let timelines = self.timelines.lock().unwrap();
    3601            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3602            0 :             (timelines.clone(), offloaded.clone())
    3603            0 :         };
    3604            0 :         let timelines_iter = timelines
    3605            0 :             .values()
    3606            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3607            0 :             .chain(
    3608            0 :                 offloaded
    3609            0 :                     .values()
    3610            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3611            0 :             );
    3612            0 :         for timeline in timelines_iter {
    3613              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3614              :             // to ensure that they do not start a split if currently in the process of doing these.
    3615              : 
    3616            0 :             let timeline_id = timeline.timeline_id();
    3617              : 
    3618            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3619              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3620              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3621              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3622            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3623            0 :                 timeline
    3624            0 :                     .remote_client
    3625            0 :                     .schedule_index_upload_for_file_changes()?;
    3626            0 :                 timeline.remote_client.wait_completion().await?;
    3627            0 :             }
    3628              : 
    3629            0 :             let remote_client = match timeline {
    3630            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3631            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3632            0 :                     let remote_client = self
    3633            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3634            0 :                     Arc::new(remote_client)
    3635              :                 }
    3636              :             };
    3637              : 
    3638              :             // Shut down the timeline's remote client: this means that the indices we write
    3639              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3640            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3641            0 :             remote_client.shutdown().await;
    3642              : 
    3643              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3644              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3645              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3646              :             // we use here really is the remotely persistent one).
    3647            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3648            0 :             let result = remote_client
    3649            0 :                 .download_index_file(&self.cancel)
    3650            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))
    3651            0 :                 .await?;
    3652            0 :             let index_part = match result {
    3653              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3654            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3655              :                 }
    3656            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3657              :             };
    3658              : 
    3659            0 :             for child_shard in child_shards {
    3660            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3661            0 :                 upload_index_part(
    3662            0 :                     &self.remote_storage,
    3663            0 :                     child_shard,
    3664            0 :                     &timeline_id,
    3665            0 :                     self.generation,
    3666            0 :                     &index_part,
    3667            0 :                     &self.cancel,
    3668            0 :                 )
    3669            0 :                 .await?;
    3670              :             }
    3671              :         }
    3672              : 
    3673            0 :         let tenant_manifest = self.build_tenant_manifest();
    3674            0 :         for child_shard in child_shards {
    3675            0 :             tracing::info!(
    3676            0 :                 "Uploading tenant manifest for child {}",
    3677            0 :                 child_shard.to_index()
    3678              :             );
    3679            0 :             upload_tenant_manifest(
    3680            0 :                 &self.remote_storage,
    3681            0 :                 child_shard,
    3682            0 :                 self.generation,
    3683            0 :                 &tenant_manifest,
    3684            0 :                 &self.cancel,
    3685            0 :             )
    3686            0 :             .await?;
    3687              :         }
    3688              : 
    3689            0 :         Ok(())
    3690            0 :     }
    3691              : 
    3692            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3693            0 :         let mut result = TopTenantShardItem {
    3694            0 :             id: self.tenant_shard_id,
    3695            0 :             resident_size: 0,
    3696            0 :             physical_size: 0,
    3697            0 :             max_logical_size: 0,
    3698            0 :         };
    3699              : 
    3700            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3701            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3702            0 : 
    3703            0 :             result.physical_size += timeline
    3704            0 :                 .remote_client
    3705            0 :                 .metrics
    3706            0 :                 .remote_physical_size_gauge
    3707            0 :                 .get();
    3708            0 :             result.max_logical_size = std::cmp::max(
    3709            0 :                 result.max_logical_size,
    3710            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3711            0 :             );
    3712            0 :         }
    3713              : 
    3714            0 :         result
    3715            0 :     }
    3716              : }
    3717              : 
    3718              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3719              : /// perform a topological sort, so that the parent of each timeline comes
    3720              : /// before the children.
    3721              : /// E extracts the ancestor from T
    3722              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3723          440 : fn tree_sort_timelines<T, E>(
    3724          440 :     timelines: HashMap<TimelineId, T>,
    3725          440 :     extractor: E,
    3726          440 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3727          440 : where
    3728          440 :     E: Fn(&T) -> Option<TimelineId>,
    3729          440 : {
    3730          440 :     let mut result = Vec::with_capacity(timelines.len());
    3731          440 : 
    3732          440 :     let mut now = Vec::with_capacity(timelines.len());
    3733          440 :     // (ancestor, children)
    3734          440 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3735          440 :         HashMap::with_capacity(timelines.len());
    3736              : 
    3737          452 :     for (timeline_id, value) in timelines {
    3738           12 :         if let Some(ancestor_id) = extractor(&value) {
    3739            4 :             let children = later.entry(ancestor_id).or_default();
    3740            4 :             children.push((timeline_id, value));
    3741            8 :         } else {
    3742            8 :             now.push((timeline_id, value));
    3743            8 :         }
    3744              :     }
    3745              : 
    3746          452 :     while let Some((timeline_id, metadata)) = now.pop() {
    3747           12 :         result.push((timeline_id, metadata));
    3748              :         // All children of this can be loaded now
    3749           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3750            4 :             now.append(&mut children);
    3751            8 :         }
    3752              :     }
    3753              : 
    3754              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3755          440 :     if !later.is_empty() {
    3756            0 :         for (missing_id, orphan_ids) in later {
    3757            0 :             for (orphan_id, _) in orphan_ids {
    3758            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3759              :             }
    3760              :         }
    3761            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3762          440 :     }
    3763          440 : 
    3764          440 :     Ok(result)
    3765          440 : }
    3766              : 
    3767              : enum ActivateTimelineArgs {
    3768              :     Yes {
    3769              :         broker_client: storage_broker::BrokerClientChannel,
    3770              :     },
    3771              :     No,
    3772              : }
    3773              : 
    3774              : impl Tenant {
    3775            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3776            0 :         self.tenant_conf.load().tenant_conf.clone()
    3777            0 :     }
    3778              : 
    3779            0 :     pub fn effective_config(&self) -> TenantConf {
    3780            0 :         self.tenant_specific_overrides()
    3781            0 :             .merge(self.conf.default_tenant_conf.clone())
    3782            0 :     }
    3783              : 
    3784            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3785            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3786            0 :         tenant_conf
    3787            0 :             .checkpoint_distance
    3788            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3789            0 :     }
    3790              : 
    3791            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3792            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3793            0 :         tenant_conf
    3794            0 :             .checkpoint_timeout
    3795            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3796            0 :     }
    3797              : 
    3798            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3799            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3800            0 :         tenant_conf
    3801            0 :             .compaction_target_size
    3802            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3803            0 :     }
    3804              : 
    3805            0 :     pub fn get_compaction_period(&self) -> Duration {
    3806            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3807            0 :         tenant_conf
    3808            0 :             .compaction_period
    3809            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3810            0 :     }
    3811              : 
    3812            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3813            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3814            0 :         tenant_conf
    3815            0 :             .compaction_threshold
    3816            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3817            0 :     }
    3818              : 
    3819            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3820            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3821            0 :         tenant_conf
    3822            0 :             .compaction_upper_limit
    3823            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3824            0 :     }
    3825              : 
    3826            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3827            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3828            0 :         tenant_conf
    3829            0 :             .gc_horizon
    3830            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3831            0 :     }
    3832              : 
    3833            0 :     pub fn get_gc_period(&self) -> Duration {
    3834            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3835            0 :         tenant_conf
    3836            0 :             .gc_period
    3837            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3838            0 :     }
    3839              : 
    3840            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3841            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3842            0 :         tenant_conf
    3843            0 :             .image_creation_threshold
    3844            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3845            0 :     }
    3846              : 
    3847            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3848            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3849            0 :         tenant_conf
    3850            0 :             .pitr_interval
    3851            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3852            0 :     }
    3853              : 
    3854            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3855            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3856            0 :         tenant_conf
    3857            0 :             .min_resident_size_override
    3858            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3859            0 :     }
    3860              : 
    3861            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3862            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3863            0 :         let heatmap_period = tenant_conf
    3864            0 :             .heatmap_period
    3865            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3866            0 :         if heatmap_period.is_zero() {
    3867            0 :             None
    3868              :         } else {
    3869            0 :             Some(heatmap_period)
    3870              :         }
    3871            0 :     }
    3872              : 
    3873            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3874            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3875            8 :         tenant_conf
    3876            8 :             .lsn_lease_length
    3877            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3878            8 :     }
    3879              : 
    3880              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3881            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3882            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3883            4 : 
    3884            4 :         let mut timeline_manifests = timelines_offloaded
    3885            4 :             .iter()
    3886            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3887            4 :             .collect::<Vec<_>>();
    3888            4 :         // Sort the manifests so that our output is deterministic
    3889            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3890            4 : 
    3891            4 :         TenantManifest {
    3892            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3893            4 :             offloaded_timelines: timeline_manifests,
    3894            4 :         }
    3895            4 :     }
    3896              : 
    3897            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    3898            0 :         &self,
    3899            0 :         update: F,
    3900            0 :     ) -> anyhow::Result<TenantConfOpt> {
    3901            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3902            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3903            0 :         // this race is not possible if both request types come from the storage
    3904            0 :         // controller (as they should!) because an exclusive op lock is required
    3905            0 :         // on the storage controller side.
    3906            0 : 
    3907            0 :         self.tenant_conf
    3908            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    3909            0 :                 Ok(Arc::new(AttachedTenantConf {
    3910            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    3911            0 :                     location: attached_conf.location,
    3912            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    3913              :                 }))
    3914            0 :             })?;
    3915              : 
    3916            0 :         let updated = self.tenant_conf.load();
    3917            0 : 
    3918            0 :         self.tenant_conf_updated(&updated.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(&updated);
    3925            0 :         }
    3926              : 
    3927            0 :         Ok(updated.tenant_conf.clone())
    3928            0 :     }
    3929              : 
    3930            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3931            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3932            0 : 
    3933            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    3934            0 : 
    3935            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3936            0 :         // Don't hold self.timelines.lock() during the notifies.
    3937            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3938            0 :         // mutexes in struct Timeline in the future.
    3939            0 :         let timelines = self.list_timelines();
    3940            0 :         for timeline in timelines {
    3941            0 :             timeline.tenant_conf_updated(&new_conf);
    3942            0 :         }
    3943            0 :     }
    3944              : 
    3945          440 :     fn get_pagestream_throttle_config(
    3946          440 :         psconf: &'static PageServerConf,
    3947          440 :         overrides: &TenantConfOpt,
    3948          440 :     ) -> throttle::Config {
    3949          440 :         overrides
    3950          440 :             .timeline_get_throttle
    3951          440 :             .clone()
    3952          440 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3953          440 :     }
    3954              : 
    3955            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3956            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    3957            0 :         self.pagestream_throttle.reconfigure(conf)
    3958            0 :     }
    3959              : 
    3960              :     /// Helper function to create a new Timeline struct.
    3961              :     ///
    3962              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3963              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3964              :     /// map.
    3965              :     ///
    3966              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3967              :     /// and we might not have the ancestor present anymore which is fine for to be
    3968              :     /// deleted timelines.
    3969              :     #[allow(clippy::too_many_arguments)]
    3970          892 :     fn create_timeline_struct(
    3971          892 :         &self,
    3972          892 :         new_timeline_id: TimelineId,
    3973          892 :         new_metadata: &TimelineMetadata,
    3974          892 :         ancestor: Option<Arc<Timeline>>,
    3975          892 :         resources: TimelineResources,
    3976          892 :         cause: CreateTimelineCause,
    3977          892 :         create_idempotency: CreateTimelineIdempotency,
    3978          892 :     ) -> anyhow::Result<Arc<Timeline>> {
    3979          892 :         let state = match cause {
    3980              :             CreateTimelineCause::Load => {
    3981          892 :                 let ancestor_id = new_metadata.ancestor_timeline();
    3982          892 :                 anyhow::ensure!(
    3983          892 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    3984            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    3985              :                 );
    3986          892 :                 TimelineState::Loading
    3987              :             }
    3988            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    3989              :         };
    3990              : 
    3991          892 :         let pg_version = new_metadata.pg_version();
    3992          892 : 
    3993          892 :         let timeline = Timeline::new(
    3994          892 :             self.conf,
    3995          892 :             Arc::clone(&self.tenant_conf),
    3996          892 :             new_metadata,
    3997          892 :             ancestor,
    3998          892 :             new_timeline_id,
    3999          892 :             self.tenant_shard_id,
    4000          892 :             self.generation,
    4001          892 :             self.shard_identity,
    4002          892 :             self.walredo_mgr.clone(),
    4003          892 :             resources,
    4004          892 :             pg_version,
    4005          892 :             state,
    4006          892 :             self.attach_wal_lag_cooldown.clone(),
    4007          892 :             create_idempotency,
    4008          892 :             self.cancel.child_token(),
    4009          892 :         );
    4010          892 : 
    4011          892 :         Ok(timeline)
    4012          892 :     }
    4013              : 
    4014              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4015              :     /// to ensure proper cleanup of background tasks and metrics.
    4016              :     //
    4017              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4018              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4019              :     #[allow(clippy::too_many_arguments)]
    4020          440 :     fn new(
    4021          440 :         state: TenantState,
    4022          440 :         conf: &'static PageServerConf,
    4023          440 :         attached_conf: AttachedTenantConf,
    4024          440 :         shard_identity: ShardIdentity,
    4025          440 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4026          440 :         tenant_shard_id: TenantShardId,
    4027          440 :         remote_storage: GenericRemoteStorage,
    4028          440 :         deletion_queue_client: DeletionQueueClient,
    4029          440 :         l0_flush_global_state: L0FlushGlobalState,
    4030          440 :     ) -> Tenant {
    4031          440 :         debug_assert!(
    4032          440 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4033              :         );
    4034              : 
    4035          440 :         let (state, mut rx) = watch::channel(state);
    4036          440 : 
    4037          440 :         tokio::spawn(async move {
    4038          439 :             // reflect tenant state in metrics:
    4039          439 :             // - global per tenant state: TENANT_STATE_METRIC
    4040          439 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4041          439 :             //
    4042          439 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4043          439 :             // alerting.
    4044          439 : 
    4045          439 :             let tid = tenant_shard_id.to_string();
    4046          439 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4047          439 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4048              : 
    4049          879 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4050          879 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4051          879 :             }
    4052              : 
    4053          439 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4054          439 : 
    4055          439 :             let is_broken = tuple.1;
    4056          439 :             let mut counted_broken = if is_broken {
    4057              :                 // add the id to the set right away, there should not be any updates on the channel
    4058              :                 // after before tenant is removed, if ever
    4059            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4060            0 :                 true
    4061              :             } else {
    4062          439 :                 false
    4063              :             };
    4064              : 
    4065              :             loop {
    4066          879 :                 let labels = &tuple.0;
    4067          879 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4068          879 :                 current.inc();
    4069          879 : 
    4070          879 :                 if rx.changed().await.is_err() {
    4071              :                     // tenant has been dropped
    4072           28 :                     current.dec();
    4073           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4074           28 :                     break;
    4075          440 :                 }
    4076          440 : 
    4077          440 :                 current.dec();
    4078          440 :                 tuple = inspect_state(&rx.borrow_and_update());
    4079          440 : 
    4080          440 :                 let is_broken = tuple.1;
    4081          440 :                 if is_broken && !counted_broken {
    4082            0 :                     counted_broken = true;
    4083            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4084            0 :                     // access
    4085            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4086          440 :                 }
    4087              :             }
    4088          440 :         });
    4089          440 : 
    4090          440 :         Tenant {
    4091          440 :             tenant_shard_id,
    4092          440 :             shard_identity,
    4093          440 :             generation: attached_conf.location.generation,
    4094          440 :             conf,
    4095          440 :             // using now here is good enough approximation to catch tenants with really long
    4096          440 :             // activation times.
    4097          440 :             constructed_at: Instant::now(),
    4098          440 :             timelines: Mutex::new(HashMap::new()),
    4099          440 :             timelines_creating: Mutex::new(HashSet::new()),
    4100          440 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4101          440 :             tenant_manifest_upload: Default::default(),
    4102          440 :             gc_cs: tokio::sync::Mutex::new(()),
    4103          440 :             walredo_mgr,
    4104          440 :             remote_storage,
    4105          440 :             deletion_queue_client,
    4106          440 :             state,
    4107          440 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4108          440 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4109          440 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4110          440 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4111          440 :                 format!("compaction-{tenant_shard_id}"),
    4112          440 :                 5,
    4113          440 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4114          440 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4115          440 :                 // use an extremely long backoff.
    4116          440 :                 Some(Duration::from_secs(3600 * 24)),
    4117          440 :             )),
    4118          440 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4119          440 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4120          440 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4121          440 :             cancel: CancellationToken::default(),
    4122          440 :             gate: Gate::default(),
    4123          440 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4124          440 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4125          440 :             )),
    4126          440 :             pagestream_throttle_metrics: Arc::new(
    4127          440 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4128          440 :             ),
    4129          440 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4130          440 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4131          440 :             gc_block: Default::default(),
    4132          440 :             l0_flush_global_state,
    4133          440 :         }
    4134          440 :     }
    4135              : 
    4136              :     /// Locate and load config
    4137            0 :     pub(super) fn load_tenant_config(
    4138            0 :         conf: &'static PageServerConf,
    4139            0 :         tenant_shard_id: &TenantShardId,
    4140            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4141            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4142            0 : 
    4143            0 :         info!("loading tenant configuration from {config_path}");
    4144              : 
    4145              :         // load and parse file
    4146            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4147            0 :             match e.kind() {
    4148              :                 std::io::ErrorKind::NotFound => {
    4149              :                     // The config should almost always exist for a tenant directory:
    4150              :                     //  - When attaching a tenant, the config is the first thing we write
    4151              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4152              :                     //    before deleting contents.
    4153              :                     //
    4154              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4155              :                     // between creating directory and writing config.  Callers should handle that as if the
    4156              :                     // directory didn't exist.
    4157              : 
    4158            0 :                     LoadConfigError::NotFound(config_path)
    4159              :                 }
    4160              :                 _ => {
    4161              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4162              :                     // that we cannot cleanly recover
    4163            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4164              :                 }
    4165              :             }
    4166            0 :         })?;
    4167              : 
    4168            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4169            0 :     }
    4170              : 
    4171              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4172              :     pub(super) async fn persist_tenant_config(
    4173              :         conf: &'static PageServerConf,
    4174              :         tenant_shard_id: &TenantShardId,
    4175              :         location_conf: &LocationConf,
    4176              :     ) -> std::io::Result<()> {
    4177              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4178              : 
    4179              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4180              :     }
    4181              : 
    4182              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4183              :     pub(super) async fn persist_tenant_config_at(
    4184              :         tenant_shard_id: &TenantShardId,
    4185              :         config_path: &Utf8Path,
    4186              :         location_conf: &LocationConf,
    4187              :     ) -> std::io::Result<()> {
    4188              :         debug!("persisting tenantconf to {config_path}");
    4189              : 
    4190              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4191              : #  It is read in case of pageserver restart.
    4192              : "#
    4193              :         .to_string();
    4194              : 
    4195            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4196            0 :             Err(std::io::Error::new(
    4197            0 :                 std::io::ErrorKind::Other,
    4198            0 :                 "tenant-config-before-write",
    4199            0 :             ))
    4200            0 :         });
    4201              : 
    4202              :         // Convert the config to a toml file.
    4203              :         conf_content +=
    4204              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4205              : 
    4206              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4207              : 
    4208              :         let conf_content = conf_content.into_bytes();
    4209              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4210              :     }
    4211              : 
    4212              :     //
    4213              :     // How garbage collection works:
    4214              :     //
    4215              :     //                    +--bar------------->
    4216              :     //                   /
    4217              :     //             +----+-----foo---------------->
    4218              :     //            /
    4219              :     // ----main--+-------------------------->
    4220              :     //                \
    4221              :     //                 +-----baz-------->
    4222              :     //
    4223              :     //
    4224              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4225              :     //    `gc_infos` are being refreshed
    4226              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4227              :     //    all the points where other timelines have been branched off.
    4228              :     //    We will refrain from removing page versions at those LSNs.
    4229              :     // 3. For each timeline, scan all layer files on the timeline.
    4230              :     //    Remove all files for which a newer file exists and which
    4231              :     //    don't cover any branch point LSNs.
    4232              :     //
    4233              :     // TODO:
    4234              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4235              :     //   don't need to keep that in the parent anymore. But currently
    4236              :     //   we do.
    4237            8 :     async fn gc_iteration_internal(
    4238            8 :         &self,
    4239            8 :         target_timeline_id: Option<TimelineId>,
    4240            8 :         horizon: u64,
    4241            8 :         pitr: Duration,
    4242            8 :         cancel: &CancellationToken,
    4243            8 :         ctx: &RequestContext,
    4244            8 :     ) -> Result<GcResult, GcError> {
    4245            8 :         let mut totals: GcResult = Default::default();
    4246            8 :         let now = Instant::now();
    4247              : 
    4248            8 :         let gc_timelines = self
    4249            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4250            8 :             .await?;
    4251              : 
    4252            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4253              : 
    4254              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4255            8 :         if !gc_timelines.is_empty() {
    4256            8 :             info!("{} timelines need GC", gc_timelines.len());
    4257              :         } else {
    4258            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4259              :         }
    4260              : 
    4261              :         // Perform GC for each timeline.
    4262              :         //
    4263              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4264              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4265              :         // with branch creation.
    4266              :         //
    4267              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4268              :         // creation task can run concurrently with timeline's GC iteration.
    4269           16 :         for timeline in gc_timelines {
    4270            8 :             if cancel.is_cancelled() {
    4271              :                 // We were requested to shut down. Stop and return with the progress we
    4272              :                 // made.
    4273            0 :                 break;
    4274            8 :             }
    4275            8 :             let result = match timeline.gc().await {
    4276              :                 Err(GcError::TimelineCancelled) => {
    4277            0 :                     if target_timeline_id.is_some() {
    4278              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4279            0 :                         return Err(GcError::TimelineCancelled);
    4280              :                     } else {
    4281              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4282              :                         // skip past this and proceed to try GC on other timelines.
    4283            0 :                         continue;
    4284              :                     }
    4285              :                 }
    4286            8 :                 r => r?,
    4287              :             };
    4288            8 :             totals += result;
    4289              :         }
    4290              : 
    4291            8 :         totals.elapsed = now.elapsed();
    4292            8 :         Ok(totals)
    4293            8 :     }
    4294              : 
    4295              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4296              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4297              :     /// [`Tenant::get_gc_horizon`].
    4298              :     ///
    4299              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4300            0 :     pub(crate) async fn refresh_gc_info(
    4301            0 :         &self,
    4302            0 :         cancel: &CancellationToken,
    4303            0 :         ctx: &RequestContext,
    4304            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4305            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4306            0 :         // might be that these configuration values get applied faster than what it was previously,
    4307            0 :         // since these were only read from the gc task.
    4308            0 :         let horizon = self.get_gc_horizon();
    4309            0 :         let pitr = self.get_pitr_interval();
    4310            0 : 
    4311            0 :         // refresh all timelines
    4312            0 :         let target_timeline_id = None;
    4313            0 : 
    4314            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4315            0 :             .await
    4316            0 :     }
    4317              : 
    4318              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4319              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4320              :     ///
    4321              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4322            0 :     fn initialize_gc_info(
    4323            0 :         &self,
    4324            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4325            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4326            0 :         restrict_to_timeline: Option<TimelineId>,
    4327            0 :     ) {
    4328            0 :         if restrict_to_timeline.is_none() {
    4329              :             // This function must be called before activation: after activation timeline create/delete operations
    4330              :             // might happen, and this function is not safe to run concurrently with those.
    4331            0 :             assert!(!self.is_active());
    4332            0 :         }
    4333              : 
    4334              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4335              :         // the branch point where it was created.
    4336            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4337            0 :             BTreeMap::new();
    4338            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4339            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4340            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4341            0 :                 ancestor_children.push((
    4342            0 :                     timeline_entry.get_ancestor_lsn(),
    4343            0 :                     *timeline_id,
    4344            0 :                     MaybeOffloaded::No,
    4345            0 :                 ));
    4346            0 :             }
    4347            0 :         });
    4348            0 :         timelines_offloaded
    4349            0 :             .iter()
    4350            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4351            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4352            0 :                     return;
    4353              :                 };
    4354            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4355            0 :                     return;
    4356              :                 };
    4357            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4358            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4359            0 :             });
    4360            0 : 
    4361            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4362            0 :         let horizon = self.get_gc_horizon();
    4363              : 
    4364              :         // Populate each timeline's GcInfo with information about its child branches
    4365            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4366            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4367              :         } else {
    4368            0 :             itertools::Either::Right(timelines.values())
    4369              :         };
    4370            0 :         for timeline in timelines_to_write {
    4371            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4372            0 :                 .remove(&timeline.timeline_id)
    4373            0 :                 .unwrap_or_default();
    4374            0 : 
    4375            0 :             branchpoints.sort_by_key(|b| b.0);
    4376            0 : 
    4377            0 :             let mut target = timeline.gc_info.write().unwrap();
    4378            0 : 
    4379            0 :             target.retain_lsns = branchpoints;
    4380            0 : 
    4381            0 :             let space_cutoff = timeline
    4382            0 :                 .get_last_record_lsn()
    4383            0 :                 .checked_sub(horizon)
    4384            0 :                 .unwrap_or(Lsn(0));
    4385            0 : 
    4386            0 :             target.cutoffs = GcCutoffs {
    4387            0 :                 space: space_cutoff,
    4388            0 :                 time: Lsn::INVALID,
    4389            0 :             };
    4390            0 :         }
    4391            0 :     }
    4392              : 
    4393            8 :     async fn refresh_gc_info_internal(
    4394            8 :         &self,
    4395            8 :         target_timeline_id: Option<TimelineId>,
    4396            8 :         horizon: u64,
    4397            8 :         pitr: Duration,
    4398            8 :         cancel: &CancellationToken,
    4399            8 :         ctx: &RequestContext,
    4400            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4401            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4402            8 :         // currently visible timelines.
    4403            8 :         let timelines = self
    4404            8 :             .timelines
    4405            8 :             .lock()
    4406            8 :             .unwrap()
    4407            8 :             .values()
    4408            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4409            8 :                 Some(target) => &tl.timeline_id == target,
    4410            0 :                 None => true,
    4411            8 :             })
    4412            8 :             .cloned()
    4413            8 :             .collect::<Vec<_>>();
    4414            8 : 
    4415            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4416              :             // We were to act on a particular timeline and it wasn't found
    4417            0 :             return Err(GcError::TimelineNotFound);
    4418            8 :         }
    4419            8 : 
    4420            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4421            8 :             HashMap::with_capacity(timelines.len());
    4422            8 : 
    4423            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4424            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4425            8 :         for timeline in timelines.iter() {
    4426            8 :             let cutoff = timeline
    4427            8 :                 .get_last_record_lsn()
    4428            8 :                 .checked_sub(horizon)
    4429            8 :                 .unwrap_or(Lsn(0));
    4430              : 
    4431            8 :             let cutoffs = timeline
    4432            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4433            8 :                 .await?;
    4434            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4435            8 :             assert!(old.is_none());
    4436              :         }
    4437              : 
    4438            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4439            0 :             return Err(GcError::TenantCancelled);
    4440            8 :         }
    4441              : 
    4442              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4443              :         // because that will stall branch creation.
    4444            8 :         let gc_cs = self.gc_cs.lock().await;
    4445              : 
    4446              :         // Ok, we now know all the branch points.
    4447              :         // Update the GC information for each timeline.
    4448            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4449           16 :         for timeline in timelines {
    4450              :             // We filtered the timeline list above
    4451            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4452            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4453            0 :             }
    4454              : 
    4455              :             {
    4456            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4457            8 : 
    4458            8 :                 // Cull any expired leases
    4459            8 :                 let now = SystemTime::now();
    4460           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4461            8 : 
    4462            8 :                 timeline
    4463            8 :                     .metrics
    4464            8 :                     .valid_lsn_lease_count_gauge
    4465            8 :                     .set(target.leases.len() as u64);
    4466              : 
    4467              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4468            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4469            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4470            0 :                         target.within_ancestor_pitr =
    4471            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4472            0 :                     }
    4473            8 :                 }
    4474              : 
    4475              :                 // Update metrics that depend on GC state
    4476            8 :                 timeline
    4477            8 :                     .metrics
    4478            8 :                     .archival_size
    4479            8 :                     .set(if target.within_ancestor_pitr {
    4480            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4481              :                     } else {
    4482            8 :                         0
    4483              :                     });
    4484            8 :                 timeline.metrics.pitr_history_size.set(
    4485            8 :                     timeline
    4486            8 :                         .get_last_record_lsn()
    4487            8 :                         .checked_sub(target.cutoffs.time)
    4488            8 :                         .unwrap_or(Lsn(0))
    4489            8 :                         .0,
    4490            8 :                 );
    4491              : 
    4492              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4493              :                 // - this timeline was created while we were finding cutoffs
    4494              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4495            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4496            8 :                     let original_cutoffs = target.cutoffs.clone();
    4497            8 :                     // GC cutoffs should never go back
    4498            8 :                     target.cutoffs = GcCutoffs {
    4499            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4500            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4501            8 :                     }
    4502            0 :                 }
    4503              :             }
    4504              : 
    4505            8 :             gc_timelines.push(timeline);
    4506              :         }
    4507            8 :         drop(gc_cs);
    4508            8 :         Ok(gc_timelines)
    4509            8 :     }
    4510              : 
    4511              :     /// A substitute for `branch_timeline` for use in unit tests.
    4512              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4513              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4514              :     /// timeline background tasks are launched, except the flush loop.
    4515              :     #[cfg(test)]
    4516          464 :     async fn branch_timeline_test(
    4517          464 :         self: &Arc<Self>,
    4518          464 :         src_timeline: &Arc<Timeline>,
    4519          464 :         dst_id: TimelineId,
    4520          464 :         ancestor_lsn: Option<Lsn>,
    4521          464 :         ctx: &RequestContext,
    4522          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4523          464 :         let tl = self
    4524          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4525          464 :             .await?
    4526          456 :             .into_timeline_for_test();
    4527          456 :         tl.set_state(TimelineState::Active);
    4528          456 :         Ok(tl)
    4529          464 :     }
    4530              : 
    4531              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4532              :     #[cfg(test)]
    4533              :     #[allow(clippy::too_many_arguments)]
    4534           12 :     pub async fn branch_timeline_test_with_layers(
    4535           12 :         self: &Arc<Self>,
    4536           12 :         src_timeline: &Arc<Timeline>,
    4537           12 :         dst_id: TimelineId,
    4538           12 :         ancestor_lsn: Option<Lsn>,
    4539           12 :         ctx: &RequestContext,
    4540           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4541           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4542           12 :         end_lsn: Lsn,
    4543           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4544              :         use checks::check_valid_layermap;
    4545              :         use itertools::Itertools;
    4546              : 
    4547           12 :         let tline = self
    4548           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4549           12 :             .await?;
    4550           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4551           12 :             ancestor_lsn
    4552              :         } else {
    4553            0 :             tline.get_last_record_lsn()
    4554              :         };
    4555           12 :         assert!(end_lsn >= ancestor_lsn);
    4556           12 :         tline.force_advance_lsn(end_lsn);
    4557           24 :         for deltas in delta_layer_desc {
    4558           12 :             tline
    4559           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4560           12 :                 .await?;
    4561              :         }
    4562           20 :         for (lsn, images) in image_layer_desc {
    4563            8 :             tline
    4564            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4565            8 :                 .await?;
    4566              :         }
    4567           12 :         let layer_names = tline
    4568           12 :             .layers
    4569           12 :             .read()
    4570           12 :             .await
    4571           12 :             .layer_map()
    4572           12 :             .unwrap()
    4573           12 :             .iter_historic_layers()
    4574           20 :             .map(|layer| layer.layer_name())
    4575           12 :             .collect_vec();
    4576           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4577            0 :             bail!("invalid layermap: {err}");
    4578           12 :         }
    4579           12 :         Ok(tline)
    4580           12 :     }
    4581              : 
    4582              :     /// Branch an existing timeline.
    4583            0 :     async fn branch_timeline(
    4584            0 :         self: &Arc<Self>,
    4585            0 :         src_timeline: &Arc<Timeline>,
    4586            0 :         dst_id: TimelineId,
    4587            0 :         start_lsn: Option<Lsn>,
    4588            0 :         ctx: &RequestContext,
    4589            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4590            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4591            0 :             .await
    4592            0 :     }
    4593              : 
    4594          464 :     async fn branch_timeline_impl(
    4595          464 :         self: &Arc<Self>,
    4596          464 :         src_timeline: &Arc<Timeline>,
    4597          464 :         dst_id: TimelineId,
    4598          464 :         start_lsn: Option<Lsn>,
    4599          464 :         _ctx: &RequestContext,
    4600          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4601          464 :         let src_id = src_timeline.timeline_id;
    4602              : 
    4603              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4604              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4605              :         // valid while we are creating the branch.
    4606          464 :         let _gc_cs = self.gc_cs.lock().await;
    4607              : 
    4608              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4609          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4610            4 :             let lsn = src_timeline.get_last_record_lsn();
    4611            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4612            4 :             lsn
    4613          464 :         });
    4614              : 
    4615              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4616          464 :         let timeline_create_guard = match self
    4617          464 :             .start_creating_timeline(
    4618          464 :                 dst_id,
    4619          464 :                 CreateTimelineIdempotency::Branch {
    4620          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4621          464 :                     ancestor_start_lsn: start_lsn,
    4622          464 :                 },
    4623          464 :             )
    4624          464 :             .await?
    4625              :         {
    4626          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4627            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4628            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4629              :             }
    4630              :         };
    4631              : 
    4632              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4633              :         // horizon on the source timeline
    4634              :         //
    4635              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4636              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4637              :         // planned GC cutoff in 'gc_info' is normally larger than
    4638              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4639              :         // changed the GC settings for the tenant to make the PITR window
    4640              :         // larger, but some of the data was already removed by an earlier GC
    4641              :         // iteration.
    4642              : 
    4643              :         // check against last actual 'latest_gc_cutoff' first
    4644          464 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4645          464 :         src_timeline
    4646          464 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4647          464 :             .context(format!(
    4648          464 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4649          464 :                 *latest_gc_cutoff_lsn,
    4650          464 :             ))
    4651          464 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4652              : 
    4653              :         // and then the planned GC cutoff
    4654              :         {
    4655          456 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4656          456 :             let cutoff = gc_info.min_cutoff();
    4657          456 :             if start_lsn < cutoff {
    4658            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4659            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4660            0 :                 )));
    4661          456 :             }
    4662          456 :         }
    4663          456 : 
    4664          456 :         //
    4665          456 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4666          456 :         // so that GC cannot advance the GC cutoff until we are finished.
    4667          456 :         // Proceed with the branch creation.
    4668          456 :         //
    4669          456 : 
    4670          456 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4671          456 :         // the timeline was branched at the current end of the source timeline.
    4672          456 :         let RecordLsn {
    4673          456 :             last: src_last,
    4674          456 :             prev: src_prev,
    4675          456 :         } = src_timeline.get_last_record_rlsn();
    4676          456 :         let dst_prev = if src_last == start_lsn {
    4677          432 :             Some(src_prev)
    4678              :         } else {
    4679           24 :             None
    4680              :         };
    4681              : 
    4682              :         // Create the metadata file, noting the ancestor of the new timeline.
    4683              :         // There is initially no data in it, but all the read-calls know to look
    4684              :         // into the ancestor.
    4685          456 :         let metadata = TimelineMetadata::new(
    4686          456 :             start_lsn,
    4687          456 :             dst_prev,
    4688          456 :             Some(src_id),
    4689          456 :             start_lsn,
    4690          456 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4691          456 :             src_timeline.initdb_lsn,
    4692          456 :             src_timeline.pg_version,
    4693          456 :         );
    4694              : 
    4695          456 :         let uninitialized_timeline = self
    4696          456 :             .prepare_new_timeline(
    4697          456 :                 dst_id,
    4698          456 :                 &metadata,
    4699          456 :                 timeline_create_guard,
    4700          456 :                 start_lsn + 1,
    4701          456 :                 Some(Arc::clone(src_timeline)),
    4702          456 :             )
    4703          456 :             .await?;
    4704              : 
    4705          456 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4706              : 
    4707              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4708              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4709              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4710              :         // could get incorrect information and remove more layers, than needed.
    4711              :         // See also https://github.com/neondatabase/neon/issues/3865
    4712          456 :         new_timeline
    4713          456 :             .remote_client
    4714          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4715          456 :             .context("branch initial metadata upload")?;
    4716              : 
    4717              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4718              : 
    4719          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4720          464 :     }
    4721              : 
    4722              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4723              :     #[cfg(test)]
    4724              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4725              :     pub(crate) async fn bootstrap_timeline_test(
    4726              :         self: &Arc<Self>,
    4727              :         timeline_id: TimelineId,
    4728              :         pg_version: u32,
    4729              :         load_existing_initdb: Option<TimelineId>,
    4730              :         ctx: &RequestContext,
    4731              :     ) -> anyhow::Result<Arc<Timeline>> {
    4732              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4733              :             .await
    4734              :             .map_err(anyhow::Error::new)
    4735            4 :             .map(|r| r.into_timeline_for_test())
    4736              :     }
    4737              : 
    4738              :     /// Get exclusive access to the timeline ID for creation.
    4739              :     ///
    4740              :     /// Timeline-creating code paths must use this function before making changes
    4741              :     /// to in-memory or persistent state.
    4742              :     ///
    4743              :     /// The `state` parameter is a description of the timeline creation operation
    4744              :     /// we intend to perform.
    4745              :     /// If the timeline was already created in the meantime, we check whether this
    4746              :     /// request conflicts or is idempotent , based on `state`.
    4747          892 :     async fn start_creating_timeline(
    4748          892 :         self: &Arc<Self>,
    4749          892 :         new_timeline_id: TimelineId,
    4750          892 :         idempotency: CreateTimelineIdempotency,
    4751          892 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4752          892 :         let allow_offloaded = false;
    4753          892 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4754          888 :             Ok(create_guard) => {
    4755          888 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4756          888 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4757              :             }
    4758            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4759              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4760              :                 // Creation is in progress, we cannot create it again, and we cannot
    4761              :                 // check if this request matches the existing one, so caller must try
    4762              :                 // again later.
    4763            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4764              :             }
    4765            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4766              :             Err(TimelineExclusionError::AlreadyExists {
    4767            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4768            0 :                 ..
    4769            0 :             }) => {
    4770            0 :                 info!("timeline already exists but is offloaded");
    4771            0 :                 Err(CreateTimelineError::Conflict)
    4772              :             }
    4773              :             Err(TimelineExclusionError::AlreadyExists {
    4774            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4775            4 :                 arg,
    4776            4 :             }) => {
    4777            4 :                 {
    4778            4 :                     let existing = &existing.create_idempotency;
    4779            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4780            4 :                     debug!("timeline already exists");
    4781              : 
    4782            4 :                     match (existing, &arg) {
    4783              :                         // FailWithConflict => no idempotency check
    4784              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4785              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4786            4 :                             warn!("timeline already exists, failing request");
    4787            4 :                             return Err(CreateTimelineError::Conflict);
    4788              :                         }
    4789              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4790            0 :                         (x, y) if x == y => {
    4791            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4792              :                             // fallthrough
    4793              :                         }
    4794              :                         (_, _) => {
    4795            0 :                             warn!("idempotency conflict, failing request");
    4796            0 :                             return Err(CreateTimelineError::Conflict);
    4797              :                         }
    4798              :                     }
    4799              :                 }
    4800              : 
    4801            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4802              :             }
    4803              :         }
    4804          892 :     }
    4805              : 
    4806            0 :     async fn upload_initdb(
    4807            0 :         &self,
    4808            0 :         timelines_path: &Utf8PathBuf,
    4809            0 :         pgdata_path: &Utf8PathBuf,
    4810            0 :         timeline_id: &TimelineId,
    4811            0 :     ) -> anyhow::Result<()> {
    4812            0 :         let temp_path = timelines_path.join(format!(
    4813            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4814            0 :         ));
    4815            0 : 
    4816            0 :         scopeguard::defer! {
    4817            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4818            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4819            0 :             }
    4820            0 :         }
    4821              : 
    4822            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4823              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4824            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4825            0 :             warn!(
    4826            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4827              :             );
    4828            0 :         }
    4829              : 
    4830            0 :         pausable_failpoint!("before-initdb-upload");
    4831              : 
    4832            0 :         backoff::retry(
    4833            0 :             || async {
    4834            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4835            0 :                     &self.remote_storage,
    4836            0 :                     &self.tenant_shard_id.tenant_id,
    4837            0 :                     timeline_id,
    4838            0 :                     pgdata_zstd.try_clone().await?,
    4839            0 :                     tar_zst_size,
    4840            0 :                     &self.cancel,
    4841            0 :                 )
    4842            0 :                 .await
    4843            0 :             },
    4844            0 :             |_| false,
    4845            0 :             3,
    4846            0 :             u32::MAX,
    4847            0 :             "persist_initdb_tar_zst",
    4848            0 :             &self.cancel,
    4849            0 :         )
    4850            0 :         .await
    4851            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4852            0 :         .and_then(|x| x)
    4853            0 :     }
    4854              : 
    4855              :     /// - run initdb to init temporary instance and get bootstrap data
    4856              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4857            4 :     async fn bootstrap_timeline(
    4858            4 :         self: &Arc<Self>,
    4859            4 :         timeline_id: TimelineId,
    4860            4 :         pg_version: u32,
    4861            4 :         load_existing_initdb: Option<TimelineId>,
    4862            4 :         ctx: &RequestContext,
    4863            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4864            4 :         let timeline_create_guard = match self
    4865            4 :             .start_creating_timeline(
    4866            4 :                 timeline_id,
    4867            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4868            4 :             )
    4869            4 :             .await?
    4870              :         {
    4871            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4872            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4873            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4874              :             }
    4875              :         };
    4876              : 
    4877              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4878              :         // temporary directory for basebackup files for the given timeline.
    4879              : 
    4880            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4881            4 :         let pgdata_path = path_with_suffix_extension(
    4882            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4883            4 :             TEMP_FILE_SUFFIX,
    4884            4 :         );
    4885            4 : 
    4886            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4887            4 :         // we won't race with other creations or existent timelines with the same path.
    4888            4 :         if pgdata_path.exists() {
    4889            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4890            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4891            0 :             })?;
    4892            4 :         }
    4893              : 
    4894              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4895            4 :         scopeguard::defer! {
    4896            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4897            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4898            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4899            4 :             }
    4900            4 :         }
    4901            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4902            4 :             if existing_initdb_timeline_id != timeline_id {
    4903            0 :                 let source_path = &remote_initdb_archive_path(
    4904            0 :                     &self.tenant_shard_id.tenant_id,
    4905            0 :                     &existing_initdb_timeline_id,
    4906            0 :                 );
    4907            0 :                 let dest_path =
    4908            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4909            0 : 
    4910            0 :                 // if this fails, it will get retried by retried control plane requests
    4911            0 :                 self.remote_storage
    4912            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4913            0 :                     .await
    4914            0 :                     .context("copy initdb tar")?;
    4915            4 :             }
    4916            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4917            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4918            4 :                     self.conf,
    4919            4 :                     &self.remote_storage,
    4920            4 :                     &self.tenant_shard_id,
    4921            4 :                     &existing_initdb_timeline_id,
    4922            4 :                     &self.cancel,
    4923            4 :                 )
    4924            4 :                 .await
    4925            4 :                 .context("download initdb tar")?;
    4926              : 
    4927            4 :             scopeguard::defer! {
    4928            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4929            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4930            4 :                 }
    4931            4 :             }
    4932            4 : 
    4933            4 :             let buf_read =
    4934            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4935            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    4936            4 :                 .await
    4937            4 :                 .context("extract initdb tar")?;
    4938              :         } else {
    4939              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4940            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4941            0 :                 .await
    4942            0 :                 .context("run initdb")?;
    4943              : 
    4944              :             // Upload the created data dir to S3
    4945            0 :             if self.tenant_shard_id().is_shard_zero() {
    4946            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4947            0 :                     .await?;
    4948            0 :             }
    4949              :         }
    4950            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4951            4 : 
    4952            4 :         // Import the contents of the data directory at the initial checkpoint
    4953            4 :         // LSN, and any WAL after that.
    4954            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4955            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4956            4 :         let new_metadata = TimelineMetadata::new(
    4957            4 :             Lsn(0),
    4958            4 :             None,
    4959            4 :             None,
    4960            4 :             Lsn(0),
    4961            4 :             pgdata_lsn,
    4962            4 :             pgdata_lsn,
    4963            4 :             pg_version,
    4964            4 :         );
    4965            4 :         let raw_timeline = self
    4966            4 :             .prepare_new_timeline(
    4967            4 :                 timeline_id,
    4968            4 :                 &new_metadata,
    4969            4 :                 timeline_create_guard,
    4970            4 :                 pgdata_lsn,
    4971            4 :                 None,
    4972            4 :             )
    4973            4 :             .await?;
    4974              : 
    4975            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4976            4 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4977              : 
    4978              :         // Flush the new layer files to disk, before we make the timeline as available to
    4979              :         // the outside world.
    4980              :         //
    4981              :         // Flush loop needs to be spawned in order to be able to flush.
    4982            4 :         unfinished_timeline.maybe_spawn_flush_loop();
    4983            4 : 
    4984            4 :         import_datadir::import_timeline_from_postgres_datadir(
    4985            4 :             unfinished_timeline,
    4986            4 :             &pgdata_path,
    4987            4 :             pgdata_lsn,
    4988            4 :             ctx,
    4989            4 :         )
    4990            4 :         .await
    4991            4 :         .with_context(|| {
    4992            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    4993            4 :         })?;
    4994              : 
    4995            4 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    4996            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    4997            0 :                 "failpoint before-checkpoint-new-timeline"
    4998            0 :             )))
    4999            4 :         });
    5000              : 
    5001            4 :         unfinished_timeline
    5002            4 :             .freeze_and_flush()
    5003            4 :             .await
    5004            4 :             .with_context(|| {
    5005            0 :                 format!(
    5006            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    5007            0 :                 )
    5008            4 :             })?;
    5009              : 
    5010              :         // All done!
    5011            4 :         let timeline = raw_timeline.finish_creation()?;
    5012              : 
    5013              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5014              : 
    5015            4 :         Ok(CreateTimelineResult::Created(timeline))
    5016            4 :     }
    5017              : 
    5018          880 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5019          880 :         RemoteTimelineClient::new(
    5020          880 :             self.remote_storage.clone(),
    5021          880 :             self.deletion_queue_client.clone(),
    5022          880 :             self.conf,
    5023          880 :             self.tenant_shard_id,
    5024          880 :             timeline_id,
    5025          880 :             self.generation,
    5026          880 :             &self.tenant_conf.load().location,
    5027          880 :         )
    5028          880 :     }
    5029              : 
    5030              :     /// Call this before constructing a timeline, to build its required structures
    5031          880 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5032          880 :         TimelineResources {
    5033          880 :             remote_client: self.build_timeline_remote_client(timeline_id),
    5034          880 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5035          880 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5036          880 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5037          880 :         }
    5038          880 :     }
    5039              : 
    5040              :     /// Creates intermediate timeline structure and its files.
    5041              :     ///
    5042              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5043              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5044              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5045          880 :     async fn prepare_new_timeline<'a>(
    5046          880 :         &'a self,
    5047          880 :         new_timeline_id: TimelineId,
    5048          880 :         new_metadata: &TimelineMetadata,
    5049          880 :         create_guard: TimelineCreateGuard,
    5050          880 :         start_lsn: Lsn,
    5051          880 :         ancestor: Option<Arc<Timeline>>,
    5052          880 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5053          880 :         let tenant_shard_id = self.tenant_shard_id;
    5054          880 : 
    5055          880 :         let resources = self.build_timeline_resources(new_timeline_id);
    5056          880 :         resources
    5057          880 :             .remote_client
    5058          880 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5059              : 
    5060          880 :         let timeline_struct = self
    5061          880 :             .create_timeline_struct(
    5062          880 :                 new_timeline_id,
    5063          880 :                 new_metadata,
    5064          880 :                 ancestor,
    5065          880 :                 resources,
    5066          880 :                 CreateTimelineCause::Load,
    5067          880 :                 create_guard.idempotency.clone(),
    5068          880 :             )
    5069          880 :             .context("Failed to create timeline data structure")?;
    5070              : 
    5071          880 :         timeline_struct.init_empty_layer_map(start_lsn);
    5072              : 
    5073          880 :         if let Err(e) = self
    5074          880 :             .create_timeline_files(&create_guard.timeline_path)
    5075          880 :             .await
    5076              :         {
    5077            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5078            0 :             cleanup_timeline_directory(create_guard);
    5079            0 :             return Err(e);
    5080          880 :         }
    5081          880 : 
    5082          880 :         debug!(
    5083            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5084              :         );
    5085              : 
    5086          880 :         Ok(UninitializedTimeline::new(
    5087          880 :             self,
    5088          880 :             new_timeline_id,
    5089          880 :             Some((timeline_struct, create_guard)),
    5090          880 :         ))
    5091          880 :     }
    5092              : 
    5093          880 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5094          880 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5095              : 
    5096          880 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5097            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5098          880 :         });
    5099              : 
    5100          880 :         Ok(())
    5101          880 :     }
    5102              : 
    5103              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5104              :     /// concurrent attempts to create the same timeline.
    5105              :     ///
    5106              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5107              :     /// offloaded timelines or not.
    5108          892 :     fn create_timeline_create_guard(
    5109          892 :         self: &Arc<Self>,
    5110          892 :         timeline_id: TimelineId,
    5111          892 :         idempotency: CreateTimelineIdempotency,
    5112          892 :         allow_offloaded: bool,
    5113          892 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5114          892 :         let tenant_shard_id = self.tenant_shard_id;
    5115          892 : 
    5116          892 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5117              : 
    5118          892 :         let create_guard = TimelineCreateGuard::new(
    5119          892 :             self,
    5120          892 :             timeline_id,
    5121          892 :             timeline_path.clone(),
    5122          892 :             idempotency,
    5123          892 :             allow_offloaded,
    5124          892 :         )?;
    5125              : 
    5126              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5127              :         // for creation.
    5128              :         // A timeline directory should never exist on disk already:
    5129              :         // - a previous failed creation would have cleaned up after itself
    5130              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5131              :         //
    5132              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5133              :         // this error may indicate a bug in cleanup on failed creations.
    5134          888 :         if timeline_path.exists() {
    5135            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5136            0 :                 "Timeline directory already exists! This is a bug."
    5137            0 :             )));
    5138          888 :         }
    5139          888 : 
    5140          888 :         Ok(create_guard)
    5141          892 :     }
    5142              : 
    5143              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5144              :     ///
    5145              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5146              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5147              :     pub async fn gather_size_inputs(
    5148              :         &self,
    5149              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5150              :         // (only if it is shorter than the real cutoff).
    5151              :         max_retention_period: Option<u64>,
    5152              :         cause: LogicalSizeCalculationCause,
    5153              :         cancel: &CancellationToken,
    5154              :         ctx: &RequestContext,
    5155              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5156              :         let logical_sizes_at_once = self
    5157              :             .conf
    5158              :             .concurrent_tenant_size_logical_size_queries
    5159              :             .inner();
    5160              : 
    5161              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5162              :         //
    5163              :         // But the only case where we need to run multiple of these at once is when we
    5164              :         // request a size for a tenant manually via API, while another background calculation
    5165              :         // is in progress (which is not a common case).
    5166              :         //
    5167              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5168              :         let mut shared_cache = tokio::select! {
    5169              :             locked = self.cached_logical_sizes.lock() => locked,
    5170              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5171              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5172              :         };
    5173              : 
    5174              :         size::gather_inputs(
    5175              :             self,
    5176              :             logical_sizes_at_once,
    5177              :             max_retention_period,
    5178              :             &mut shared_cache,
    5179              :             cause,
    5180              :             cancel,
    5181              :             ctx,
    5182              :         )
    5183              :         .await
    5184              :     }
    5185              : 
    5186              :     /// Calculate synthetic tenant size and cache the result.
    5187              :     /// This is periodically called by background worker.
    5188              :     /// result is cached in tenant struct
    5189              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5190              :     pub async fn calculate_synthetic_size(
    5191              :         &self,
    5192              :         cause: LogicalSizeCalculationCause,
    5193              :         cancel: &CancellationToken,
    5194              :         ctx: &RequestContext,
    5195              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5196              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5197              : 
    5198              :         let size = inputs.calculate();
    5199              : 
    5200              :         self.set_cached_synthetic_size(size);
    5201              : 
    5202              :         Ok(size)
    5203              :     }
    5204              : 
    5205              :     /// Cache given synthetic size and update the metric value
    5206            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5207            0 :         self.cached_synthetic_tenant_size
    5208            0 :             .store(size, Ordering::Relaxed);
    5209            0 : 
    5210            0 :         // Only shard zero should be calculating synthetic sizes
    5211            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5212              : 
    5213            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5214            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5215            0 :             .unwrap()
    5216            0 :             .set(size);
    5217            0 :     }
    5218              : 
    5219            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5220            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5221            0 :     }
    5222              : 
    5223              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5224              :     ///
    5225              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5226              :     /// from an external API handler.
    5227              :     ///
    5228              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5229              :     /// still bounded by tenant/timeline shutdown.
    5230              :     #[tracing::instrument(skip_all)]
    5231              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5232              :         let timelines = self.timelines.lock().unwrap().clone();
    5233              : 
    5234            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5235            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5236            0 :             timeline.freeze_and_flush().await?;
    5237            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5238            0 :             timeline.remote_client.wait_completion().await?;
    5239              : 
    5240            0 :             Ok(())
    5241            0 :         }
    5242              : 
    5243              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5244              :         // aborted when this function's future is cancelled: they should stay alive
    5245              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5246              :         // before Timeline shutdown completes.
    5247              :         let mut results = FuturesUnordered::new();
    5248              : 
    5249              :         for (_timeline_id, timeline) in timelines {
    5250              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5251              :             // means that if this function's future is cancelled, the Timeline shutdown
    5252              :             // will still wait for any I/O in here to complete.
    5253              :             let Ok(gate) = timeline.gate.enter() else {
    5254              :                 continue;
    5255              :             };
    5256            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5257              :             results.push(jh);
    5258              :         }
    5259              : 
    5260              :         while let Some(r) = results.next().await {
    5261              :             if let Err(e) = r {
    5262              :                 if !e.is_cancelled() && !e.is_panic() {
    5263              :                     tracing::error!("unexpected join error: {e:?}");
    5264              :                 }
    5265              :             }
    5266              :         }
    5267              : 
    5268              :         // The flushes we did above were just writes, but the Tenant might have had
    5269              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5270              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5271              :         // because it's typically a no-op.
    5272              :         match self.deletion_queue_client.flush_execute().await {
    5273              :             Ok(_) => {}
    5274              :             Err(DeletionQueueError::ShuttingDown) => {}
    5275              :         }
    5276              : 
    5277              :         Ok(())
    5278              :     }
    5279              : 
    5280            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5281            0 :         self.tenant_conf.load().tenant_conf.clone()
    5282            0 :     }
    5283              : 
    5284              :     /// How much local storage would this tenant like to have?  It can cope with
    5285              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5286              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5287              :     /// by keeping important things on local disk.
    5288              :     ///
    5289              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5290              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5291              :     /// actually use more than they report here.
    5292            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5293            0 :         let timelines = self.timelines.lock().unwrap();
    5294            0 : 
    5295            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5296            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5297            0 :         // of them is used actively enough to occupy space on disk.
    5298            0 :         timelines
    5299            0 :             .values()
    5300            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5301            0 :             .max()
    5302            0 :             .unwrap_or(0)
    5303            0 :     }
    5304              : 
    5305              :     /// Serialize and write the latest TenantManifest to remote storage.
    5306            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5307              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5308              :         // must be loaded while holding this lock. This makes it safe to call this function
    5309              :         // from anywhere without worrying about colliding updates.
    5310            4 :         let mut guard = tokio::select! {
    5311            4 :             g = self.tenant_manifest_upload.lock() => {
    5312            4 :                 g
    5313              :             },
    5314            4 :             _ = self.cancel.cancelled() => {
    5315            0 :                 return Err(TenantManifestError::Cancelled);
    5316              :             }
    5317              :         };
    5318              : 
    5319            4 :         let manifest = self.build_tenant_manifest();
    5320            4 :         if Some(&manifest) == (*guard).as_ref() {
    5321              :             // Optimisation: skip uploads that don't change anything.
    5322            0 :             return Ok(());
    5323            4 :         }
    5324            4 : 
    5325            4 :         // Remote storage does no retries internally, so wrap it
    5326            4 :         match backoff::retry(
    5327            4 :             || async {
    5328            4 :                 upload_tenant_manifest(
    5329            4 :                     &self.remote_storage,
    5330            4 :                     &self.tenant_shard_id,
    5331            4 :                     self.generation,
    5332            4 :                     &manifest,
    5333            4 :                     &self.cancel,
    5334            4 :                 )
    5335            4 :                 .await
    5336            8 :             },
    5337            4 :             |_e| self.cancel.is_cancelled(),
    5338            4 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5339            4 :             FAILED_REMOTE_OP_RETRIES,
    5340            4 :             "uploading tenant manifest",
    5341            4 :             &self.cancel,
    5342            4 :         )
    5343            4 :         .await
    5344              :         {
    5345            0 :             None => Err(TenantManifestError::Cancelled),
    5346            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5347            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5348              :             Some(Ok(_)) => {
    5349              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5350              :                 // re-uploading the same thing.
    5351            4 :                 *guard = Some(manifest);
    5352            4 : 
    5353            4 :                 Ok(())
    5354              :             }
    5355              :         }
    5356            4 :     }
    5357              : }
    5358              : 
    5359              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5360              : /// to get bootstrap data for timeline initialization.
    5361            0 : async fn run_initdb(
    5362            0 :     conf: &'static PageServerConf,
    5363            0 :     initdb_target_dir: &Utf8Path,
    5364            0 :     pg_version: u32,
    5365            0 :     cancel: &CancellationToken,
    5366            0 : ) -> Result<(), InitdbError> {
    5367            0 :     let initdb_bin_path = conf
    5368            0 :         .pg_bin_dir(pg_version)
    5369            0 :         .map_err(InitdbError::Other)?
    5370            0 :         .join("initdb");
    5371            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5372            0 :     info!(
    5373            0 :         "running {} in {}, libdir: {}",
    5374              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5375              :     );
    5376              : 
    5377            0 :     let _permit = {
    5378            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5379            0 :         INIT_DB_SEMAPHORE.acquire().await
    5380              :     };
    5381              : 
    5382            0 :     CONCURRENT_INITDBS.inc();
    5383            0 :     scopeguard::defer! {
    5384            0 :         CONCURRENT_INITDBS.dec();
    5385            0 :     }
    5386            0 : 
    5387            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5388            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5389            0 :         superuser: &conf.superuser,
    5390            0 :         locale: &conf.locale,
    5391            0 :         initdb_bin: &initdb_bin_path,
    5392            0 :         pg_version,
    5393            0 :         library_search_path: &initdb_lib_dir,
    5394            0 :         pgdata: initdb_target_dir,
    5395            0 :     })
    5396            0 :     .await
    5397            0 :     .map_err(InitdbError::Inner);
    5398            0 : 
    5399            0 :     // This isn't true cancellation support, see above. Still return an error to
    5400            0 :     // excercise the cancellation code path.
    5401            0 :     if cancel.is_cancelled() {
    5402            0 :         return Err(InitdbError::Cancelled);
    5403            0 :     }
    5404            0 : 
    5405            0 :     res
    5406            0 : }
    5407              : 
    5408              : /// Dump contents of a layer file to stdout.
    5409            0 : pub async fn dump_layerfile_from_path(
    5410            0 :     path: &Utf8Path,
    5411            0 :     verbose: bool,
    5412            0 :     ctx: &RequestContext,
    5413            0 : ) -> anyhow::Result<()> {
    5414              :     use std::os::unix::fs::FileExt;
    5415              : 
    5416              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5417              :     // file.
    5418            0 :     let file = File::open(path)?;
    5419            0 :     let mut header_buf = [0u8; 2];
    5420            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5421              : 
    5422            0 :     match u16::from_be_bytes(header_buf) {
    5423              :         crate::IMAGE_FILE_MAGIC => {
    5424            0 :             ImageLayer::new_for_path(path, file)?
    5425            0 :                 .dump(verbose, ctx)
    5426            0 :                 .await?
    5427              :         }
    5428              :         crate::DELTA_FILE_MAGIC => {
    5429            0 :             DeltaLayer::new_for_path(path, file)?
    5430            0 :                 .dump(verbose, ctx)
    5431            0 :                 .await?
    5432              :         }
    5433            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5434              :     }
    5435              : 
    5436            0 :     Ok(())
    5437            0 : }
    5438              : 
    5439              : #[cfg(test)]
    5440              : pub(crate) mod harness {
    5441              :     use bytes::{Bytes, BytesMut};
    5442              :     use once_cell::sync::OnceCell;
    5443              :     use pageserver_api::models::ShardParameters;
    5444              :     use pageserver_api::shard::ShardIndex;
    5445              :     use utils::logging;
    5446              : 
    5447              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5448              :     use crate::l0_flush::L0FlushConfig;
    5449              :     use crate::walredo::apply_neon;
    5450              :     use pageserver_api::key::Key;
    5451              :     use pageserver_api::record::NeonWalRecord;
    5452              : 
    5453              :     use super::*;
    5454              :     use hex_literal::hex;
    5455              :     use utils::id::TenantId;
    5456              : 
    5457              :     pub const TIMELINE_ID: TimelineId =
    5458              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5459              :     pub const NEW_TIMELINE_ID: TimelineId =
    5460              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5461              : 
    5462              :     /// Convenience function to create a page image with given string as the only content
    5463     10057556 :     pub fn test_img(s: &str) -> Bytes {
    5464     10057556 :         let mut buf = BytesMut::new();
    5465     10057556 :         buf.extend_from_slice(s.as_bytes());
    5466     10057556 :         buf.resize(64, 0);
    5467     10057556 : 
    5468     10057556 :         buf.freeze()
    5469     10057556 :     }
    5470              : 
    5471              :     impl From<TenantConf> for TenantConfOpt {
    5472          440 :         fn from(tenant_conf: TenantConf) -> Self {
    5473          440 :             Self {
    5474          440 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5475          440 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5476          440 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5477          440 :                 compaction_period: Some(tenant_conf.compaction_period),
    5478          440 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5479          440 :                 compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
    5480          440 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5481          440 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5482          440 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5483          440 :                 l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
    5484          440 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5485          440 :                 gc_period: Some(tenant_conf.gc_period),
    5486          440 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5487          440 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5488          440 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5489          440 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5490          440 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5491          440 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5492          440 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5493          440 :                 evictions_low_residence_duration_metric_threshold: Some(
    5494          440 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5495          440 :                 ),
    5496          440 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5497          440 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5498          440 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5499          440 :                 image_layer_creation_check_threshold: Some(
    5500          440 :                     tenant_conf.image_layer_creation_check_threshold,
    5501          440 :                 ),
    5502          440 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5503          440 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5504          440 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5505          440 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5506          440 :                 rel_size_v2_enabled: tenant_conf.rel_size_v2_enabled,
    5507          440 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5508          440 :                 gc_compaction_initial_threshold_kb: Some(
    5509          440 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5510          440 :                 ),
    5511          440 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5512          440 :             }
    5513          440 :         }
    5514              :     }
    5515              : 
    5516              :     pub struct TenantHarness {
    5517              :         pub conf: &'static PageServerConf,
    5518              :         pub tenant_conf: TenantConf,
    5519              :         pub tenant_shard_id: TenantShardId,
    5520              :         pub generation: Generation,
    5521              :         pub shard: ShardIndex,
    5522              :         pub remote_storage: GenericRemoteStorage,
    5523              :         pub remote_fs_dir: Utf8PathBuf,
    5524              :         pub deletion_queue: MockDeletionQueue,
    5525              :     }
    5526              : 
    5527              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5528              : 
    5529          488 :     pub(crate) fn setup_logging() {
    5530          488 :         LOG_HANDLE.get_or_init(|| {
    5531          464 :             logging::init(
    5532          464 :                 logging::LogFormat::Test,
    5533          464 :                 // enable it in case the tests exercise code paths that use
    5534          464 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5535          464 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5536          464 :                 logging::Output::Stdout,
    5537          464 :             )
    5538          464 :             .expect("Failed to init test logging")
    5539          488 :         });
    5540          488 :     }
    5541              : 
    5542              :     impl TenantHarness {
    5543          440 :         pub async fn create_custom(
    5544          440 :             test_name: &'static str,
    5545          440 :             tenant_conf: TenantConf,
    5546          440 :             tenant_id: TenantId,
    5547          440 :             shard_identity: ShardIdentity,
    5548          440 :             generation: Generation,
    5549          440 :         ) -> anyhow::Result<Self> {
    5550          440 :             setup_logging();
    5551          440 : 
    5552          440 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5553          440 :             let _ = fs::remove_dir_all(&repo_dir);
    5554          440 :             fs::create_dir_all(&repo_dir)?;
    5555              : 
    5556          440 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5557          440 :             // Make a static copy of the config. This can never be free'd, but that's
    5558          440 :             // OK in a test.
    5559          440 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5560          440 : 
    5561          440 :             let shard = shard_identity.shard_index();
    5562          440 :             let tenant_shard_id = TenantShardId {
    5563          440 :                 tenant_id,
    5564          440 :                 shard_number: shard.shard_number,
    5565          440 :                 shard_count: shard.shard_count,
    5566          440 :             };
    5567          440 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5568          440 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5569              : 
    5570              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5571          440 :             let remote_fs_dir = conf.workdir.join("localfs");
    5572          440 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5573          440 :             let config = RemoteStorageConfig {
    5574          440 :                 storage: RemoteStorageKind::LocalFs {
    5575          440 :                     local_path: remote_fs_dir.clone(),
    5576          440 :                 },
    5577          440 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5578          440 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5579          440 :             };
    5580          440 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5581          440 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5582          440 : 
    5583          440 :             Ok(Self {
    5584          440 :                 conf,
    5585          440 :                 tenant_conf,
    5586          440 :                 tenant_shard_id,
    5587          440 :                 generation,
    5588          440 :                 shard,
    5589          440 :                 remote_storage,
    5590          440 :                 remote_fs_dir,
    5591          440 :                 deletion_queue,
    5592          440 :             })
    5593          440 :         }
    5594              : 
    5595          416 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5596          416 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5597          416 :             // The tests perform them manually if needed.
    5598          416 :             let tenant_conf = TenantConf {
    5599          416 :                 gc_period: Duration::ZERO,
    5600          416 :                 compaction_period: Duration::ZERO,
    5601          416 :                 ..TenantConf::default()
    5602          416 :             };
    5603          416 :             let tenant_id = TenantId::generate();
    5604          416 :             let shard = ShardIdentity::unsharded();
    5605          416 :             Self::create_custom(
    5606          416 :                 test_name,
    5607          416 :                 tenant_conf,
    5608          416 :                 tenant_id,
    5609          416 :                 shard,
    5610          416 :                 Generation::new(0xdeadbeef),
    5611          416 :             )
    5612          416 :             .await
    5613          416 :         }
    5614              : 
    5615           40 :         pub fn span(&self) -> tracing::Span {
    5616           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5617           40 :         }
    5618              : 
    5619          440 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5620          440 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5621          440 :             (
    5622          440 :                 self.do_try_load(&ctx)
    5623          440 :                     .await
    5624          440 :                     .expect("failed to load test tenant"),
    5625          440 :                 ctx,
    5626          440 :             )
    5627          440 :         }
    5628              : 
    5629              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5630              :         pub(crate) async fn do_try_load(
    5631              :             &self,
    5632              :             ctx: &RequestContext,
    5633              :         ) -> anyhow::Result<Arc<Tenant>> {
    5634              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5635              : 
    5636              :             let tenant = Arc::new(Tenant::new(
    5637              :                 TenantState::Attaching,
    5638              :                 self.conf,
    5639              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5640              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5641              :                     self.generation,
    5642              :                     &ShardParameters::default(),
    5643              :                 ))
    5644              :                 .unwrap(),
    5645              :                 // This is a legacy/test code path: sharding isn't supported here.
    5646              :                 ShardIdentity::unsharded(),
    5647              :                 Some(walredo_mgr),
    5648              :                 self.tenant_shard_id,
    5649              :                 self.remote_storage.clone(),
    5650              :                 self.deletion_queue.new_client(),
    5651              :                 // TODO: ideally we should run all unit tests with both configs
    5652              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5653              :             ));
    5654              : 
    5655              :             let preload = tenant
    5656              :                 .preload(&self.remote_storage, CancellationToken::new())
    5657              :                 .await?;
    5658              :             tenant.attach(Some(preload), ctx).await?;
    5659              : 
    5660              :             tenant.state.send_replace(TenantState::Active);
    5661              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5662              :                 timeline.set_state(TimelineState::Active);
    5663              :             }
    5664              :             Ok(tenant)
    5665              :         }
    5666              : 
    5667            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5668            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5669            4 :         }
    5670              :     }
    5671              : 
    5672              :     // Mock WAL redo manager that doesn't do much
    5673              :     pub(crate) struct TestRedoManager;
    5674              : 
    5675              :     impl TestRedoManager {
    5676              :         /// # Cancel-Safety
    5677              :         ///
    5678              :         /// This method is cancellation-safe.
    5679         1636 :         pub async fn request_redo(
    5680         1636 :             &self,
    5681         1636 :             key: Key,
    5682         1636 :             lsn: Lsn,
    5683         1636 :             base_img: Option<(Lsn, Bytes)>,
    5684         1636 :             records: Vec<(Lsn, NeonWalRecord)>,
    5685         1636 :             _pg_version: u32,
    5686         1636 :         ) -> Result<Bytes, walredo::Error> {
    5687         2392 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5688         1636 :             if records_neon {
    5689              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5690         1636 :                 let mut page = match (base_img, records.first()) {
    5691         1504 :                     (Some((_lsn, img)), _) => {
    5692         1504 :                         let mut page = BytesMut::new();
    5693         1504 :                         page.extend_from_slice(&img);
    5694         1504 :                         page
    5695              :                     }
    5696          132 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5697              :                     _ => {
    5698            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5699              :                     }
    5700              :                 };
    5701              : 
    5702         4028 :                 for (record_lsn, record) in records {
    5703         2392 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5704              :                 }
    5705         1636 :                 Ok(page.freeze())
    5706              :             } else {
    5707              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5708            0 :                 let s = format!(
    5709            0 :                     "redo for {} to get to {}, with {} and {} records",
    5710            0 :                     key,
    5711            0 :                     lsn,
    5712            0 :                     if base_img.is_some() {
    5713            0 :                         "base image"
    5714              :                     } else {
    5715            0 :                         "no base image"
    5716              :                     },
    5717            0 :                     records.len()
    5718            0 :                 );
    5719            0 :                 println!("{s}");
    5720            0 : 
    5721            0 :                 Ok(test_img(&s))
    5722              :             }
    5723         1636 :         }
    5724              :     }
    5725              : }
    5726              : 
    5727              : #[cfg(test)]
    5728              : mod tests {
    5729              :     use std::collections::{BTreeMap, BTreeSet};
    5730              : 
    5731              :     use super::*;
    5732              :     use crate::keyspace::KeySpaceAccum;
    5733              :     use crate::tenant::harness::*;
    5734              :     use crate::tenant::timeline::CompactFlags;
    5735              :     use crate::DEFAULT_PG_VERSION;
    5736              :     use bytes::{Bytes, BytesMut};
    5737              :     use hex_literal::hex;
    5738              :     use itertools::Itertools;
    5739              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5740              :     use pageserver_api::keyspace::KeySpace;
    5741              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5742              :     use pageserver_api::value::Value;
    5743              :     use pageserver_compaction::helpers::overlaps_with;
    5744              :     use rand::{thread_rng, Rng};
    5745              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5746              :     use tests::storage_layer::ValuesReconstructState;
    5747              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5748              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5749              :     use utils::id::TenantId;
    5750              : 
    5751              :     #[cfg(feature = "testing")]
    5752              :     use models::CompactLsnRange;
    5753              :     #[cfg(feature = "testing")]
    5754              :     use pageserver_api::record::NeonWalRecord;
    5755              :     #[cfg(feature = "testing")]
    5756              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5757              :     #[cfg(feature = "testing")]
    5758              :     use timeline::GcInfo;
    5759              : 
    5760              :     static TEST_KEY: Lazy<Key> =
    5761           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5762              : 
    5763              :     #[tokio::test]
    5764            4 :     async fn test_basic() -> anyhow::Result<()> {
    5765            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5766            4 :         let tline = tenant
    5767            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5768            4 :             .await?;
    5769            4 : 
    5770            4 :         let mut writer = tline.writer().await;
    5771            4 :         writer
    5772            4 :             .put(
    5773            4 :                 *TEST_KEY,
    5774            4 :                 Lsn(0x10),
    5775            4 :                 &Value::Image(test_img("foo at 0x10")),
    5776            4 :                 &ctx,
    5777            4 :             )
    5778            4 :             .await?;
    5779            4 :         writer.finish_write(Lsn(0x10));
    5780            4 :         drop(writer);
    5781            4 : 
    5782            4 :         let mut writer = tline.writer().await;
    5783            4 :         writer
    5784            4 :             .put(
    5785            4 :                 *TEST_KEY,
    5786            4 :                 Lsn(0x20),
    5787            4 :                 &Value::Image(test_img("foo at 0x20")),
    5788            4 :                 &ctx,
    5789            4 :             )
    5790            4 :             .await?;
    5791            4 :         writer.finish_write(Lsn(0x20));
    5792            4 :         drop(writer);
    5793            4 : 
    5794            4 :         assert_eq!(
    5795            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5796            4 :             test_img("foo at 0x10")
    5797            4 :         );
    5798            4 :         assert_eq!(
    5799            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5800            4 :             test_img("foo at 0x10")
    5801            4 :         );
    5802            4 :         assert_eq!(
    5803            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5804            4 :             test_img("foo at 0x20")
    5805            4 :         );
    5806            4 : 
    5807            4 :         Ok(())
    5808            4 :     }
    5809              : 
    5810              :     #[tokio::test]
    5811            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5812            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5813            4 :             .await?
    5814            4 :             .load()
    5815            4 :             .await;
    5816            4 :         let _ = tenant
    5817            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5818            4 :             .await?;
    5819            4 : 
    5820            4 :         match tenant
    5821            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5822            4 :             .await
    5823            4 :         {
    5824            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5825            4 :             Err(e) => assert_eq!(
    5826            4 :                 e.to_string(),
    5827            4 :                 "timeline already exists with different parameters".to_string()
    5828            4 :             ),
    5829            4 :         }
    5830            4 : 
    5831            4 :         Ok(())
    5832            4 :     }
    5833              : 
    5834              :     /// Convenience function to create a page image with given string as the only content
    5835           20 :     pub fn test_value(s: &str) -> Value {
    5836           20 :         let mut buf = BytesMut::new();
    5837           20 :         buf.extend_from_slice(s.as_bytes());
    5838           20 :         Value::Image(buf.freeze())
    5839           20 :     }
    5840              : 
    5841              :     ///
    5842              :     /// Test branch creation
    5843              :     ///
    5844              :     #[tokio::test]
    5845            4 :     async fn test_branch() -> anyhow::Result<()> {
    5846            4 :         use std::str::from_utf8;
    5847            4 : 
    5848            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5849            4 :         let tline = tenant
    5850            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5851            4 :             .await?;
    5852            4 :         let mut writer = tline.writer().await;
    5853            4 : 
    5854            4 :         #[allow(non_snake_case)]
    5855            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5856            4 :         #[allow(non_snake_case)]
    5857            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5858            4 : 
    5859            4 :         // Insert a value on the timeline
    5860            4 :         writer
    5861            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5862            4 :             .await?;
    5863            4 :         writer
    5864            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5865            4 :             .await?;
    5866            4 :         writer.finish_write(Lsn(0x20));
    5867            4 : 
    5868            4 :         writer
    5869            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5870            4 :             .await?;
    5871            4 :         writer.finish_write(Lsn(0x30));
    5872            4 :         writer
    5873            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5874            4 :             .await?;
    5875            4 :         writer.finish_write(Lsn(0x40));
    5876            4 : 
    5877            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5878            4 : 
    5879            4 :         // Branch the history, modify relation differently on the new timeline
    5880            4 :         tenant
    5881            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5882            4 :             .await?;
    5883            4 :         let newtline = tenant
    5884            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    5885            4 :             .expect("Should have a local timeline");
    5886            4 :         let mut new_writer = newtline.writer().await;
    5887            4 :         new_writer
    5888            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5889            4 :             .await?;
    5890            4 :         new_writer.finish_write(Lsn(0x40));
    5891            4 : 
    5892            4 :         // Check page contents on both branches
    5893            4 :         assert_eq!(
    5894            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5895            4 :             "foo at 0x40"
    5896            4 :         );
    5897            4 :         assert_eq!(
    5898            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5899            4 :             "bar at 0x40"
    5900            4 :         );
    5901            4 :         assert_eq!(
    5902            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5903            4 :             "foobar at 0x20"
    5904            4 :         );
    5905            4 : 
    5906            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5907            4 : 
    5908            4 :         Ok(())
    5909            4 :     }
    5910              : 
    5911           40 :     async fn make_some_layers(
    5912           40 :         tline: &Timeline,
    5913           40 :         start_lsn: Lsn,
    5914           40 :         ctx: &RequestContext,
    5915           40 :     ) -> anyhow::Result<()> {
    5916           40 :         let mut lsn = start_lsn;
    5917              :         {
    5918           40 :             let mut writer = tline.writer().await;
    5919              :             // Create a relation on the timeline
    5920           40 :             writer
    5921           40 :                 .put(
    5922           40 :                     *TEST_KEY,
    5923           40 :                     lsn,
    5924           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5925           40 :                     ctx,
    5926           40 :                 )
    5927           40 :                 .await?;
    5928           40 :             writer.finish_write(lsn);
    5929           40 :             lsn += 0x10;
    5930           40 :             writer
    5931           40 :                 .put(
    5932           40 :                     *TEST_KEY,
    5933           40 :                     lsn,
    5934           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5935           40 :                     ctx,
    5936           40 :                 )
    5937           40 :                 .await?;
    5938           40 :             writer.finish_write(lsn);
    5939           40 :             lsn += 0x10;
    5940           40 :         }
    5941           40 :         tline.freeze_and_flush().await?;
    5942              :         {
    5943           40 :             let mut writer = tline.writer().await;
    5944           40 :             writer
    5945           40 :                 .put(
    5946           40 :                     *TEST_KEY,
    5947           40 :                     lsn,
    5948           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5949           40 :                     ctx,
    5950           40 :                 )
    5951           40 :                 .await?;
    5952           40 :             writer.finish_write(lsn);
    5953           40 :             lsn += 0x10;
    5954           40 :             writer
    5955           40 :                 .put(
    5956           40 :                     *TEST_KEY,
    5957           40 :                     lsn,
    5958           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5959           40 :                     ctx,
    5960           40 :                 )
    5961           40 :                 .await?;
    5962           40 :             writer.finish_write(lsn);
    5963           40 :         }
    5964           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5965           40 :     }
    5966              : 
    5967              :     #[tokio::test(start_paused = true)]
    5968            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5969            4 :         let (tenant, ctx) =
    5970            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5971            4 :                 .await?
    5972            4 :                 .load()
    5973            4 :                 .await;
    5974            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5975            4 :         // initial transition into AttachedSingle.
    5976            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5977            4 :         tokio::time::resume();
    5978            4 :         let tline = tenant
    5979            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5980            4 :             .await?;
    5981            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5982            4 : 
    5983            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5984            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5985            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5986            4 :         // below should fail.
    5987            4 :         tenant
    5988            4 :             .gc_iteration(
    5989            4 :                 Some(TIMELINE_ID),
    5990            4 :                 0x10,
    5991            4 :                 Duration::ZERO,
    5992            4 :                 &CancellationToken::new(),
    5993            4 :                 &ctx,
    5994            4 :             )
    5995            4 :             .await?;
    5996            4 : 
    5997            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5998            4 :         match tenant
    5999            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6000            4 :             .await
    6001            4 :         {
    6002            4 :             Ok(_) => panic!("branching should have failed"),
    6003            4 :             Err(err) => {
    6004            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6005            4 :                     panic!("wrong error type")
    6006            4 :                 };
    6007            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6008            4 :                 assert!(err
    6009            4 :                     .source()
    6010            4 :                     .unwrap()
    6011            4 :                     .to_string()
    6012            4 :                     .contains("we might've already garbage collected needed data"))
    6013            4 :             }
    6014            4 :         }
    6015            4 : 
    6016            4 :         Ok(())
    6017            4 :     }
    6018              : 
    6019              :     #[tokio::test]
    6020            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6021            4 :         let (tenant, ctx) =
    6022            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6023            4 :                 .await?
    6024            4 :                 .load()
    6025            4 :                 .await;
    6026            4 : 
    6027            4 :         let tline = tenant
    6028            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6029            4 :             .await?;
    6030            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6031            4 :         match tenant
    6032            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6033            4 :             .await
    6034            4 :         {
    6035            4 :             Ok(_) => panic!("branching should have failed"),
    6036            4 :             Err(err) => {
    6037            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6038            4 :                     panic!("wrong error type");
    6039            4 :                 };
    6040            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6041            4 :                 assert!(&err
    6042            4 :                     .source()
    6043            4 :                     .unwrap()
    6044            4 :                     .to_string()
    6045            4 :                     .contains("is earlier than latest GC cutoff"));
    6046            4 :             }
    6047            4 :         }
    6048            4 : 
    6049            4 :         Ok(())
    6050            4 :     }
    6051              : 
    6052              :     /*
    6053              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6054              :     // remove the old value, we'd need to work a little harder
    6055              :     #[tokio::test]
    6056              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6057              :         let repo =
    6058              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6059              :             .load();
    6060              : 
    6061              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6062              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6063              : 
    6064              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6065              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    6066              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    6067              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6068              :             Ok(_) => panic!("request for page should have failed"),
    6069              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6070              :         }
    6071              :         Ok(())
    6072              :     }
    6073              :      */
    6074              : 
    6075              :     #[tokio::test]
    6076            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6077            4 :         let (tenant, ctx) =
    6078            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6079            4 :                 .await?
    6080            4 :                 .load()
    6081            4 :                 .await;
    6082            4 :         let tline = tenant
    6083            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6084            4 :             .await?;
    6085            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6086            4 : 
    6087            4 :         tenant
    6088            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6089            4 :             .await?;
    6090            4 :         let newtline = tenant
    6091            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6092            4 :             .expect("Should have a local timeline");
    6093            4 : 
    6094            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6095            4 : 
    6096            4 :         tline.set_broken("test".to_owned());
    6097            4 : 
    6098            4 :         tenant
    6099            4 :             .gc_iteration(
    6100            4 :                 Some(TIMELINE_ID),
    6101            4 :                 0x10,
    6102            4 :                 Duration::ZERO,
    6103            4 :                 &CancellationToken::new(),
    6104            4 :                 &ctx,
    6105            4 :             )
    6106            4 :             .await?;
    6107            4 : 
    6108            4 :         // The branchpoints should contain all timelines, even ones marked
    6109            4 :         // as Broken.
    6110            4 :         {
    6111            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6112            4 :             assert_eq!(branchpoints.len(), 1);
    6113            4 :             assert_eq!(
    6114            4 :                 branchpoints[0],
    6115            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6116            4 :             );
    6117            4 :         }
    6118            4 : 
    6119            4 :         // You can read the key from the child branch even though the parent is
    6120            4 :         // Broken, as long as you don't need to access data from the parent.
    6121            4 :         assert_eq!(
    6122            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6123            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6124            4 :         );
    6125            4 : 
    6126            4 :         // This needs to traverse to the parent, and fails.
    6127            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6128            4 :         assert!(
    6129            4 :             err.to_string().starts_with(&format!(
    6130            4 :                 "bad state on timeline {}: Broken",
    6131            4 :                 tline.timeline_id
    6132            4 :             )),
    6133            4 :             "{err}"
    6134            4 :         );
    6135            4 : 
    6136            4 :         Ok(())
    6137            4 :     }
    6138              : 
    6139              :     #[tokio::test]
    6140            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6141            4 :         let (tenant, ctx) =
    6142            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6143            4 :                 .await?
    6144            4 :                 .load()
    6145            4 :                 .await;
    6146            4 :         let tline = tenant
    6147            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6148            4 :             .await?;
    6149            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6150            4 : 
    6151            4 :         tenant
    6152            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6153            4 :             .await?;
    6154            4 :         let newtline = tenant
    6155            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6156            4 :             .expect("Should have a local timeline");
    6157            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6158            4 :         tenant
    6159            4 :             .gc_iteration(
    6160            4 :                 Some(TIMELINE_ID),
    6161            4 :                 0x10,
    6162            4 :                 Duration::ZERO,
    6163            4 :                 &CancellationToken::new(),
    6164            4 :                 &ctx,
    6165            4 :             )
    6166            4 :             .await?;
    6167            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6168            4 : 
    6169            4 :         Ok(())
    6170            4 :     }
    6171              :     #[tokio::test]
    6172            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6173            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6174            4 :             .await?
    6175            4 :             .load()
    6176            4 :             .await;
    6177            4 :         let tline = tenant
    6178            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6179            4 :             .await?;
    6180            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6181            4 : 
    6182            4 :         tenant
    6183            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6184            4 :             .await?;
    6185            4 :         let newtline = tenant
    6186            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6187            4 :             .expect("Should have a local timeline");
    6188            4 : 
    6189            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6190            4 : 
    6191            4 :         // run gc on parent
    6192            4 :         tenant
    6193            4 :             .gc_iteration(
    6194            4 :                 Some(TIMELINE_ID),
    6195            4 :                 0x10,
    6196            4 :                 Duration::ZERO,
    6197            4 :                 &CancellationToken::new(),
    6198            4 :                 &ctx,
    6199            4 :             )
    6200            4 :             .await?;
    6201            4 : 
    6202            4 :         // Check that the data is still accessible on the branch.
    6203            4 :         assert_eq!(
    6204            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6205            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6206            4 :         );
    6207            4 : 
    6208            4 :         Ok(())
    6209            4 :     }
    6210              : 
    6211              :     #[tokio::test]
    6212            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6213            4 :         const TEST_NAME: &str = "timeline_load";
    6214            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6215            4 :         {
    6216            4 :             let (tenant, ctx) = harness.load().await;
    6217            4 :             let tline = tenant
    6218            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6219            4 :                 .await?;
    6220            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6221            4 :             // so that all uploads finish & we can call harness.load() below again
    6222            4 :             tenant
    6223            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6224            4 :                 .instrument(harness.span())
    6225            4 :                 .await
    6226            4 :                 .ok()
    6227            4 :                 .unwrap();
    6228            4 :         }
    6229            4 : 
    6230            4 :         let (tenant, _ctx) = harness.load().await;
    6231            4 :         tenant
    6232            4 :             .get_timeline(TIMELINE_ID, true)
    6233            4 :             .expect("cannot load timeline");
    6234            4 : 
    6235            4 :         Ok(())
    6236            4 :     }
    6237              : 
    6238              :     #[tokio::test]
    6239            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6240            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6241            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6242            4 :         // create two timelines
    6243            4 :         {
    6244            4 :             let (tenant, ctx) = harness.load().await;
    6245            4 :             let tline = tenant
    6246            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6247            4 :                 .await?;
    6248            4 : 
    6249            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6250            4 : 
    6251            4 :             let child_tline = tenant
    6252            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6253            4 :                 .await?;
    6254            4 :             child_tline.set_state(TimelineState::Active);
    6255            4 : 
    6256            4 :             let newtline = tenant
    6257            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6258            4 :                 .expect("Should have a local timeline");
    6259            4 : 
    6260            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6261            4 : 
    6262            4 :             // so that all uploads finish & we can call harness.load() below again
    6263            4 :             tenant
    6264            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6265            4 :                 .instrument(harness.span())
    6266            4 :                 .await
    6267            4 :                 .ok()
    6268            4 :                 .unwrap();
    6269            4 :         }
    6270            4 : 
    6271            4 :         // check that both of them are initially unloaded
    6272            4 :         let (tenant, _ctx) = harness.load().await;
    6273            4 : 
    6274            4 :         // check that both, child and ancestor are loaded
    6275            4 :         let _child_tline = tenant
    6276            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6277            4 :             .expect("cannot get child timeline loaded");
    6278            4 : 
    6279            4 :         let _ancestor_tline = tenant
    6280            4 :             .get_timeline(TIMELINE_ID, true)
    6281            4 :             .expect("cannot get ancestor timeline loaded");
    6282            4 : 
    6283            4 :         Ok(())
    6284            4 :     }
    6285              : 
    6286              :     #[tokio::test]
    6287            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6288            4 :         use storage_layer::AsLayerDesc;
    6289            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6290            4 :             .await?
    6291            4 :             .load()
    6292            4 :             .await;
    6293            4 :         let tline = tenant
    6294            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6295            4 :             .await?;
    6296            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6297            4 : 
    6298            4 :         let layer_map = tline.layers.read().await;
    6299            4 :         let level0_deltas = layer_map
    6300            4 :             .layer_map()?
    6301            4 :             .level0_deltas()
    6302            4 :             .iter()
    6303            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6304            4 :             .collect::<Vec<_>>();
    6305            4 : 
    6306            4 :         assert!(!level0_deltas.is_empty());
    6307            4 : 
    6308           12 :         for delta in level0_deltas {
    6309            4 :             // Ensure we are dumping a delta layer here
    6310            8 :             assert!(delta.layer_desc().is_delta);
    6311            8 :             delta.dump(true, &ctx).await.unwrap();
    6312            4 :         }
    6313            4 : 
    6314            4 :         Ok(())
    6315            4 :     }
    6316              : 
    6317              :     #[tokio::test]
    6318            4 :     async fn test_images() -> anyhow::Result<()> {
    6319            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6320            4 :         let tline = tenant
    6321            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6322            4 :             .await?;
    6323            4 : 
    6324            4 :         let mut writer = tline.writer().await;
    6325            4 :         writer
    6326            4 :             .put(
    6327            4 :                 *TEST_KEY,
    6328            4 :                 Lsn(0x10),
    6329            4 :                 &Value::Image(test_img("foo at 0x10")),
    6330            4 :                 &ctx,
    6331            4 :             )
    6332            4 :             .await?;
    6333            4 :         writer.finish_write(Lsn(0x10));
    6334            4 :         drop(writer);
    6335            4 : 
    6336            4 :         tline.freeze_and_flush().await?;
    6337            4 :         tline
    6338            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6339            4 :             .await?;
    6340            4 : 
    6341            4 :         let mut writer = tline.writer().await;
    6342            4 :         writer
    6343            4 :             .put(
    6344            4 :                 *TEST_KEY,
    6345            4 :                 Lsn(0x20),
    6346            4 :                 &Value::Image(test_img("foo at 0x20")),
    6347            4 :                 &ctx,
    6348            4 :             )
    6349            4 :             .await?;
    6350            4 :         writer.finish_write(Lsn(0x20));
    6351            4 :         drop(writer);
    6352            4 : 
    6353            4 :         tline.freeze_and_flush().await?;
    6354            4 :         tline
    6355            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6356            4 :             .await?;
    6357            4 : 
    6358            4 :         let mut writer = tline.writer().await;
    6359            4 :         writer
    6360            4 :             .put(
    6361            4 :                 *TEST_KEY,
    6362            4 :                 Lsn(0x30),
    6363            4 :                 &Value::Image(test_img("foo at 0x30")),
    6364            4 :                 &ctx,
    6365            4 :             )
    6366            4 :             .await?;
    6367            4 :         writer.finish_write(Lsn(0x30));
    6368            4 :         drop(writer);
    6369            4 : 
    6370            4 :         tline.freeze_and_flush().await?;
    6371            4 :         tline
    6372            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6373            4 :             .await?;
    6374            4 : 
    6375            4 :         let mut writer = tline.writer().await;
    6376            4 :         writer
    6377            4 :             .put(
    6378            4 :                 *TEST_KEY,
    6379            4 :                 Lsn(0x40),
    6380            4 :                 &Value::Image(test_img("foo at 0x40")),
    6381            4 :                 &ctx,
    6382            4 :             )
    6383            4 :             .await?;
    6384            4 :         writer.finish_write(Lsn(0x40));
    6385            4 :         drop(writer);
    6386            4 : 
    6387            4 :         tline.freeze_and_flush().await?;
    6388            4 :         tline
    6389            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6390            4 :             .await?;
    6391            4 : 
    6392            4 :         assert_eq!(
    6393            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6394            4 :             test_img("foo at 0x10")
    6395            4 :         );
    6396            4 :         assert_eq!(
    6397            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6398            4 :             test_img("foo at 0x10")
    6399            4 :         );
    6400            4 :         assert_eq!(
    6401            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6402            4 :             test_img("foo at 0x20")
    6403            4 :         );
    6404            4 :         assert_eq!(
    6405            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6406            4 :             test_img("foo at 0x30")
    6407            4 :         );
    6408            4 :         assert_eq!(
    6409            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6410            4 :             test_img("foo at 0x40")
    6411            4 :         );
    6412            4 : 
    6413            4 :         Ok(())
    6414            4 :     }
    6415              : 
    6416            8 :     async fn bulk_insert_compact_gc(
    6417            8 :         tenant: &Tenant,
    6418            8 :         timeline: &Arc<Timeline>,
    6419            8 :         ctx: &RequestContext,
    6420            8 :         lsn: Lsn,
    6421            8 :         repeat: usize,
    6422            8 :         key_count: usize,
    6423            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6424            8 :         let compact = true;
    6425            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6426            8 :     }
    6427              : 
    6428           16 :     async fn bulk_insert_maybe_compact_gc(
    6429           16 :         tenant: &Tenant,
    6430           16 :         timeline: &Arc<Timeline>,
    6431           16 :         ctx: &RequestContext,
    6432           16 :         mut lsn: Lsn,
    6433           16 :         repeat: usize,
    6434           16 :         key_count: usize,
    6435           16 :         compact: bool,
    6436           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6437           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6438           16 : 
    6439           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6440           16 :         let mut blknum = 0;
    6441           16 : 
    6442           16 :         // Enforce that key range is monotonously increasing
    6443           16 :         let mut keyspace = KeySpaceAccum::new();
    6444           16 : 
    6445           16 :         let cancel = CancellationToken::new();
    6446           16 : 
    6447           16 :         for _ in 0..repeat {
    6448          800 :             for _ in 0..key_count {
    6449      8000000 :                 test_key.field6 = blknum;
    6450      8000000 :                 let mut writer = timeline.writer().await;
    6451      8000000 :                 writer
    6452      8000000 :                     .put(
    6453      8000000 :                         test_key,
    6454      8000000 :                         lsn,
    6455      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6456      8000000 :                         ctx,
    6457      8000000 :                     )
    6458      8000000 :                     .await?;
    6459      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6460      8000000 :                 writer.finish_write(lsn);
    6461      8000000 :                 drop(writer);
    6462      8000000 : 
    6463      8000000 :                 keyspace.add_key(test_key);
    6464      8000000 : 
    6465      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6466      8000000 :                 blknum += 1;
    6467              :             }
    6468              : 
    6469          800 :             timeline.freeze_and_flush().await?;
    6470          800 :             if compact {
    6471              :                 // this requires timeline to be &Arc<Timeline>
    6472          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6473          400 :             }
    6474              : 
    6475              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6476              :             // originally was.
    6477          800 :             let res = tenant
    6478          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6479          800 :                 .await?;
    6480              : 
    6481          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6482              :         }
    6483              : 
    6484           16 :         Ok(inserted)
    6485           16 :     }
    6486              : 
    6487              :     //
    6488              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6489              :     // Repeat 50 times.
    6490              :     //
    6491              :     #[tokio::test]
    6492            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6493            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6494            4 :         let (tenant, ctx) = harness.load().await;
    6495            4 :         let tline = tenant
    6496            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6497            4 :             .await?;
    6498            4 : 
    6499            4 :         let lsn = Lsn(0x10);
    6500            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6501            4 : 
    6502            4 :         Ok(())
    6503            4 :     }
    6504              : 
    6505              :     // Test the vectored get real implementation against a simple sequential implementation.
    6506              :     //
    6507              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6508              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6509              :     // grow to the right on the X axis.
    6510              :     //                       [Delta]
    6511              :     //                 [Delta]
    6512              :     //           [Delta]
    6513              :     //    [Delta]
    6514              :     // ------------ Image ---------------
    6515              :     //
    6516              :     // After layer generation we pick the ranges to query as follows:
    6517              :     // 1. The beginning of each delta layer
    6518              :     // 2. At the seam between two adjacent delta layers
    6519              :     //
    6520              :     // There's one major downside to this test: delta layers only contains images,
    6521              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6522              :     #[tokio::test]
    6523            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6524            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6525            4 :         let (tenant, ctx) = harness.load().await;
    6526            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6527            4 :         let tline = tenant
    6528            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6529            4 :             .await?;
    6530            4 : 
    6531            4 :         let lsn = Lsn(0x10);
    6532            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6533            4 : 
    6534            4 :         let guard = tline.layers.read().await;
    6535            4 :         let lm = guard.layer_map()?;
    6536            4 : 
    6537            4 :         lm.dump(true, &ctx).await?;
    6538            4 : 
    6539            4 :         let mut reads = Vec::new();
    6540            4 :         let mut prev = None;
    6541           24 :         lm.iter_historic_layers().for_each(|desc| {
    6542           24 :             if !desc.is_delta() {
    6543            4 :                 prev = Some(desc.clone());
    6544            4 :                 return;
    6545           20 :             }
    6546           20 : 
    6547           20 :             let start = desc.key_range.start;
    6548           20 :             let end = desc
    6549           20 :                 .key_range
    6550           20 :                 .start
    6551           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6552           20 :             reads.push(KeySpace {
    6553           20 :                 ranges: vec![start..end],
    6554           20 :             });
    6555            4 : 
    6556           20 :             if let Some(prev) = &prev {
    6557           20 :                 if !prev.is_delta() {
    6558           20 :                     return;
    6559            4 :                 }
    6560            0 : 
    6561            0 :                 let first_range = Key {
    6562            0 :                     field6: prev.key_range.end.field6 - 4,
    6563            0 :                     ..prev.key_range.end
    6564            0 :                 }..prev.key_range.end;
    6565            0 : 
    6566            0 :                 let second_range = desc.key_range.start..Key {
    6567            0 :                     field6: desc.key_range.start.field6 + 4,
    6568            0 :                     ..desc.key_range.start
    6569            0 :                 };
    6570            0 : 
    6571            0 :                 reads.push(KeySpace {
    6572            0 :                     ranges: vec![first_range, second_range],
    6573            0 :                 });
    6574            4 :             };
    6575            4 : 
    6576            4 :             prev = Some(desc.clone());
    6577           24 :         });
    6578            4 : 
    6579            4 :         drop(guard);
    6580            4 : 
    6581            4 :         // Pick a big LSN such that we query over all the changes.
    6582            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6583            4 : 
    6584           24 :         for read in reads {
    6585           20 :             info!("Doing vectored read on {:?}", read);
    6586            4 : 
    6587           20 :             let vectored_res = tline
    6588           20 :                 .get_vectored_impl(
    6589           20 :                     read.clone(),
    6590           20 :                     reads_lsn,
    6591           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6592           20 :                     &ctx,
    6593           20 :                 )
    6594           20 :                 .await;
    6595            4 : 
    6596           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6597           20 :             let mut expect_missing = false;
    6598           20 :             let mut key = read.start().unwrap();
    6599          660 :             while key != read.end().unwrap() {
    6600          640 :                 if let Some(lsns) = inserted.get(&key) {
    6601          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6602          640 :                     match expected_lsn {
    6603          640 :                         Some(lsn) => {
    6604          640 :                             expected_lsns.insert(key, *lsn);
    6605          640 :                         }
    6606            4 :                         None => {
    6607            4 :                             expect_missing = true;
    6608            0 :                             break;
    6609            4 :                         }
    6610            4 :                     }
    6611            4 :                 } else {
    6612            4 :                     expect_missing = true;
    6613            0 :                     break;
    6614            4 :                 }
    6615            4 : 
    6616          640 :                 key = key.next();
    6617            4 :             }
    6618            4 : 
    6619           20 :             if expect_missing {
    6620            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6621            4 :             } else {
    6622          640 :                 for (key, image) in vectored_res? {
    6623          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6624          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6625          640 :                     assert_eq!(image?, expected_image);
    6626            4 :                 }
    6627            4 :             }
    6628            4 :         }
    6629            4 : 
    6630            4 :         Ok(())
    6631            4 :     }
    6632              : 
    6633              :     #[tokio::test]
    6634            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6635            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6636            4 : 
    6637            4 :         let (tenant, ctx) = harness.load().await;
    6638            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6639            4 :         let tline = tenant
    6640            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6641            4 :             .await?;
    6642            4 :         let tline = tline.raw_timeline().unwrap();
    6643            4 : 
    6644            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6645            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6646            4 :         modification.set_lsn(Lsn(0x1008))?;
    6647            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6648            4 :         modification.commit(&ctx).await?;
    6649            4 : 
    6650            4 :         let child_timeline_id = TimelineId::generate();
    6651            4 :         tenant
    6652            4 :             .branch_timeline_test(
    6653            4 :                 tline,
    6654            4 :                 child_timeline_id,
    6655            4 :                 Some(tline.get_last_record_lsn()),
    6656            4 :                 &ctx,
    6657            4 :             )
    6658            4 :             .await?;
    6659            4 : 
    6660            4 :         let child_timeline = tenant
    6661            4 :             .get_timeline(child_timeline_id, true)
    6662            4 :             .expect("Should have the branched timeline");
    6663            4 : 
    6664            4 :         let aux_keyspace = KeySpace {
    6665            4 :             ranges: vec![NON_INHERITED_RANGE],
    6666            4 :         };
    6667            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6668            4 : 
    6669            4 :         let vectored_res = child_timeline
    6670            4 :             .get_vectored_impl(
    6671            4 :                 aux_keyspace.clone(),
    6672            4 :                 read_lsn,
    6673            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6674            4 :                 &ctx,
    6675            4 :             )
    6676            4 :             .await;
    6677            4 : 
    6678            4 :         let images = vectored_res?;
    6679            4 :         assert!(images.is_empty());
    6680            4 :         Ok(())
    6681            4 :     }
    6682              : 
    6683              :     // Test that vectored get handles layer gaps correctly
    6684              :     // by advancing into the next ancestor timeline if required.
    6685              :     //
    6686              :     // The test generates timelines that look like the diagram below.
    6687              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6688              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6689              :     //
    6690              :     // ```
    6691              :     //-------------------------------+
    6692              :     //                          ...  |
    6693              :     //               [   L1   ]      |
    6694              :     //     [ / L1   ]                | Child Timeline
    6695              :     // ...                           |
    6696              :     // ------------------------------+
    6697              :     //     [ X L1   ]                | Parent Timeline
    6698              :     // ------------------------------+
    6699              :     // ```
    6700              :     #[tokio::test]
    6701            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6702            4 :         let tenant_conf = TenantConf {
    6703            4 :             // Make compaction deterministic
    6704            4 :             gc_period: Duration::ZERO,
    6705            4 :             compaction_period: Duration::ZERO,
    6706            4 :             // Encourage creation of L1 layers
    6707            4 :             checkpoint_distance: 16 * 1024,
    6708            4 :             compaction_target_size: 8 * 1024,
    6709            4 :             ..TenantConf::default()
    6710            4 :         };
    6711            4 : 
    6712            4 :         let harness = TenantHarness::create_custom(
    6713            4 :             "test_get_vectored_key_gap",
    6714            4 :             tenant_conf,
    6715            4 :             TenantId::generate(),
    6716            4 :             ShardIdentity::unsharded(),
    6717            4 :             Generation::new(0xdeadbeef),
    6718            4 :         )
    6719            4 :         .await?;
    6720            4 :         let (tenant, ctx) = harness.load().await;
    6721            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6722            4 : 
    6723            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6724            4 :         let gap_at_key = current_key.add(100);
    6725            4 :         let mut current_lsn = Lsn(0x10);
    6726            4 : 
    6727            4 :         const KEY_COUNT: usize = 10_000;
    6728            4 : 
    6729            4 :         let timeline_id = TimelineId::generate();
    6730            4 :         let current_timeline = tenant
    6731            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6732            4 :             .await?;
    6733            4 : 
    6734            4 :         current_lsn += 0x100;
    6735            4 : 
    6736            4 :         let mut writer = current_timeline.writer().await;
    6737            4 :         writer
    6738            4 :             .put(
    6739            4 :                 gap_at_key,
    6740            4 :                 current_lsn,
    6741            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6742            4 :                 &ctx,
    6743            4 :             )
    6744            4 :             .await?;
    6745            4 :         writer.finish_write(current_lsn);
    6746            4 :         drop(writer);
    6747            4 : 
    6748            4 :         let mut latest_lsns = HashMap::new();
    6749            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6750            4 : 
    6751            4 :         current_timeline.freeze_and_flush().await?;
    6752            4 : 
    6753            4 :         let child_timeline_id = TimelineId::generate();
    6754            4 : 
    6755            4 :         tenant
    6756            4 :             .branch_timeline_test(
    6757            4 :                 &current_timeline,
    6758            4 :                 child_timeline_id,
    6759            4 :                 Some(current_lsn),
    6760            4 :                 &ctx,
    6761            4 :             )
    6762            4 :             .await?;
    6763            4 :         let child_timeline = tenant
    6764            4 :             .get_timeline(child_timeline_id, true)
    6765            4 :             .expect("Should have the branched timeline");
    6766            4 : 
    6767        40004 :         for i in 0..KEY_COUNT {
    6768        40000 :             if current_key == gap_at_key {
    6769            4 :                 current_key = current_key.next();
    6770            4 :                 continue;
    6771        39996 :             }
    6772        39996 : 
    6773        39996 :             current_lsn += 0x10;
    6774            4 : 
    6775        39996 :             let mut writer = child_timeline.writer().await;
    6776        39996 :             writer
    6777        39996 :                 .put(
    6778        39996 :                     current_key,
    6779        39996 :                     current_lsn,
    6780        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6781        39996 :                     &ctx,
    6782        39996 :                 )
    6783        39996 :                 .await?;
    6784        39996 :             writer.finish_write(current_lsn);
    6785        39996 :             drop(writer);
    6786        39996 : 
    6787        39996 :             latest_lsns.insert(current_key, current_lsn);
    6788        39996 :             current_key = current_key.next();
    6789        39996 : 
    6790        39996 :             // Flush every now and then to encourage layer file creation.
    6791        39996 :             if i % 500 == 0 {
    6792           80 :                 child_timeline.freeze_and_flush().await?;
    6793        39916 :             }
    6794            4 :         }
    6795            4 : 
    6796            4 :         child_timeline.freeze_and_flush().await?;
    6797            4 :         let mut flags = EnumSet::new();
    6798            4 :         flags.insert(CompactFlags::ForceRepartition);
    6799            4 :         child_timeline
    6800            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    6801            4 :             .await?;
    6802            4 : 
    6803            4 :         let key_near_end = {
    6804            4 :             let mut tmp = current_key;
    6805            4 :             tmp.field6 -= 10;
    6806            4 :             tmp
    6807            4 :         };
    6808            4 : 
    6809            4 :         let key_near_gap = {
    6810            4 :             let mut tmp = gap_at_key;
    6811            4 :             tmp.field6 -= 10;
    6812            4 :             tmp
    6813            4 :         };
    6814            4 : 
    6815            4 :         let read = KeySpace {
    6816            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6817            4 :         };
    6818            4 :         let results = child_timeline
    6819            4 :             .get_vectored_impl(
    6820            4 :                 read.clone(),
    6821            4 :                 current_lsn,
    6822            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6823            4 :                 &ctx,
    6824            4 :             )
    6825            4 :             .await?;
    6826            4 : 
    6827           88 :         for (key, img_res) in results {
    6828           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6829           84 :             assert_eq!(img_res?, expected);
    6830            4 :         }
    6831            4 : 
    6832            4 :         Ok(())
    6833            4 :     }
    6834              : 
    6835              :     // Test that vectored get descends into ancestor timelines correctly and
    6836              :     // does not return an image that's newer than requested.
    6837              :     //
    6838              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6839              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6840              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6841              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6842              :     // order to avoid returning an image that's too new. The test below constructs such
    6843              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6844              :     // ```
    6845              :     //    LSN
    6846              :     //     ^
    6847              :     //     |
    6848              :     //     |
    6849              :     // 500 | --------------------------------------> branch point
    6850              :     // 400 |        X
    6851              :     // 300 |        X
    6852              :     // 200 | --------------------------------------> requested lsn
    6853              :     // 100 |        X
    6854              :     //     |---------------------------------------> Key
    6855              :     //              |
    6856              :     //              ------> requested key
    6857              :     //
    6858              :     // Legend:
    6859              :     // * X - page images
    6860              :     // ```
    6861              :     #[tokio::test]
    6862            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6863            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6864            4 :         let (tenant, ctx) = harness.load().await;
    6865            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6866            4 : 
    6867            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6868            4 :         let end_key = start_key.add(1000);
    6869            4 :         let child_gap_at_key = start_key.add(500);
    6870            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6871            4 : 
    6872            4 :         let mut current_lsn = Lsn(0x10);
    6873            4 : 
    6874            4 :         let timeline_id = TimelineId::generate();
    6875            4 :         let parent_timeline = tenant
    6876            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6877            4 :             .await?;
    6878            4 : 
    6879            4 :         current_lsn += 0x100;
    6880            4 : 
    6881           16 :         for _ in 0..3 {
    6882           12 :             let mut key = start_key;
    6883        12012 :             while key < end_key {
    6884        12000 :                 current_lsn += 0x10;
    6885        12000 : 
    6886        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6887            4 : 
    6888        12000 :                 let mut writer = parent_timeline.writer().await;
    6889        12000 :                 writer
    6890        12000 :                     .put(
    6891        12000 :                         key,
    6892        12000 :                         current_lsn,
    6893        12000 :                         &Value::Image(test_img(&image_value)),
    6894        12000 :                         &ctx,
    6895        12000 :                     )
    6896        12000 :                     .await?;
    6897        12000 :                 writer.finish_write(current_lsn);
    6898        12000 : 
    6899        12000 :                 if key == child_gap_at_key {
    6900           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6901        11988 :                 }
    6902            4 : 
    6903        12000 :                 key = key.next();
    6904            4 :             }
    6905            4 : 
    6906           12 :             parent_timeline.freeze_and_flush().await?;
    6907            4 :         }
    6908            4 : 
    6909            4 :         let child_timeline_id = TimelineId::generate();
    6910            4 : 
    6911            4 :         let child_timeline = tenant
    6912            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6913            4 :             .await?;
    6914            4 : 
    6915            4 :         let mut key = start_key;
    6916         4004 :         while key < end_key {
    6917         4000 :             if key == child_gap_at_key {
    6918            4 :                 key = key.next();
    6919            4 :                 continue;
    6920         3996 :             }
    6921         3996 : 
    6922         3996 :             current_lsn += 0x10;
    6923            4 : 
    6924         3996 :             let mut writer = child_timeline.writer().await;
    6925         3996 :             writer
    6926         3996 :                 .put(
    6927         3996 :                     key,
    6928         3996 :                     current_lsn,
    6929         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6930         3996 :                     &ctx,
    6931         3996 :                 )
    6932         3996 :                 .await?;
    6933         3996 :             writer.finish_write(current_lsn);
    6934         3996 : 
    6935         3996 :             key = key.next();
    6936            4 :         }
    6937            4 : 
    6938            4 :         child_timeline.freeze_and_flush().await?;
    6939            4 : 
    6940            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6941            4 :         let mut query_lsns = Vec::new();
    6942           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6943           72 :             for offset in lsn_offsets {
    6944           60 :                 query_lsns.push(Lsn(image_lsn
    6945           60 :                     .0
    6946           60 :                     .checked_add_signed(offset)
    6947           60 :                     .expect("Shouldn't overflow")));
    6948           60 :             }
    6949            4 :         }
    6950            4 : 
    6951           64 :         for query_lsn in query_lsns {
    6952           60 :             let results = child_timeline
    6953           60 :                 .get_vectored_impl(
    6954           60 :                     KeySpace {
    6955           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6956           60 :                     },
    6957           60 :                     query_lsn,
    6958           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6959           60 :                     &ctx,
    6960           60 :                 )
    6961           60 :                 .await;
    6962            4 : 
    6963           60 :             let expected_item = parent_gap_lsns
    6964           60 :                 .iter()
    6965           60 :                 .rev()
    6966          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6967           60 : 
    6968           60 :             info!(
    6969            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6970            4 :                 query_lsn, expected_item
    6971            4 :             );
    6972            4 : 
    6973           60 :             match expected_item {
    6974           52 :                 Some((_, img_value)) => {
    6975           52 :                     let key_results = results.expect("No vectored get error expected");
    6976           52 :                     let key_result = &key_results[&child_gap_at_key];
    6977           52 :                     let returned_img = key_result
    6978           52 :                         .as_ref()
    6979           52 :                         .expect("No page reconstruct error expected");
    6980           52 : 
    6981           52 :                     info!(
    6982            4 :                         "Vectored read at LSN {} returned image {}",
    6983            0 :                         query_lsn,
    6984            0 :                         std::str::from_utf8(returned_img)?
    6985            4 :                     );
    6986           52 :                     assert_eq!(*returned_img, test_img(img_value));
    6987            4 :                 }
    6988            4 :                 None => {
    6989            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6990            4 :                 }
    6991            4 :             }
    6992            4 :         }
    6993            4 : 
    6994            4 :         Ok(())
    6995            4 :     }
    6996              : 
    6997              :     #[tokio::test]
    6998            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    6999            4 :         let names_algorithms = [
    7000            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7001            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7002            4 :         ];
    7003           12 :         for (name, algorithm) in names_algorithms {
    7004            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7005            4 :         }
    7006            4 :         Ok(())
    7007            4 :     }
    7008              : 
    7009            8 :     async fn test_random_updates_algorithm(
    7010            8 :         name: &'static str,
    7011            8 :         compaction_algorithm: CompactionAlgorithm,
    7012            8 :     ) -> anyhow::Result<()> {
    7013            8 :         let mut harness = TenantHarness::create(name).await?;
    7014            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7015            8 :             kind: compaction_algorithm,
    7016            8 :         };
    7017            8 :         let (tenant, ctx) = harness.load().await;
    7018            8 :         let tline = tenant
    7019            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7020            8 :             .await?;
    7021              : 
    7022              :         const NUM_KEYS: usize = 1000;
    7023            8 :         let cancel = CancellationToken::new();
    7024            8 : 
    7025            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7026            8 :         let mut test_key_end = test_key;
    7027            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7028            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7029            8 : 
    7030            8 :         let mut keyspace = KeySpaceAccum::new();
    7031            8 : 
    7032            8 :         // Track when each page was last modified. Used to assert that
    7033            8 :         // a read sees the latest page version.
    7034            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7035            8 : 
    7036            8 :         let mut lsn = Lsn(0x10);
    7037              :         #[allow(clippy::needless_range_loop)]
    7038         8008 :         for blknum in 0..NUM_KEYS {
    7039         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7040         8000 :             test_key.field6 = blknum as u32;
    7041         8000 :             let mut writer = tline.writer().await;
    7042         8000 :             writer
    7043         8000 :                 .put(
    7044         8000 :                     test_key,
    7045         8000 :                     lsn,
    7046         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7047         8000 :                     &ctx,
    7048         8000 :                 )
    7049         8000 :                 .await?;
    7050         8000 :             writer.finish_write(lsn);
    7051         8000 :             updated[blknum] = lsn;
    7052         8000 :             drop(writer);
    7053         8000 : 
    7054         8000 :             keyspace.add_key(test_key);
    7055              :         }
    7056              : 
    7057          408 :         for _ in 0..50 {
    7058       400400 :             for _ in 0..NUM_KEYS {
    7059       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7060       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7061       400000 :                 test_key.field6 = blknum as u32;
    7062       400000 :                 let mut writer = tline.writer().await;
    7063       400000 :                 writer
    7064       400000 :                     .put(
    7065       400000 :                         test_key,
    7066       400000 :                         lsn,
    7067       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7068       400000 :                         &ctx,
    7069       400000 :                     )
    7070       400000 :                     .await?;
    7071       400000 :                 writer.finish_write(lsn);
    7072       400000 :                 drop(writer);
    7073       400000 :                 updated[blknum] = lsn;
    7074              :             }
    7075              : 
    7076              :             // Read all the blocks
    7077       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7078       400000 :                 test_key.field6 = blknum as u32;
    7079       400000 :                 assert_eq!(
    7080       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7081       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7082              :                 );
    7083              :             }
    7084              : 
    7085              :             // Perform a cycle of flush, and GC
    7086          400 :             tline.freeze_and_flush().await?;
    7087          400 :             tenant
    7088          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7089          400 :                 .await?;
    7090              :         }
    7091              : 
    7092            8 :         Ok(())
    7093            8 :     }
    7094              : 
    7095              :     #[tokio::test]
    7096            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7097            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7098            4 :             .await?
    7099            4 :             .load()
    7100            4 :             .await;
    7101            4 :         let mut tline = tenant
    7102            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7103            4 :             .await?;
    7104            4 : 
    7105            4 :         const NUM_KEYS: usize = 1000;
    7106            4 : 
    7107            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7108            4 : 
    7109            4 :         let mut keyspace = KeySpaceAccum::new();
    7110            4 : 
    7111            4 :         let cancel = CancellationToken::new();
    7112            4 : 
    7113            4 :         // Track when each page was last modified. Used to assert that
    7114            4 :         // a read sees the latest page version.
    7115            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7116            4 : 
    7117            4 :         let mut lsn = Lsn(0x10);
    7118            4 :         #[allow(clippy::needless_range_loop)]
    7119         4004 :         for blknum in 0..NUM_KEYS {
    7120         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7121         4000 :             test_key.field6 = blknum as u32;
    7122         4000 :             let mut writer = tline.writer().await;
    7123         4000 :             writer
    7124         4000 :                 .put(
    7125         4000 :                     test_key,
    7126         4000 :                     lsn,
    7127         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7128         4000 :                     &ctx,
    7129         4000 :                 )
    7130         4000 :                 .await?;
    7131         4000 :             writer.finish_write(lsn);
    7132         4000 :             updated[blknum] = lsn;
    7133         4000 :             drop(writer);
    7134         4000 : 
    7135         4000 :             keyspace.add_key(test_key);
    7136            4 :         }
    7137            4 : 
    7138          204 :         for _ in 0..50 {
    7139          200 :             let new_tline_id = TimelineId::generate();
    7140          200 :             tenant
    7141          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7142          200 :                 .await?;
    7143          200 :             tline = tenant
    7144          200 :                 .get_timeline(new_tline_id, true)
    7145          200 :                 .expect("Should have the branched timeline");
    7146            4 : 
    7147       200200 :             for _ in 0..NUM_KEYS {
    7148       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7149       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7150       200000 :                 test_key.field6 = blknum as u32;
    7151       200000 :                 let mut writer = tline.writer().await;
    7152       200000 :                 writer
    7153       200000 :                     .put(
    7154       200000 :                         test_key,
    7155       200000 :                         lsn,
    7156       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7157       200000 :                         &ctx,
    7158       200000 :                     )
    7159       200000 :                     .await?;
    7160       200000 :                 println!("updating {} at {}", blknum, lsn);
    7161       200000 :                 writer.finish_write(lsn);
    7162       200000 :                 drop(writer);
    7163       200000 :                 updated[blknum] = lsn;
    7164            4 :             }
    7165            4 : 
    7166            4 :             // Read all the blocks
    7167       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7168       200000 :                 test_key.field6 = blknum as u32;
    7169       200000 :                 assert_eq!(
    7170       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7171       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7172            4 :                 );
    7173            4 :             }
    7174            4 : 
    7175            4 :             // Perform a cycle of flush, compact, and GC
    7176          200 :             tline.freeze_and_flush().await?;
    7177          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7178          200 :             tenant
    7179          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7180          200 :                 .await?;
    7181            4 :         }
    7182            4 : 
    7183            4 :         Ok(())
    7184            4 :     }
    7185              : 
    7186              :     #[tokio::test]
    7187            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7188            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7189            4 :             .await?
    7190            4 :             .load()
    7191            4 :             .await;
    7192            4 :         let mut tline = tenant
    7193            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7194            4 :             .await?;
    7195            4 : 
    7196            4 :         const NUM_KEYS: usize = 100;
    7197            4 :         const NUM_TLINES: usize = 50;
    7198            4 : 
    7199            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7200            4 :         // Track page mutation lsns across different timelines.
    7201            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7202            4 : 
    7203            4 :         let mut lsn = Lsn(0x10);
    7204            4 : 
    7205            4 :         #[allow(clippy::needless_range_loop)]
    7206          204 :         for idx in 0..NUM_TLINES {
    7207          200 :             let new_tline_id = TimelineId::generate();
    7208          200 :             tenant
    7209          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7210          200 :                 .await?;
    7211          200 :             tline = tenant
    7212          200 :                 .get_timeline(new_tline_id, true)
    7213          200 :                 .expect("Should have the branched timeline");
    7214            4 : 
    7215        20200 :             for _ in 0..NUM_KEYS {
    7216        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7217        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7218        20000 :                 test_key.field6 = blknum as u32;
    7219        20000 :                 let mut writer = tline.writer().await;
    7220        20000 :                 writer
    7221        20000 :                     .put(
    7222        20000 :                         test_key,
    7223        20000 :                         lsn,
    7224        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7225        20000 :                         &ctx,
    7226        20000 :                     )
    7227        20000 :                     .await?;
    7228        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7229        20000 :                 writer.finish_write(lsn);
    7230        20000 :                 drop(writer);
    7231        20000 :                 updated[idx][blknum] = lsn;
    7232            4 :             }
    7233            4 :         }
    7234            4 : 
    7235            4 :         // Read pages from leaf timeline across all ancestors.
    7236          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7237        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7238            4 :                 // Skip empty mutations.
    7239        20000 :                 if lsn.0 == 0 {
    7240         7324 :                     continue;
    7241        12676 :                 }
    7242        12676 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7243        12676 :                 test_key.field6 = blknum as u32;
    7244        12676 :                 assert_eq!(
    7245        12676 :                     tline.get(test_key, *lsn, &ctx).await?,
    7246        12676 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7247            4 :                 );
    7248            4 :             }
    7249            4 :         }
    7250            4 :         Ok(())
    7251            4 :     }
    7252              : 
    7253              :     #[tokio::test]
    7254            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7255            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7256            4 :             .await?
    7257            4 :             .load()
    7258            4 :             .await;
    7259            4 : 
    7260            4 :         let initdb_lsn = Lsn(0x20);
    7261            4 :         let utline = tenant
    7262            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7263            4 :             .await?;
    7264            4 :         let tline = utline.raw_timeline().unwrap();
    7265            4 : 
    7266            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7267            4 :         tline.maybe_spawn_flush_loop();
    7268            4 : 
    7269            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7270            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7271            4 :         // Except if you `put` at `initdb_lsn`.
    7272            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7273            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7274            4 :         // Let's make sure the test timeline can handle that case.
    7275            4 :         {
    7276            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7277            4 :             assert_eq!(
    7278            4 :                 timeline::FlushLoopState::Running {
    7279            4 :                     expect_initdb_optimization: false,
    7280            4 :                     initdb_optimization_count: 0,
    7281            4 :                 },
    7282            4 :                 *state
    7283            4 :             );
    7284            4 :             *state = timeline::FlushLoopState::Running {
    7285            4 :                 expect_initdb_optimization: true,
    7286            4 :                 initdb_optimization_count: 0,
    7287            4 :             };
    7288            4 :         }
    7289            4 : 
    7290            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7291            4 :         // As explained above, the optimization requires some keys to be present.
    7292            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7293            4 :         // This is what `create_test_timeline` does, by the way.
    7294            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7295            4 :         modification
    7296            4 :             .init_empty_test_timeline()
    7297            4 :             .context("init_empty_test_timeline")?;
    7298            4 :         modification
    7299            4 :             .commit(&ctx)
    7300            4 :             .await
    7301            4 :             .context("commit init_empty_test_timeline modification")?;
    7302            4 : 
    7303            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7304            4 :         tline.freeze_and_flush().await?;
    7305            4 : 
    7306            4 :         // assert freeze_and_flush exercised the initdb optimization
    7307            4 :         {
    7308            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7309            4 :             let timeline::FlushLoopState::Running {
    7310            4 :                 expect_initdb_optimization,
    7311            4 :                 initdb_optimization_count,
    7312            4 :             } = *state
    7313            4 :             else {
    7314            4 :                 panic!("unexpected state: {:?}", *state);
    7315            4 :             };
    7316            4 :             assert!(expect_initdb_optimization);
    7317            4 :             assert!(initdb_optimization_count > 0);
    7318            4 :         }
    7319            4 :         Ok(())
    7320            4 :     }
    7321              : 
    7322              :     #[tokio::test]
    7323            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7324            4 :         let name = "test_create_guard_crash";
    7325            4 :         let harness = TenantHarness::create(name).await?;
    7326            4 :         {
    7327            4 :             let (tenant, ctx) = harness.load().await;
    7328            4 :             let tline = tenant
    7329            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7330            4 :                 .await?;
    7331            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7332            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7333            4 :             raw_tline
    7334            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7335            4 :                 .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
    7336            4 :                 .await;
    7337            4 :             std::mem::forget(tline);
    7338            4 :         }
    7339            4 : 
    7340            4 :         let (tenant, _) = harness.load().await;
    7341            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7342            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7343            4 :             Err(e) => {
    7344            4 :                 assert_eq!(
    7345            4 :                     e,
    7346            4 :                     GetTimelineError::NotFound {
    7347            4 :                         tenant_id: tenant.tenant_shard_id,
    7348            4 :                         timeline_id: TIMELINE_ID,
    7349            4 :                     }
    7350            4 :                 )
    7351            4 :             }
    7352            4 :         }
    7353            4 : 
    7354            4 :         assert!(!harness
    7355            4 :             .conf
    7356            4 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7357            4 :             .exists());
    7358            4 : 
    7359            4 :         Ok(())
    7360            4 :     }
    7361              : 
    7362              :     #[tokio::test]
    7363            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7364            4 :         let names_algorithms = [
    7365            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7366            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7367            4 :         ];
    7368           12 :         for (name, algorithm) in names_algorithms {
    7369            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7370            4 :         }
    7371            4 :         Ok(())
    7372            4 :     }
    7373              : 
    7374            8 :     async fn test_read_at_max_lsn_algorithm(
    7375            8 :         name: &'static str,
    7376            8 :         compaction_algorithm: CompactionAlgorithm,
    7377            8 :     ) -> anyhow::Result<()> {
    7378            8 :         let mut harness = TenantHarness::create(name).await?;
    7379            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7380            8 :             kind: compaction_algorithm,
    7381            8 :         };
    7382            8 :         let (tenant, ctx) = harness.load().await;
    7383            8 :         let tline = tenant
    7384            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7385            8 :             .await?;
    7386              : 
    7387            8 :         let lsn = Lsn(0x10);
    7388            8 :         let compact = false;
    7389            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7390              : 
    7391            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7392            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7393              : 
    7394            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7395            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7396              : 
    7397            8 :         Ok(())
    7398            8 :     }
    7399              : 
    7400              :     #[tokio::test]
    7401            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7402            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7403            4 :         let (tenant, ctx) = harness.load().await;
    7404            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7405            4 :         let tline = tenant
    7406            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7407            4 :             .await?;
    7408            4 : 
    7409            4 :         const NUM_KEYS: usize = 1000;
    7410            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7411            4 : 
    7412            4 :         let cancel = CancellationToken::new();
    7413            4 : 
    7414            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7415            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7416            4 :         let mut test_key = base_key;
    7417            4 : 
    7418            4 :         // Track when each page was last modified. Used to assert that
    7419            4 :         // a read sees the latest page version.
    7420            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7421            4 : 
    7422            4 :         let mut lsn = Lsn(0x10);
    7423            4 :         #[allow(clippy::needless_range_loop)]
    7424         4004 :         for blknum in 0..NUM_KEYS {
    7425         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7426         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7427         4000 :             let mut writer = tline.writer().await;
    7428         4000 :             writer
    7429         4000 :                 .put(
    7430         4000 :                     test_key,
    7431         4000 :                     lsn,
    7432         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7433         4000 :                     &ctx,
    7434         4000 :                 )
    7435         4000 :                 .await?;
    7436         4000 :             writer.finish_write(lsn);
    7437         4000 :             updated[blknum] = lsn;
    7438         4000 :             drop(writer);
    7439            4 :         }
    7440            4 : 
    7441            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7442            4 : 
    7443           48 :         for iter in 0..=10 {
    7444            4 :             // Read all the blocks
    7445        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7446        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7447        44000 :                 assert_eq!(
    7448        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7449        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7450            4 :                 );
    7451            4 :             }
    7452            4 : 
    7453           44 :             let mut cnt = 0;
    7454        44000 :             for (key, value) in tline
    7455           44 :                 .get_vectored_impl(
    7456           44 :                     keyspace.clone(),
    7457           44 :                     lsn,
    7458           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7459           44 :                     &ctx,
    7460           44 :                 )
    7461           44 :                 .await?
    7462            4 :             {
    7463        44000 :                 let blknum = key.field6 as usize;
    7464        44000 :                 let value = value?;
    7465        44000 :                 assert!(blknum % STEP == 0);
    7466        44000 :                 let blknum = blknum / STEP;
    7467        44000 :                 assert_eq!(
    7468        44000 :                     value,
    7469        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7470        44000 :                 );
    7471        44000 :                 cnt += 1;
    7472            4 :             }
    7473            4 : 
    7474           44 :             assert_eq!(cnt, NUM_KEYS);
    7475            4 : 
    7476        44044 :             for _ in 0..NUM_KEYS {
    7477        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7478        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7479        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7480        44000 :                 let mut writer = tline.writer().await;
    7481        44000 :                 writer
    7482        44000 :                     .put(
    7483        44000 :                         test_key,
    7484        44000 :                         lsn,
    7485        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7486        44000 :                         &ctx,
    7487        44000 :                     )
    7488        44000 :                     .await?;
    7489        44000 :                 writer.finish_write(lsn);
    7490        44000 :                 drop(writer);
    7491        44000 :                 updated[blknum] = lsn;
    7492            4 :             }
    7493            4 : 
    7494            4 :             // Perform two cycles of flush, compact, and GC
    7495          132 :             for round in 0..2 {
    7496           88 :                 tline.freeze_and_flush().await?;
    7497           88 :                 tline
    7498           88 :                     .compact(
    7499           88 :                         &cancel,
    7500           88 :                         if iter % 5 == 0 && round == 0 {
    7501           12 :                             let mut flags = EnumSet::new();
    7502           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7503           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7504           12 :                             flags
    7505            4 :                         } else {
    7506           76 :                             EnumSet::empty()
    7507            4 :                         },
    7508           88 :                         &ctx,
    7509           88 :                     )
    7510           88 :                     .await?;
    7511           88 :                 tenant
    7512           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7513           88 :                     .await?;
    7514            4 :             }
    7515            4 :         }
    7516            4 : 
    7517            4 :         Ok(())
    7518            4 :     }
    7519              : 
    7520              :     #[tokio::test]
    7521            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7522            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7523            4 :         let (tenant, ctx) = harness.load().await;
    7524            4 :         let tline = tenant
    7525            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7526            4 :             .await?;
    7527            4 : 
    7528            4 :         let cancel = CancellationToken::new();
    7529            4 : 
    7530            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7531            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7532            4 :         let test_key = base_key;
    7533            4 :         let mut lsn = Lsn(0x10);
    7534            4 : 
    7535           84 :         for _ in 0..20 {
    7536           80 :             lsn = Lsn(lsn.0 + 0x10);
    7537           80 :             let mut writer = tline.writer().await;
    7538           80 :             writer
    7539           80 :                 .put(
    7540           80 :                     test_key,
    7541           80 :                     lsn,
    7542           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7543           80 :                     &ctx,
    7544           80 :                 )
    7545           80 :                 .await?;
    7546           80 :             writer.finish_write(lsn);
    7547           80 :             drop(writer);
    7548           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7549            4 :         }
    7550            4 : 
    7551            4 :         let before_num_l0_delta_files =
    7552            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7553            4 : 
    7554            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7555            4 : 
    7556            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7557            4 : 
    7558            4 :         assert!(after_num_l0_delta_files < before_num_l0_delta_files, "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}");
    7559            4 : 
    7560            4 :         assert_eq!(
    7561            4 :             tline.get(test_key, lsn, &ctx).await?,
    7562            4 :             test_img(&format!("{} at {}", 0, lsn))
    7563            4 :         );
    7564            4 : 
    7565            4 :         Ok(())
    7566            4 :     }
    7567              : 
    7568              :     #[tokio::test]
    7569            4 :     async fn test_aux_file_e2e() {
    7570            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7571            4 : 
    7572            4 :         let (tenant, ctx) = harness.load().await;
    7573            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7574            4 : 
    7575            4 :         let mut lsn = Lsn(0x08);
    7576            4 : 
    7577            4 :         let tline: Arc<Timeline> = tenant
    7578            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7579            4 :             .await
    7580            4 :             .unwrap();
    7581            4 : 
    7582            4 :         {
    7583            4 :             lsn += 8;
    7584            4 :             let mut modification = tline.begin_modification(lsn);
    7585            4 :             modification
    7586            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7587            4 :                 .await
    7588            4 :                 .unwrap();
    7589            4 :             modification.commit(&ctx).await.unwrap();
    7590            4 :         }
    7591            4 : 
    7592            4 :         // we can read everything from the storage
    7593            4 :         let files = tline
    7594            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7595            4 :             .await
    7596            4 :             .unwrap();
    7597            4 :         assert_eq!(
    7598            4 :             files.get("pg_logical/mappings/test1"),
    7599            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7600            4 :         );
    7601            4 : 
    7602            4 :         {
    7603            4 :             lsn += 8;
    7604            4 :             let mut modification = tline.begin_modification(lsn);
    7605            4 :             modification
    7606            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7607            4 :                 .await
    7608            4 :                 .unwrap();
    7609            4 :             modification.commit(&ctx).await.unwrap();
    7610            4 :         }
    7611            4 : 
    7612            4 :         let files = tline
    7613            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7614            4 :             .await
    7615            4 :             .unwrap();
    7616            4 :         assert_eq!(
    7617            4 :             files.get("pg_logical/mappings/test2"),
    7618            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7619            4 :         );
    7620            4 : 
    7621            4 :         let child = tenant
    7622            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7623            4 :             .await
    7624            4 :             .unwrap();
    7625            4 : 
    7626            4 :         let files = child
    7627            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7628            4 :             .await
    7629            4 :             .unwrap();
    7630            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7631            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7632            4 :     }
    7633              : 
    7634              :     #[tokio::test]
    7635            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7636            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7637            4 :         let (tenant, ctx) = harness.load().await;
    7638            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7639            4 :         let tline = tenant
    7640            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7641            4 :             .await?;
    7642            4 : 
    7643            4 :         const NUM_KEYS: usize = 1000;
    7644            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7645            4 : 
    7646            4 :         let cancel = CancellationToken::new();
    7647            4 : 
    7648            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7649            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7650            4 :         let mut test_key = base_key;
    7651            4 :         let mut lsn = Lsn(0x10);
    7652            4 : 
    7653           16 :         async fn scan_with_statistics(
    7654           16 :             tline: &Timeline,
    7655           16 :             keyspace: &KeySpace,
    7656           16 :             lsn: Lsn,
    7657           16 :             ctx: &RequestContext,
    7658           16 :             io_concurrency: IoConcurrency,
    7659           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7660           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7661           16 :             let res = tline
    7662           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7663           16 :                 .await?;
    7664           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7665           16 :         }
    7666            4 : 
    7667            4 :         #[allow(clippy::needless_range_loop)]
    7668         4004 :         for blknum in 0..NUM_KEYS {
    7669         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7670         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7671         4000 :             let mut writer = tline.writer().await;
    7672         4000 :             writer
    7673         4000 :                 .put(
    7674         4000 :                     test_key,
    7675         4000 :                     lsn,
    7676         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7677         4000 :                     &ctx,
    7678         4000 :                 )
    7679         4000 :                 .await?;
    7680         4000 :             writer.finish_write(lsn);
    7681         4000 :             drop(writer);
    7682            4 :         }
    7683            4 : 
    7684            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7685            4 : 
    7686           44 :         for iter in 1..=10 {
    7687        40040 :             for _ in 0..NUM_KEYS {
    7688        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7689        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7690        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7691        40000 :                 let mut writer = tline.writer().await;
    7692        40000 :                 writer
    7693        40000 :                     .put(
    7694        40000 :                         test_key,
    7695        40000 :                         lsn,
    7696        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7697        40000 :                         &ctx,
    7698        40000 :                     )
    7699        40000 :                     .await?;
    7700        40000 :                 writer.finish_write(lsn);
    7701        40000 :                 drop(writer);
    7702            4 :             }
    7703            4 : 
    7704           40 :             tline.freeze_and_flush().await?;
    7705            4 : 
    7706           40 :             if iter % 5 == 0 {
    7707            8 :                 let (_, before_delta_file_accessed) =
    7708            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7709            8 :                         .await?;
    7710            8 :                 tline
    7711            8 :                     .compact(
    7712            8 :                         &cancel,
    7713            8 :                         {
    7714            8 :                             let mut flags = EnumSet::new();
    7715            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7716            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7717            8 :                             flags
    7718            8 :                         },
    7719            8 :                         &ctx,
    7720            8 :                     )
    7721            8 :                     .await?;
    7722            8 :                 let (_, after_delta_file_accessed) =
    7723            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7724            8 :                         .await?;
    7725            8 :                 assert!(after_delta_file_accessed < before_delta_file_accessed, "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}");
    7726            4 :                 // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
    7727            8 :                 assert!(
    7728            8 :                     after_delta_file_accessed <= 2,
    7729            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7730            4 :                 );
    7731           32 :             }
    7732            4 :         }
    7733            4 : 
    7734            4 :         Ok(())
    7735            4 :     }
    7736              : 
    7737              :     #[tokio::test]
    7738            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7739            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7740            4 :         let (tenant, ctx) = harness.load().await;
    7741            4 : 
    7742            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7743            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7744            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7745            4 : 
    7746            4 :         let tline = tenant
    7747            4 :             .create_test_timeline_with_layers(
    7748            4 :                 TIMELINE_ID,
    7749            4 :                 Lsn(0x10),
    7750            4 :                 DEFAULT_PG_VERSION,
    7751            4 :                 &ctx,
    7752            4 :                 Vec::new(), // delta layers
    7753            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7754            4 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7755            4 :             )
    7756            4 :             .await?;
    7757            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7758            4 : 
    7759            4 :         let child = tenant
    7760            4 :             .branch_timeline_test_with_layers(
    7761            4 :                 &tline,
    7762            4 :                 NEW_TIMELINE_ID,
    7763            4 :                 Some(Lsn(0x20)),
    7764            4 :                 &ctx,
    7765            4 :                 Vec::new(), // delta layers
    7766            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7767            4 :                 Lsn(0x30),
    7768            4 :             )
    7769            4 :             .await
    7770            4 :             .unwrap();
    7771            4 : 
    7772            4 :         let lsn = Lsn(0x30);
    7773            4 : 
    7774            4 :         // test vectored get on parent timeline
    7775            4 :         assert_eq!(
    7776            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7777            4 :             Some(test_img("data key 1"))
    7778            4 :         );
    7779            4 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7780            4 :             .await
    7781            4 :             .unwrap_err()
    7782            4 :             .is_missing_key_error());
    7783            4 :         assert!(
    7784            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7785            4 :                 .await
    7786            4 :                 .unwrap_err()
    7787            4 :                 .is_missing_key_error()
    7788            4 :         );
    7789            4 : 
    7790            4 :         // test vectored get on child timeline
    7791            4 :         assert_eq!(
    7792            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7793            4 :             Some(test_img("data key 1"))
    7794            4 :         );
    7795            4 :         assert_eq!(
    7796            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7797            4 :             Some(test_img("data key 2"))
    7798            4 :         );
    7799            4 :         assert!(
    7800            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7801            4 :                 .await
    7802            4 :                 .unwrap_err()
    7803            4 :                 .is_missing_key_error()
    7804            4 :         );
    7805            4 : 
    7806            4 :         Ok(())
    7807            4 :     }
    7808              : 
    7809              :     #[tokio::test]
    7810            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7811            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7812            4 :         let (tenant, ctx) = harness.load().await;
    7813            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7814            4 : 
    7815            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7816            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7817            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7818            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7819            4 : 
    7820            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    7821            4 :         let base_inherited_key_child =
    7822            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    7823            4 :         let base_inherited_key_nonexist =
    7824            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    7825            4 :         let base_inherited_key_overwrite =
    7826            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    7827            4 : 
    7828            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7829            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    7830            4 : 
    7831            4 :         let tline = tenant
    7832            4 :             .create_test_timeline_with_layers(
    7833            4 :                 TIMELINE_ID,
    7834            4 :                 Lsn(0x10),
    7835            4 :                 DEFAULT_PG_VERSION,
    7836            4 :                 &ctx,
    7837            4 :                 Vec::new(), // delta layers
    7838            4 :                 vec![(
    7839            4 :                     Lsn(0x20),
    7840            4 :                     vec![
    7841            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    7842            4 :                         (
    7843            4 :                             base_inherited_key_overwrite,
    7844            4 :                             test_img("metadata key overwrite 1a"),
    7845            4 :                         ),
    7846            4 :                         (base_key, test_img("metadata key 1")),
    7847            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7848            4 :                     ],
    7849            4 :                 )], // image layers
    7850            4 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7851            4 :             )
    7852            4 :             .await?;
    7853            4 : 
    7854            4 :         let child = tenant
    7855            4 :             .branch_timeline_test_with_layers(
    7856            4 :                 &tline,
    7857            4 :                 NEW_TIMELINE_ID,
    7858            4 :                 Some(Lsn(0x20)),
    7859            4 :                 &ctx,
    7860            4 :                 Vec::new(), // delta layers
    7861            4 :                 vec![(
    7862            4 :                     Lsn(0x30),
    7863            4 :                     vec![
    7864            4 :                         (
    7865            4 :                             base_inherited_key_child,
    7866            4 :                             test_img("metadata inherited key 2"),
    7867            4 :                         ),
    7868            4 :                         (
    7869            4 :                             base_inherited_key_overwrite,
    7870            4 :                             test_img("metadata key overwrite 2a"),
    7871            4 :                         ),
    7872            4 :                         (base_key_child, test_img("metadata key 2")),
    7873            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    7874            4 :                     ],
    7875            4 :                 )], // image layers
    7876            4 :                 Lsn(0x30),
    7877            4 :             )
    7878            4 :             .await
    7879            4 :             .unwrap();
    7880            4 : 
    7881            4 :         let lsn = Lsn(0x30);
    7882            4 : 
    7883            4 :         // test vectored get on parent timeline
    7884            4 :         assert_eq!(
    7885            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7886            4 :             Some(test_img("metadata key 1"))
    7887            4 :         );
    7888            4 :         assert_eq!(
    7889            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7890            4 :             None
    7891            4 :         );
    7892            4 :         assert_eq!(
    7893            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7894            4 :             None
    7895            4 :         );
    7896            4 :         assert_eq!(
    7897            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    7898            4 :             Some(test_img("metadata key overwrite 1b"))
    7899            4 :         );
    7900            4 :         assert_eq!(
    7901            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    7902            4 :             Some(test_img("metadata inherited key 1"))
    7903            4 :         );
    7904            4 :         assert_eq!(
    7905            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    7906            4 :             None
    7907            4 :         );
    7908            4 :         assert_eq!(
    7909            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    7910            4 :             None
    7911            4 :         );
    7912            4 :         assert_eq!(
    7913            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    7914            4 :             Some(test_img("metadata key overwrite 1a"))
    7915            4 :         );
    7916            4 : 
    7917            4 :         // test vectored get on child timeline
    7918            4 :         assert_eq!(
    7919            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7920            4 :             None
    7921            4 :         );
    7922            4 :         assert_eq!(
    7923            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7924            4 :             Some(test_img("metadata key 2"))
    7925            4 :         );
    7926            4 :         assert_eq!(
    7927            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7928            4 :             None
    7929            4 :         );
    7930            4 :         assert_eq!(
    7931            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    7932            4 :             Some(test_img("metadata inherited key 1"))
    7933            4 :         );
    7934            4 :         assert_eq!(
    7935            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    7936            4 :             Some(test_img("metadata inherited key 2"))
    7937            4 :         );
    7938            4 :         assert_eq!(
    7939            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    7940            4 :             None
    7941            4 :         );
    7942            4 :         assert_eq!(
    7943            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    7944            4 :             Some(test_img("metadata key overwrite 2b"))
    7945            4 :         );
    7946            4 :         assert_eq!(
    7947            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    7948            4 :             Some(test_img("metadata key overwrite 2a"))
    7949            4 :         );
    7950            4 : 
    7951            4 :         // test vectored scan on parent timeline
    7952            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    7953            4 :         let res = tline
    7954            4 :             .get_vectored_impl(
    7955            4 :                 KeySpace::single(Key::metadata_key_range()),
    7956            4 :                 lsn,
    7957            4 :                 &mut reconstruct_state,
    7958            4 :                 &ctx,
    7959            4 :             )
    7960            4 :             .await?;
    7961            4 : 
    7962            4 :         assert_eq!(
    7963            4 :             res.into_iter()
    7964           16 :                 .map(|(k, v)| (k, v.unwrap()))
    7965            4 :                 .collect::<Vec<_>>(),
    7966            4 :             vec![
    7967            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    7968            4 :                 (
    7969            4 :                     base_inherited_key_overwrite,
    7970            4 :                     test_img("metadata key overwrite 1a")
    7971            4 :                 ),
    7972            4 :                 (base_key, test_img("metadata key 1")),
    7973            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    7974            4 :             ]
    7975            4 :         );
    7976            4 : 
    7977            4 :         // test vectored scan on child timeline
    7978            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    7979            4 :         let res = child
    7980            4 :             .get_vectored_impl(
    7981            4 :                 KeySpace::single(Key::metadata_key_range()),
    7982            4 :                 lsn,
    7983            4 :                 &mut reconstruct_state,
    7984            4 :                 &ctx,
    7985            4 :             )
    7986            4 :             .await?;
    7987            4 : 
    7988            4 :         assert_eq!(
    7989            4 :             res.into_iter()
    7990           20 :                 .map(|(k, v)| (k, v.unwrap()))
    7991            4 :                 .collect::<Vec<_>>(),
    7992            4 :             vec![
    7993            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    7994            4 :                 (
    7995            4 :                     base_inherited_key_child,
    7996            4 :                     test_img("metadata inherited key 2")
    7997            4 :                 ),
    7998            4 :                 (
    7999            4 :                     base_inherited_key_overwrite,
    8000            4 :                     test_img("metadata key overwrite 2a")
    8001            4 :                 ),
    8002            4 :                 (base_key_child, test_img("metadata key 2")),
    8003            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8004            4 :             ]
    8005            4 :         );
    8006            4 : 
    8007            4 :         Ok(())
    8008            4 :     }
    8009              : 
    8010          112 :     async fn get_vectored_impl_wrapper(
    8011          112 :         tline: &Arc<Timeline>,
    8012          112 :         key: Key,
    8013          112 :         lsn: Lsn,
    8014          112 :         ctx: &RequestContext,
    8015          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8016          112 :         let io_concurrency =
    8017          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8018          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8019          112 :         let mut res = tline
    8020          112 :             .get_vectored_impl(
    8021          112 :                 KeySpace::single(key..key.next()),
    8022          112 :                 lsn,
    8023          112 :                 &mut reconstruct_state,
    8024          112 :                 ctx,
    8025          112 :             )
    8026          112 :             .await?;
    8027          100 :         Ok(res.pop_last().map(|(k, v)| {
    8028           64 :             assert_eq!(k, key);
    8029           64 :             v.unwrap()
    8030          100 :         }))
    8031          112 :     }
    8032              : 
    8033              :     #[tokio::test]
    8034            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8035            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8036            4 :         let (tenant, ctx) = harness.load().await;
    8037            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8038            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8039            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8040            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8041            4 : 
    8042            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8043            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8044            4 :         // Lsn 0x20 key1+key2 tomestones
    8045            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8046            4 :         let tline = tenant
    8047            4 :             .create_test_timeline_with_layers(
    8048            4 :                 TIMELINE_ID,
    8049            4 :                 Lsn(0x10),
    8050            4 :                 DEFAULT_PG_VERSION,
    8051            4 :                 &ctx,
    8052            4 :                 // delta layers
    8053            4 :                 vec![
    8054            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8055            4 :                         Lsn(0x10)..Lsn(0x20),
    8056            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8057            4 :                     ),
    8058            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8059            4 :                         Lsn(0x20)..Lsn(0x30),
    8060            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8061            4 :                     ),
    8062            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8063            4 :                         Lsn(0x20)..Lsn(0x30),
    8064            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8065            4 :                     ),
    8066            4 :                 ],
    8067            4 :                 // image layers
    8068            4 :                 vec![
    8069            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8070            4 :                     (
    8071            4 :                         Lsn(0x30),
    8072            4 :                         vec![
    8073            4 :                             (key0, test_img("metadata key 0")),
    8074            4 :                             (key3, test_img("metadata key 3")),
    8075            4 :                         ],
    8076            4 :                     ),
    8077            4 :                 ],
    8078            4 :                 Lsn(0x30),
    8079            4 :             )
    8080            4 :             .await?;
    8081            4 : 
    8082            4 :         let lsn = Lsn(0x30);
    8083            4 :         let old_lsn = Lsn(0x20);
    8084            4 : 
    8085            4 :         assert_eq!(
    8086            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8087            4 :             Some(test_img("metadata key 0"))
    8088            4 :         );
    8089            4 :         assert_eq!(
    8090            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8091            4 :             None,
    8092            4 :         );
    8093            4 :         assert_eq!(
    8094            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8095            4 :             None,
    8096            4 :         );
    8097            4 :         assert_eq!(
    8098            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8099            4 :             Some(Bytes::new()),
    8100            4 :         );
    8101            4 :         assert_eq!(
    8102            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8103            4 :             Some(Bytes::new()),
    8104            4 :         );
    8105            4 :         assert_eq!(
    8106            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8107            4 :             Some(test_img("metadata key 3"))
    8108            4 :         );
    8109            4 : 
    8110            4 :         Ok(())
    8111            4 :     }
    8112              : 
    8113              :     #[tokio::test]
    8114            4 :     async fn test_metadata_tombstone_image_creation() {
    8115            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8116            4 :             .await
    8117            4 :             .unwrap();
    8118            4 :         let (tenant, ctx) = harness.load().await;
    8119            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8120            4 : 
    8121            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8122            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8123            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8124            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8125            4 : 
    8126            4 :         let tline = tenant
    8127            4 :             .create_test_timeline_with_layers(
    8128            4 :                 TIMELINE_ID,
    8129            4 :                 Lsn(0x10),
    8130            4 :                 DEFAULT_PG_VERSION,
    8131            4 :                 &ctx,
    8132            4 :                 // delta layers
    8133            4 :                 vec![
    8134            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8135            4 :                         Lsn(0x10)..Lsn(0x20),
    8136            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8137            4 :                     ),
    8138            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8139            4 :                         Lsn(0x20)..Lsn(0x30),
    8140            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8141            4 :                     ),
    8142            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8143            4 :                         Lsn(0x20)..Lsn(0x30),
    8144            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8145            4 :                     ),
    8146            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8147            4 :                         Lsn(0x30)..Lsn(0x40),
    8148            4 :                         vec![
    8149            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8150            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8151            4 :                         ],
    8152            4 :                     ),
    8153            4 :                 ],
    8154            4 :                 // image layers
    8155            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8156            4 :                 Lsn(0x40),
    8157            4 :             )
    8158            4 :             .await
    8159            4 :             .unwrap();
    8160            4 : 
    8161            4 :         let cancel = CancellationToken::new();
    8162            4 : 
    8163            4 :         tline
    8164            4 :             .compact(
    8165            4 :                 &cancel,
    8166            4 :                 {
    8167            4 :                     let mut flags = EnumSet::new();
    8168            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8169            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8170            4 :                     flags
    8171            4 :                 },
    8172            4 :                 &ctx,
    8173            4 :             )
    8174            4 :             .await
    8175            4 :             .unwrap();
    8176            4 : 
    8177            4 :         // Image layers are created at last_record_lsn
    8178            4 :         let images = tline
    8179            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8180            4 :             .await
    8181            4 :             .unwrap()
    8182            4 :             .into_iter()
    8183           36 :             .filter(|(k, _)| k.is_metadata_key())
    8184            4 :             .collect::<Vec<_>>();
    8185            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8186            4 :     }
    8187              : 
    8188              :     #[tokio::test]
    8189            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8190            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8191            4 :             .await
    8192            4 :             .unwrap();
    8193            4 :         let (tenant, ctx) = harness.load().await;
    8194            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8195            4 : 
    8196            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8197            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8198            4 : 
    8199            4 :         let tline = tenant
    8200            4 :             .create_test_timeline_with_layers(
    8201            4 :                 TIMELINE_ID,
    8202            4 :                 Lsn(0x10),
    8203            4 :                 DEFAULT_PG_VERSION,
    8204            4 :                 &ctx,
    8205            4 :                 // delta layers
    8206            4 :                 vec![
    8207            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8208            4 :                         Lsn(0x10)..Lsn(0x20),
    8209            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8210            4 :                     ),
    8211            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8212            4 :                         Lsn(0x20)..Lsn(0x30),
    8213            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8214            4 :                     ),
    8215            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8216            4 :                         Lsn(0x20)..Lsn(0x30),
    8217            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8218            4 :                     ),
    8219            4 :                 ],
    8220            4 :                 // image layers
    8221            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8222            4 :                 Lsn(0x30),
    8223            4 :             )
    8224            4 :             .await
    8225            4 :             .unwrap();
    8226            4 : 
    8227            4 :         let cancel = CancellationToken::new();
    8228            4 : 
    8229            4 :         tline
    8230            4 :             .compact(
    8231            4 :                 &cancel,
    8232            4 :                 {
    8233            4 :                     let mut flags = EnumSet::new();
    8234            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8235            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8236            4 :                     flags
    8237            4 :                 },
    8238            4 :                 &ctx,
    8239            4 :             )
    8240            4 :             .await
    8241            4 :             .unwrap();
    8242            4 : 
    8243            4 :         // Image layers are created at last_record_lsn
    8244            4 :         let images = tline
    8245            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8246            4 :             .await
    8247            4 :             .unwrap()
    8248            4 :             .into_iter()
    8249           28 :             .filter(|(k, _)| k.is_metadata_key())
    8250            4 :             .collect::<Vec<_>>();
    8251            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8252            4 :     }
    8253              : 
    8254              :     #[tokio::test]
    8255            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8256            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8257            4 :         let (tenant, ctx) = harness.load().await;
    8258            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8259            4 : 
    8260          204 :         fn get_key(id: u32) -> Key {
    8261          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8262          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8263          204 :             key.field6 = id;
    8264          204 :             key
    8265          204 :         }
    8266            4 : 
    8267            4 :         // We create
    8268            4 :         // - one bottom-most image layer,
    8269            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8270            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8271            4 :         // - a delta layer D3 above the horizon.
    8272            4 :         //
    8273            4 :         //                             | D3 |
    8274            4 :         //  | D1 |
    8275            4 :         // -|    |-- gc horizon -----------------
    8276            4 :         //  |    |                | D2 |
    8277            4 :         // --------- img layer ------------------
    8278            4 :         //
    8279            4 :         // What we should expact from this compaction is:
    8280            4 :         //                             | D3 |
    8281            4 :         //  | Part of D1 |
    8282            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8283            4 : 
    8284            4 :         // img layer at 0x10
    8285            4 :         let img_layer = (0..10)
    8286           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8287            4 :             .collect_vec();
    8288            4 : 
    8289            4 :         let delta1 = vec![
    8290            4 :             (
    8291            4 :                 get_key(1),
    8292            4 :                 Lsn(0x20),
    8293            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8294            4 :             ),
    8295            4 :             (
    8296            4 :                 get_key(2),
    8297            4 :                 Lsn(0x30),
    8298            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8299            4 :             ),
    8300            4 :             (
    8301            4 :                 get_key(3),
    8302            4 :                 Lsn(0x40),
    8303            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8304            4 :             ),
    8305            4 :         ];
    8306            4 :         let delta2 = vec![
    8307            4 :             (
    8308            4 :                 get_key(5),
    8309            4 :                 Lsn(0x20),
    8310            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8311            4 :             ),
    8312            4 :             (
    8313            4 :                 get_key(6),
    8314            4 :                 Lsn(0x20),
    8315            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8316            4 :             ),
    8317            4 :         ];
    8318            4 :         let delta3 = vec![
    8319            4 :             (
    8320            4 :                 get_key(8),
    8321            4 :                 Lsn(0x48),
    8322            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8323            4 :             ),
    8324            4 :             (
    8325            4 :                 get_key(9),
    8326            4 :                 Lsn(0x48),
    8327            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8328            4 :             ),
    8329            4 :         ];
    8330            4 : 
    8331            4 :         let tline = tenant
    8332            4 :             .create_test_timeline_with_layers(
    8333            4 :                 TIMELINE_ID,
    8334            4 :                 Lsn(0x10),
    8335            4 :                 DEFAULT_PG_VERSION,
    8336            4 :                 &ctx,
    8337            4 :                 vec![
    8338            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8339            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8340            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8341            4 :                 ], // delta layers
    8342            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8343            4 :                 Lsn(0x50),
    8344            4 :             )
    8345            4 :             .await?;
    8346            4 :         {
    8347            4 :             tline
    8348            4 :                 .latest_gc_cutoff_lsn
    8349            4 :                 .lock_for_write()
    8350            4 :                 .store_and_unlock(Lsn(0x30))
    8351            4 :                 .wait()
    8352            4 :                 .await;
    8353            4 :             // Update GC info
    8354            4 :             let mut guard = tline.gc_info.write().unwrap();
    8355            4 :             guard.cutoffs.time = Lsn(0x30);
    8356            4 :             guard.cutoffs.space = Lsn(0x30);
    8357            4 :         }
    8358            4 : 
    8359            4 :         let expected_result = [
    8360            4 :             Bytes::from_static(b"value 0@0x10"),
    8361            4 :             Bytes::from_static(b"value 1@0x20"),
    8362            4 :             Bytes::from_static(b"value 2@0x30"),
    8363            4 :             Bytes::from_static(b"value 3@0x40"),
    8364            4 :             Bytes::from_static(b"value 4@0x10"),
    8365            4 :             Bytes::from_static(b"value 5@0x20"),
    8366            4 :             Bytes::from_static(b"value 6@0x20"),
    8367            4 :             Bytes::from_static(b"value 7@0x10"),
    8368            4 :             Bytes::from_static(b"value 8@0x48"),
    8369            4 :             Bytes::from_static(b"value 9@0x48"),
    8370            4 :         ];
    8371            4 : 
    8372           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8373           40 :             assert_eq!(
    8374           40 :                 tline
    8375           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8376           40 :                     .await
    8377           40 :                     .unwrap(),
    8378            4 :                 expected
    8379            4 :             );
    8380            4 :         }
    8381            4 : 
    8382            4 :         let cancel = CancellationToken::new();
    8383            4 :         tline
    8384            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8385            4 :             .await
    8386            4 :             .unwrap();
    8387            4 : 
    8388           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8389           40 :             assert_eq!(
    8390           40 :                 tline
    8391           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8392           40 :                     .await
    8393           40 :                     .unwrap(),
    8394            4 :                 expected
    8395            4 :             );
    8396            4 :         }
    8397            4 : 
    8398            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8399            4 :         let image_at_gc_horizon = tline
    8400            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8401            4 :             .await
    8402            4 :             .unwrap()
    8403            4 :             .into_iter()
    8404           68 :             .filter(|(k, _)| k.is_metadata_key())
    8405            4 :             .collect::<Vec<_>>();
    8406            4 : 
    8407            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8408            4 :         let expected_result = [
    8409            4 :             Bytes::from_static(b"value 0@0x10"),
    8410            4 :             Bytes::from_static(b"value 1@0x20"),
    8411            4 :             Bytes::from_static(b"value 2@0x30"),
    8412            4 :             Bytes::from_static(b"value 3@0x10"),
    8413            4 :             Bytes::from_static(b"value 4@0x10"),
    8414            4 :             Bytes::from_static(b"value 5@0x20"),
    8415            4 :             Bytes::from_static(b"value 6@0x20"),
    8416            4 :             Bytes::from_static(b"value 7@0x10"),
    8417            4 :             Bytes::from_static(b"value 8@0x10"),
    8418            4 :             Bytes::from_static(b"value 9@0x10"),
    8419            4 :         ];
    8420           44 :         for idx in 0..10 {
    8421           40 :             assert_eq!(
    8422           40 :                 image_at_gc_horizon[idx],
    8423           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8424           40 :             );
    8425            4 :         }
    8426            4 : 
    8427            4 :         // Check if old layers are removed / new layers have the expected LSN
    8428            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8429            4 :         assert_eq!(
    8430            4 :             all_layers,
    8431            4 :             vec![
    8432            4 :                 // Image layer at GC horizon
    8433            4 :                 PersistentLayerKey {
    8434            4 :                     key_range: Key::MIN..Key::MAX,
    8435            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8436            4 :                     is_delta: false
    8437            4 :                 },
    8438            4 :                 // The delta layer below the horizon
    8439            4 :                 PersistentLayerKey {
    8440            4 :                     key_range: get_key(3)..get_key(4),
    8441            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8442            4 :                     is_delta: true
    8443            4 :                 },
    8444            4 :                 // The delta3 layer that should not be picked for the compaction
    8445            4 :                 PersistentLayerKey {
    8446            4 :                     key_range: get_key(8)..get_key(10),
    8447            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8448            4 :                     is_delta: true
    8449            4 :                 }
    8450            4 :             ]
    8451            4 :         );
    8452            4 : 
    8453            4 :         // increase GC horizon and compact again
    8454            4 :         {
    8455            4 :             tline
    8456            4 :                 .latest_gc_cutoff_lsn
    8457            4 :                 .lock_for_write()
    8458            4 :                 .store_and_unlock(Lsn(0x40))
    8459            4 :                 .wait()
    8460            4 :                 .await;
    8461            4 :             // Update GC info
    8462            4 :             let mut guard = tline.gc_info.write().unwrap();
    8463            4 :             guard.cutoffs.time = Lsn(0x40);
    8464            4 :             guard.cutoffs.space = Lsn(0x40);
    8465            4 :         }
    8466            4 :         tline
    8467            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8468            4 :             .await
    8469            4 :             .unwrap();
    8470            4 : 
    8471            4 :         Ok(())
    8472            4 :     }
    8473              : 
    8474              :     #[cfg(feature = "testing")]
    8475              :     #[tokio::test]
    8476            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8477            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8478            4 :         let (tenant, ctx) = harness.load().await;
    8479            4 : 
    8480           48 :         fn get_key(id: u32) -> Key {
    8481           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8482           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8483           48 :             key.field6 = id;
    8484           48 :             key
    8485           48 :         }
    8486            4 : 
    8487            4 :         let delta1 = vec![
    8488            4 :             (
    8489            4 :                 get_key(1),
    8490            4 :                 Lsn(0x20),
    8491            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8492            4 :             ),
    8493            4 :             (
    8494            4 :                 get_key(1),
    8495            4 :                 Lsn(0x30),
    8496            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8497            4 :             ),
    8498            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8499            4 :             (
    8500            4 :                 get_key(2),
    8501            4 :                 Lsn(0x20),
    8502            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8503            4 :             ),
    8504            4 :             (
    8505            4 :                 get_key(2),
    8506            4 :                 Lsn(0x30),
    8507            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8508            4 :             ),
    8509            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8510            4 :             (
    8511            4 :                 get_key(3),
    8512            4 :                 Lsn(0x20),
    8513            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8514            4 :             ),
    8515            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8516            4 :             (
    8517            4 :                 get_key(4),
    8518            4 :                 Lsn(0x20),
    8519            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8520            4 :             ),
    8521            4 :         ];
    8522            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8523            4 : 
    8524            4 :         let tline = tenant
    8525            4 :             .create_test_timeline_with_layers(
    8526            4 :                 TIMELINE_ID,
    8527            4 :                 Lsn(0x10),
    8528            4 :                 DEFAULT_PG_VERSION,
    8529            4 :                 &ctx,
    8530            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8531            4 :                     Lsn(0x10)..Lsn(0x40),
    8532            4 :                     delta1,
    8533            4 :                 )], // delta layers
    8534            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8535            4 :                 Lsn(0x50),
    8536            4 :             )
    8537            4 :             .await?;
    8538            4 : 
    8539            4 :         assert_eq!(
    8540            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8541            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8542            4 :         );
    8543            4 :         assert_eq!(
    8544            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8545            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8546            4 :         );
    8547            4 : 
    8548            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8549            4 : 
    8550            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8551            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8552            4 : 
    8553            4 :         Ok(())
    8554            4 :     }
    8555              : 
    8556              :     #[tokio::test(start_paused = true)]
    8557            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8558            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8559            4 :             .await
    8560            4 :             .unwrap()
    8561            4 :             .load()
    8562            4 :             .await;
    8563            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8564            4 :         // initial transition into AttachedSingle.
    8565            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8566            4 :         tokio::time::resume();
    8567            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8568            4 : 
    8569            4 :         let end_lsn = Lsn(0x100);
    8570            4 :         let image_layers = (0x20..=0x90)
    8571            4 :             .step_by(0x10)
    8572           32 :             .map(|n| {
    8573           32 :                 (
    8574           32 :                     Lsn(n),
    8575           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8576           32 :                 )
    8577           32 :             })
    8578            4 :             .collect();
    8579            4 : 
    8580            4 :         let timeline = tenant
    8581            4 :             .create_test_timeline_with_layers(
    8582            4 :                 TIMELINE_ID,
    8583            4 :                 Lsn(0x10),
    8584            4 :                 DEFAULT_PG_VERSION,
    8585            4 :                 &ctx,
    8586            4 :                 Vec::new(),
    8587            4 :                 image_layers,
    8588            4 :                 end_lsn,
    8589            4 :             )
    8590            4 :             .await?;
    8591            4 : 
    8592            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8593            4 :         let mut leases = Vec::new();
    8594           12 :         leased_lsns.iter().for_each(|n| {
    8595           12 :             leases.push(
    8596           12 :                 timeline
    8597           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8598           12 :                     .expect("lease request should succeed"),
    8599           12 :             );
    8600           12 :         });
    8601            4 : 
    8602            4 :         let updated_lease_0 = timeline
    8603            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8604            4 :             .expect("lease renewal should succeed");
    8605            4 :         assert_eq!(
    8606            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8607            4 :             " Renewing with shorter lease should not change the lease."
    8608            4 :         );
    8609            4 : 
    8610            4 :         let updated_lease_1 = timeline
    8611            4 :             .renew_lsn_lease(
    8612            4 :                 Lsn(leased_lsns[1]),
    8613            4 :                 timeline.get_lsn_lease_length() * 2,
    8614            4 :                 &ctx,
    8615            4 :             )
    8616            4 :             .expect("lease renewal should succeed");
    8617            4 :         assert!(
    8618            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8619            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8620            4 :         );
    8621            4 : 
    8622            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8623            4 :         info!(
    8624            4 :             "latest_gc_cutoff_lsn: {}",
    8625            0 :             *timeline.get_latest_gc_cutoff_lsn()
    8626            4 :         );
    8627            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8628            4 : 
    8629            4 :         let res = tenant
    8630            4 :             .gc_iteration(
    8631            4 :                 Some(TIMELINE_ID),
    8632            4 :                 0,
    8633            4 :                 Duration::ZERO,
    8634            4 :                 &CancellationToken::new(),
    8635            4 :                 &ctx,
    8636            4 :             )
    8637            4 :             .await
    8638            4 :             .unwrap();
    8639            4 : 
    8640            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8641            4 :         // 0/10: initdb layer
    8642            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8643            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8644            4 :         // Keeping 0/90 b/c it is the latest layer.
    8645            4 :         assert_eq!(res.layers_not_updated, 1);
    8646            4 :         // Removed 0/80.
    8647            4 :         assert_eq!(res.layers_removed, 1);
    8648            4 : 
    8649            4 :         // Make lease on a already GC-ed LSN.
    8650            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8651            4 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    8652            4 :         timeline
    8653            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8654            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8655            4 : 
    8656            4 :         // Should still be able to renew a currently valid lease
    8657            4 :         // Assumption: original lease to is still valid for 0/50.
    8658            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8659            4 :         timeline
    8660            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8661            4 :             .expect("lease renewal with validation should succeed");
    8662            4 : 
    8663            4 :         Ok(())
    8664            4 :     }
    8665              : 
    8666              :     #[cfg(feature = "testing")]
    8667              :     #[tokio::test]
    8668            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8669            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8670            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8671            4 :             false,
    8672            4 :         )
    8673            4 :         .await
    8674            4 :     }
    8675              : 
    8676              :     #[cfg(feature = "testing")]
    8677              :     #[tokio::test]
    8678            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8679            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8680            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8681            4 :             true,
    8682            4 :         )
    8683            4 :         .await
    8684            4 :     }
    8685              : 
    8686              :     #[cfg(feature = "testing")]
    8687            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8688            8 :         test_name: &'static str,
    8689            8 :         use_delta_bottom_layer: bool,
    8690            8 :     ) -> anyhow::Result<()> {
    8691            8 :         let harness = TenantHarness::create(test_name).await?;
    8692            8 :         let (tenant, ctx) = harness.load().await;
    8693              : 
    8694          552 :         fn get_key(id: u32) -> Key {
    8695          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8696          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8697          552 :             key.field6 = id;
    8698          552 :             key
    8699          552 :         }
    8700              : 
    8701              :         // We create
    8702              :         // - one bottom-most image layer,
    8703              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8704              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8705              :         // - a delta layer D3 above the horizon.
    8706              :         //
    8707              :         //                             | D3 |
    8708              :         //  | D1 |
    8709              :         // -|    |-- gc horizon -----------------
    8710              :         //  |    |                | D2 |
    8711              :         // --------- img layer ------------------
    8712              :         //
    8713              :         // What we should expact from this compaction is:
    8714              :         //                             | D3 |
    8715              :         //  | Part of D1 |
    8716              :         // --------- img layer with D1+D2 at GC horizon------------------
    8717              : 
    8718              :         // img layer at 0x10
    8719            8 :         let img_layer = (0..10)
    8720           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8721            8 :             .collect_vec();
    8722            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8723            8 :         let delta4 = (0..10)
    8724           80 :             .map(|id| {
    8725           80 :                 (
    8726           80 :                     get_key(id),
    8727           80 :                     Lsn(0x08),
    8728           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8729           80 :                 )
    8730           80 :             })
    8731            8 :             .collect_vec();
    8732            8 : 
    8733            8 :         let delta1 = vec![
    8734            8 :             (
    8735            8 :                 get_key(1),
    8736            8 :                 Lsn(0x20),
    8737            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8738            8 :             ),
    8739            8 :             (
    8740            8 :                 get_key(2),
    8741            8 :                 Lsn(0x30),
    8742            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8743            8 :             ),
    8744            8 :             (
    8745            8 :                 get_key(3),
    8746            8 :                 Lsn(0x28),
    8747            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8748            8 :             ),
    8749            8 :             (
    8750            8 :                 get_key(3),
    8751            8 :                 Lsn(0x30),
    8752            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8753            8 :             ),
    8754            8 :             (
    8755            8 :                 get_key(3),
    8756            8 :                 Lsn(0x40),
    8757            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8758            8 :             ),
    8759            8 :         ];
    8760            8 :         let delta2 = vec![
    8761            8 :             (
    8762            8 :                 get_key(5),
    8763            8 :                 Lsn(0x20),
    8764            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8765            8 :             ),
    8766            8 :             (
    8767            8 :                 get_key(6),
    8768            8 :                 Lsn(0x20),
    8769            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8770            8 :             ),
    8771            8 :         ];
    8772            8 :         let delta3 = vec![
    8773            8 :             (
    8774            8 :                 get_key(8),
    8775            8 :                 Lsn(0x48),
    8776            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8777            8 :             ),
    8778            8 :             (
    8779            8 :                 get_key(9),
    8780            8 :                 Lsn(0x48),
    8781            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8782            8 :             ),
    8783            8 :         ];
    8784              : 
    8785            8 :         let tline = if use_delta_bottom_layer {
    8786            4 :             tenant
    8787            4 :                 .create_test_timeline_with_layers(
    8788            4 :                     TIMELINE_ID,
    8789            4 :                     Lsn(0x08),
    8790            4 :                     DEFAULT_PG_VERSION,
    8791            4 :                     &ctx,
    8792            4 :                     vec![
    8793            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8794            4 :                             Lsn(0x08)..Lsn(0x10),
    8795            4 :                             delta4,
    8796            4 :                         ),
    8797            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8798            4 :                             Lsn(0x20)..Lsn(0x48),
    8799            4 :                             delta1,
    8800            4 :                         ),
    8801            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8802            4 :                             Lsn(0x20)..Lsn(0x48),
    8803            4 :                             delta2,
    8804            4 :                         ),
    8805            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8806            4 :                             Lsn(0x48)..Lsn(0x50),
    8807            4 :                             delta3,
    8808            4 :                         ),
    8809            4 :                     ], // delta layers
    8810            4 :                     vec![], // image layers
    8811            4 :                     Lsn(0x50),
    8812            4 :                 )
    8813            4 :                 .await?
    8814              :         } else {
    8815            4 :             tenant
    8816            4 :                 .create_test_timeline_with_layers(
    8817            4 :                     TIMELINE_ID,
    8818            4 :                     Lsn(0x10),
    8819            4 :                     DEFAULT_PG_VERSION,
    8820            4 :                     &ctx,
    8821            4 :                     vec![
    8822            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8823            4 :                             Lsn(0x10)..Lsn(0x48),
    8824            4 :                             delta1,
    8825            4 :                         ),
    8826            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8827            4 :                             Lsn(0x10)..Lsn(0x48),
    8828            4 :                             delta2,
    8829            4 :                         ),
    8830            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8831            4 :                             Lsn(0x48)..Lsn(0x50),
    8832            4 :                             delta3,
    8833            4 :                         ),
    8834            4 :                     ], // delta layers
    8835            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8836            4 :                     Lsn(0x50),
    8837            4 :                 )
    8838            4 :                 .await?
    8839              :         };
    8840              :         {
    8841            8 :             tline
    8842            8 :                 .latest_gc_cutoff_lsn
    8843            8 :                 .lock_for_write()
    8844            8 :                 .store_and_unlock(Lsn(0x30))
    8845            8 :                 .wait()
    8846            8 :                 .await;
    8847              :             // Update GC info
    8848            8 :             let mut guard = tline.gc_info.write().unwrap();
    8849            8 :             *guard = GcInfo {
    8850            8 :                 retain_lsns: vec![],
    8851            8 :                 cutoffs: GcCutoffs {
    8852            8 :                     time: Lsn(0x30),
    8853            8 :                     space: Lsn(0x30),
    8854            8 :                 },
    8855            8 :                 leases: Default::default(),
    8856            8 :                 within_ancestor_pitr: false,
    8857            8 :             };
    8858            8 :         }
    8859            8 : 
    8860            8 :         let expected_result = [
    8861            8 :             Bytes::from_static(b"value 0@0x10"),
    8862            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8863            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8864            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8865            8 :             Bytes::from_static(b"value 4@0x10"),
    8866            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8867            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8868            8 :             Bytes::from_static(b"value 7@0x10"),
    8869            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8870            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8871            8 :         ];
    8872            8 : 
    8873            8 :         let expected_result_at_gc_horizon = [
    8874            8 :             Bytes::from_static(b"value 0@0x10"),
    8875            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8876            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8877            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8878            8 :             Bytes::from_static(b"value 4@0x10"),
    8879            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8880            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8881            8 :             Bytes::from_static(b"value 7@0x10"),
    8882            8 :             Bytes::from_static(b"value 8@0x10"),
    8883            8 :             Bytes::from_static(b"value 9@0x10"),
    8884            8 :         ];
    8885              : 
    8886           88 :         for idx in 0..10 {
    8887           80 :             assert_eq!(
    8888           80 :                 tline
    8889           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8890           80 :                     .await
    8891           80 :                     .unwrap(),
    8892           80 :                 &expected_result[idx]
    8893              :             );
    8894           80 :             assert_eq!(
    8895           80 :                 tline
    8896           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8897           80 :                     .await
    8898           80 :                     .unwrap(),
    8899           80 :                 &expected_result_at_gc_horizon[idx]
    8900              :             );
    8901              :         }
    8902              : 
    8903            8 :         let cancel = CancellationToken::new();
    8904            8 :         tline
    8905            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8906            8 :             .await
    8907            8 :             .unwrap();
    8908              : 
    8909           88 :         for idx in 0..10 {
    8910           80 :             assert_eq!(
    8911           80 :                 tline
    8912           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8913           80 :                     .await
    8914           80 :                     .unwrap(),
    8915           80 :                 &expected_result[idx]
    8916              :             );
    8917           80 :             assert_eq!(
    8918           80 :                 tline
    8919           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8920           80 :                     .await
    8921           80 :                     .unwrap(),
    8922           80 :                 &expected_result_at_gc_horizon[idx]
    8923              :             );
    8924              :         }
    8925              : 
    8926              :         // increase GC horizon and compact again
    8927              :         {
    8928            8 :             tline
    8929            8 :                 .latest_gc_cutoff_lsn
    8930            8 :                 .lock_for_write()
    8931            8 :                 .store_and_unlock(Lsn(0x40))
    8932            8 :                 .wait()
    8933            8 :                 .await;
    8934              :             // Update GC info
    8935            8 :             let mut guard = tline.gc_info.write().unwrap();
    8936            8 :             guard.cutoffs.time = Lsn(0x40);
    8937            8 :             guard.cutoffs.space = Lsn(0x40);
    8938            8 :         }
    8939            8 :         tline
    8940            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8941            8 :             .await
    8942            8 :             .unwrap();
    8943            8 : 
    8944            8 :         Ok(())
    8945            8 :     }
    8946              : 
    8947              :     #[cfg(feature = "testing")]
    8948              :     #[tokio::test]
    8949            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8950            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8951            4 :         let (tenant, ctx) = harness.load().await;
    8952            4 :         let tline = tenant
    8953            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8954            4 :             .await?;
    8955            4 :         tline.force_advance_lsn(Lsn(0x70));
    8956            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8957            4 :         let history = vec![
    8958            4 :             (
    8959            4 :                 key,
    8960            4 :                 Lsn(0x10),
    8961            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8962            4 :             ),
    8963            4 :             (
    8964            4 :                 key,
    8965            4 :                 Lsn(0x20),
    8966            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8967            4 :             ),
    8968            4 :             (
    8969            4 :                 key,
    8970            4 :                 Lsn(0x30),
    8971            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8972            4 :             ),
    8973            4 :             (
    8974            4 :                 key,
    8975            4 :                 Lsn(0x40),
    8976            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8977            4 :             ),
    8978            4 :             (
    8979            4 :                 key,
    8980            4 :                 Lsn(0x50),
    8981            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8982            4 :             ),
    8983            4 :             (
    8984            4 :                 key,
    8985            4 :                 Lsn(0x60),
    8986            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8987            4 :             ),
    8988            4 :             (
    8989            4 :                 key,
    8990            4 :                 Lsn(0x70),
    8991            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8992            4 :             ),
    8993            4 :             (
    8994            4 :                 key,
    8995            4 :                 Lsn(0x80),
    8996            4 :                 Value::Image(Bytes::copy_from_slice(
    8997            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8998            4 :                 )),
    8999            4 :             ),
    9000            4 :             (
    9001            4 :                 key,
    9002            4 :                 Lsn(0x90),
    9003            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9004            4 :             ),
    9005            4 :         ];
    9006            4 :         let res = tline
    9007            4 :             .generate_key_retention(
    9008            4 :                 key,
    9009            4 :                 &history,
    9010            4 :                 Lsn(0x60),
    9011            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9012            4 :                 3,
    9013            4 :                 None,
    9014            4 :             )
    9015            4 :             .await
    9016            4 :             .unwrap();
    9017            4 :         let expected_res = KeyHistoryRetention {
    9018            4 :             below_horizon: vec![
    9019            4 :                 (
    9020            4 :                     Lsn(0x20),
    9021            4 :                     KeyLogAtLsn(vec![(
    9022            4 :                         Lsn(0x20),
    9023            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9024            4 :                     )]),
    9025            4 :                 ),
    9026            4 :                 (
    9027            4 :                     Lsn(0x40),
    9028            4 :                     KeyLogAtLsn(vec![
    9029            4 :                         (
    9030            4 :                             Lsn(0x30),
    9031            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9032            4 :                         ),
    9033            4 :                         (
    9034            4 :                             Lsn(0x40),
    9035            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9036            4 :                         ),
    9037            4 :                     ]),
    9038            4 :                 ),
    9039            4 :                 (
    9040            4 :                     Lsn(0x50),
    9041            4 :                     KeyLogAtLsn(vec![(
    9042            4 :                         Lsn(0x50),
    9043            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9044            4 :                     )]),
    9045            4 :                 ),
    9046            4 :                 (
    9047            4 :                     Lsn(0x60),
    9048            4 :                     KeyLogAtLsn(vec![(
    9049            4 :                         Lsn(0x60),
    9050            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9051            4 :                     )]),
    9052            4 :                 ),
    9053            4 :             ],
    9054            4 :             above_horizon: KeyLogAtLsn(vec![
    9055            4 :                 (
    9056            4 :                     Lsn(0x70),
    9057            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9058            4 :                 ),
    9059            4 :                 (
    9060            4 :                     Lsn(0x80),
    9061            4 :                     Value::Image(Bytes::copy_from_slice(
    9062            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9063            4 :                     )),
    9064            4 :                 ),
    9065            4 :                 (
    9066            4 :                     Lsn(0x90),
    9067            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9068            4 :                 ),
    9069            4 :             ]),
    9070            4 :         };
    9071            4 :         assert_eq!(res, expected_res);
    9072            4 : 
    9073            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9074            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9075            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9076            4 :         // For example, we have
    9077            4 :         // ```plain
    9078            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9079            4 :         // ```
    9080            4 :         // Now the GC horizon moves up, and we have
    9081            4 :         // ```plain
    9082            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9083            4 :         // ```
    9084            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9085            4 :         // We will end up with
    9086            4 :         // ```plain
    9087            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9088            4 :         // ```
    9089            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9090            4 :         // We should be able to handle this partial history and drop everything before the
    9091            4 :         // gc_horizon image.
    9092            4 : 
    9093            4 :         let history = vec![
    9094            4 :             (
    9095            4 :                 key,
    9096            4 :                 Lsn(0x20),
    9097            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9098            4 :             ),
    9099            4 :             (
    9100            4 :                 key,
    9101            4 :                 Lsn(0x30),
    9102            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9103            4 :             ),
    9104            4 :             (
    9105            4 :                 key,
    9106            4 :                 Lsn(0x40),
    9107            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9108            4 :             ),
    9109            4 :             (
    9110            4 :                 key,
    9111            4 :                 Lsn(0x50),
    9112            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9113            4 :             ),
    9114            4 :             (
    9115            4 :                 key,
    9116            4 :                 Lsn(0x60),
    9117            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9118            4 :             ),
    9119            4 :             (
    9120            4 :                 key,
    9121            4 :                 Lsn(0x70),
    9122            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9123            4 :             ),
    9124            4 :             (
    9125            4 :                 key,
    9126            4 :                 Lsn(0x80),
    9127            4 :                 Value::Image(Bytes::copy_from_slice(
    9128            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9129            4 :                 )),
    9130            4 :             ),
    9131            4 :             (
    9132            4 :                 key,
    9133            4 :                 Lsn(0x90),
    9134            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9135            4 :             ),
    9136            4 :         ];
    9137            4 :         let res = tline
    9138            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9139            4 :             .await
    9140            4 :             .unwrap();
    9141            4 :         let expected_res = KeyHistoryRetention {
    9142            4 :             below_horizon: vec![
    9143            4 :                 (
    9144            4 :                     Lsn(0x40),
    9145            4 :                     KeyLogAtLsn(vec![(
    9146            4 :                         Lsn(0x40),
    9147            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9148            4 :                     )]),
    9149            4 :                 ),
    9150            4 :                 (
    9151            4 :                     Lsn(0x50),
    9152            4 :                     KeyLogAtLsn(vec![(
    9153            4 :                         Lsn(0x50),
    9154            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9155            4 :                     )]),
    9156            4 :                 ),
    9157            4 :                 (
    9158            4 :                     Lsn(0x60),
    9159            4 :                     KeyLogAtLsn(vec![(
    9160            4 :                         Lsn(0x60),
    9161            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9162            4 :                     )]),
    9163            4 :                 ),
    9164            4 :             ],
    9165            4 :             above_horizon: KeyLogAtLsn(vec![
    9166            4 :                 (
    9167            4 :                     Lsn(0x70),
    9168            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9169            4 :                 ),
    9170            4 :                 (
    9171            4 :                     Lsn(0x80),
    9172            4 :                     Value::Image(Bytes::copy_from_slice(
    9173            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9174            4 :                     )),
    9175            4 :                 ),
    9176            4 :                 (
    9177            4 :                     Lsn(0x90),
    9178            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9179            4 :                 ),
    9180            4 :             ]),
    9181            4 :         };
    9182            4 :         assert_eq!(res, expected_res);
    9183            4 : 
    9184            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9185            4 :         // the ancestor image in the test case.
    9186            4 : 
    9187            4 :         let history = vec![
    9188            4 :             (
    9189            4 :                 key,
    9190            4 :                 Lsn(0x20),
    9191            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9192            4 :             ),
    9193            4 :             (
    9194            4 :                 key,
    9195            4 :                 Lsn(0x30),
    9196            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9197            4 :             ),
    9198            4 :             (
    9199            4 :                 key,
    9200            4 :                 Lsn(0x40),
    9201            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9202            4 :             ),
    9203            4 :             (
    9204            4 :                 key,
    9205            4 :                 Lsn(0x70),
    9206            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9207            4 :             ),
    9208            4 :         ];
    9209            4 :         let res = tline
    9210            4 :             .generate_key_retention(
    9211            4 :                 key,
    9212            4 :                 &history,
    9213            4 :                 Lsn(0x60),
    9214            4 :                 &[],
    9215            4 :                 3,
    9216            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9217            4 :             )
    9218            4 :             .await
    9219            4 :             .unwrap();
    9220            4 :         let expected_res = KeyHistoryRetention {
    9221            4 :             below_horizon: vec![(
    9222            4 :                 Lsn(0x60),
    9223            4 :                 KeyLogAtLsn(vec![(
    9224            4 :                     Lsn(0x60),
    9225            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9226            4 :                 )]),
    9227            4 :             )],
    9228            4 :             above_horizon: KeyLogAtLsn(vec![(
    9229            4 :                 Lsn(0x70),
    9230            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9231            4 :             )]),
    9232            4 :         };
    9233            4 :         assert_eq!(res, expected_res);
    9234            4 : 
    9235            4 :         let history = vec![
    9236            4 :             (
    9237            4 :                 key,
    9238            4 :                 Lsn(0x20),
    9239            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9240            4 :             ),
    9241            4 :             (
    9242            4 :                 key,
    9243            4 :                 Lsn(0x40),
    9244            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9245            4 :             ),
    9246            4 :             (
    9247            4 :                 key,
    9248            4 :                 Lsn(0x60),
    9249            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9250            4 :             ),
    9251            4 :             (
    9252            4 :                 key,
    9253            4 :                 Lsn(0x70),
    9254            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9255            4 :             ),
    9256            4 :         ];
    9257            4 :         let res = tline
    9258            4 :             .generate_key_retention(
    9259            4 :                 key,
    9260            4 :                 &history,
    9261            4 :                 Lsn(0x60),
    9262            4 :                 &[Lsn(0x30)],
    9263            4 :                 3,
    9264            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9265            4 :             )
    9266            4 :             .await
    9267            4 :             .unwrap();
    9268            4 :         let expected_res = KeyHistoryRetention {
    9269            4 :             below_horizon: vec![
    9270            4 :                 (
    9271            4 :                     Lsn(0x30),
    9272            4 :                     KeyLogAtLsn(vec![(
    9273            4 :                         Lsn(0x20),
    9274            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9275            4 :                     )]),
    9276            4 :                 ),
    9277            4 :                 (
    9278            4 :                     Lsn(0x60),
    9279            4 :                     KeyLogAtLsn(vec![(
    9280            4 :                         Lsn(0x60),
    9281            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9282            4 :                     )]),
    9283            4 :                 ),
    9284            4 :             ],
    9285            4 :             above_horizon: KeyLogAtLsn(vec![(
    9286            4 :                 Lsn(0x70),
    9287            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9288            4 :             )]),
    9289            4 :         };
    9290            4 :         assert_eq!(res, expected_res);
    9291            4 : 
    9292            4 :         Ok(())
    9293            4 :     }
    9294              : 
    9295              :     #[cfg(feature = "testing")]
    9296              :     #[tokio::test]
    9297            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9298            4 :         let harness =
    9299            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9300            4 :         let (tenant, ctx) = harness.load().await;
    9301            4 : 
    9302         1036 :         fn get_key(id: u32) -> Key {
    9303         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9304         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9305         1036 :             key.field6 = id;
    9306         1036 :             key
    9307         1036 :         }
    9308            4 : 
    9309            4 :         let img_layer = (0..10)
    9310           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9311            4 :             .collect_vec();
    9312            4 : 
    9313            4 :         let delta1 = vec![
    9314            4 :             (
    9315            4 :                 get_key(1),
    9316            4 :                 Lsn(0x20),
    9317            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9318            4 :             ),
    9319            4 :             (
    9320            4 :                 get_key(2),
    9321            4 :                 Lsn(0x30),
    9322            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9323            4 :             ),
    9324            4 :             (
    9325            4 :                 get_key(3),
    9326            4 :                 Lsn(0x28),
    9327            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9328            4 :             ),
    9329            4 :             (
    9330            4 :                 get_key(3),
    9331            4 :                 Lsn(0x30),
    9332            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9333            4 :             ),
    9334            4 :             (
    9335            4 :                 get_key(3),
    9336            4 :                 Lsn(0x40),
    9337            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9338            4 :             ),
    9339            4 :         ];
    9340            4 :         let delta2 = vec![
    9341            4 :             (
    9342            4 :                 get_key(5),
    9343            4 :                 Lsn(0x20),
    9344            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9345            4 :             ),
    9346            4 :             (
    9347            4 :                 get_key(6),
    9348            4 :                 Lsn(0x20),
    9349            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9350            4 :             ),
    9351            4 :         ];
    9352            4 :         let delta3 = vec![
    9353            4 :             (
    9354            4 :                 get_key(8),
    9355            4 :                 Lsn(0x48),
    9356            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9357            4 :             ),
    9358            4 :             (
    9359            4 :                 get_key(9),
    9360            4 :                 Lsn(0x48),
    9361            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9362            4 :             ),
    9363            4 :         ];
    9364            4 : 
    9365            4 :         let tline = tenant
    9366            4 :             .create_test_timeline_with_layers(
    9367            4 :                 TIMELINE_ID,
    9368            4 :                 Lsn(0x10),
    9369            4 :                 DEFAULT_PG_VERSION,
    9370            4 :                 &ctx,
    9371            4 :                 vec![
    9372            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9373            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9374            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9375            4 :                 ], // delta layers
    9376            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9377            4 :                 Lsn(0x50),
    9378            4 :             )
    9379            4 :             .await?;
    9380            4 :         {
    9381            4 :             tline
    9382            4 :                 .latest_gc_cutoff_lsn
    9383            4 :                 .lock_for_write()
    9384            4 :                 .store_and_unlock(Lsn(0x30))
    9385            4 :                 .wait()
    9386            4 :                 .await;
    9387            4 :             // Update GC info
    9388            4 :             let mut guard = tline.gc_info.write().unwrap();
    9389            4 :             *guard = GcInfo {
    9390            4 :                 retain_lsns: vec![
    9391            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9392            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9393            4 :                 ],
    9394            4 :                 cutoffs: GcCutoffs {
    9395            4 :                     time: Lsn(0x30),
    9396            4 :                     space: Lsn(0x30),
    9397            4 :                 },
    9398            4 :                 leases: Default::default(),
    9399            4 :                 within_ancestor_pitr: false,
    9400            4 :             };
    9401            4 :         }
    9402            4 : 
    9403            4 :         let expected_result = [
    9404            4 :             Bytes::from_static(b"value 0@0x10"),
    9405            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9406            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9407            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9408            4 :             Bytes::from_static(b"value 4@0x10"),
    9409            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9410            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9411            4 :             Bytes::from_static(b"value 7@0x10"),
    9412            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9413            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9414            4 :         ];
    9415            4 : 
    9416            4 :         let expected_result_at_gc_horizon = [
    9417            4 :             Bytes::from_static(b"value 0@0x10"),
    9418            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9419            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9420            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9421            4 :             Bytes::from_static(b"value 4@0x10"),
    9422            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9423            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9424            4 :             Bytes::from_static(b"value 7@0x10"),
    9425            4 :             Bytes::from_static(b"value 8@0x10"),
    9426            4 :             Bytes::from_static(b"value 9@0x10"),
    9427            4 :         ];
    9428            4 : 
    9429            4 :         let expected_result_at_lsn_20 = [
    9430            4 :             Bytes::from_static(b"value 0@0x10"),
    9431            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9432            4 :             Bytes::from_static(b"value 2@0x10"),
    9433            4 :             Bytes::from_static(b"value 3@0x10"),
    9434            4 :             Bytes::from_static(b"value 4@0x10"),
    9435            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9436            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9437            4 :             Bytes::from_static(b"value 7@0x10"),
    9438            4 :             Bytes::from_static(b"value 8@0x10"),
    9439            4 :             Bytes::from_static(b"value 9@0x10"),
    9440            4 :         ];
    9441            4 : 
    9442            4 :         let expected_result_at_lsn_10 = [
    9443            4 :             Bytes::from_static(b"value 0@0x10"),
    9444            4 :             Bytes::from_static(b"value 1@0x10"),
    9445            4 :             Bytes::from_static(b"value 2@0x10"),
    9446            4 :             Bytes::from_static(b"value 3@0x10"),
    9447            4 :             Bytes::from_static(b"value 4@0x10"),
    9448            4 :             Bytes::from_static(b"value 5@0x10"),
    9449            4 :             Bytes::from_static(b"value 6@0x10"),
    9450            4 :             Bytes::from_static(b"value 7@0x10"),
    9451            4 :             Bytes::from_static(b"value 8@0x10"),
    9452            4 :             Bytes::from_static(b"value 9@0x10"),
    9453            4 :         ];
    9454            4 : 
    9455           24 :         let verify_result = || async {
    9456           24 :             let gc_horizon = {
    9457           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9458           24 :                 gc_info.cutoffs.time
    9459            4 :             };
    9460          264 :             for idx in 0..10 {
    9461          240 :                 assert_eq!(
    9462          240 :                     tline
    9463          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9464          240 :                         .await
    9465          240 :                         .unwrap(),
    9466          240 :                     &expected_result[idx]
    9467            4 :                 );
    9468          240 :                 assert_eq!(
    9469          240 :                     tline
    9470          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9471          240 :                         .await
    9472          240 :                         .unwrap(),
    9473          240 :                     &expected_result_at_gc_horizon[idx]
    9474            4 :                 );
    9475          240 :                 assert_eq!(
    9476          240 :                     tline
    9477          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9478          240 :                         .await
    9479          240 :                         .unwrap(),
    9480          240 :                     &expected_result_at_lsn_20[idx]
    9481            4 :                 );
    9482          240 :                 assert_eq!(
    9483          240 :                     tline
    9484          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9485          240 :                         .await
    9486          240 :                         .unwrap(),
    9487          240 :                     &expected_result_at_lsn_10[idx]
    9488            4 :                 );
    9489            4 :             }
    9490           48 :         };
    9491            4 : 
    9492            4 :         verify_result().await;
    9493            4 : 
    9494            4 :         let cancel = CancellationToken::new();
    9495            4 :         let mut dryrun_flags = EnumSet::new();
    9496            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9497            4 : 
    9498            4 :         tline
    9499            4 :             .compact_with_gc(
    9500            4 :                 &cancel,
    9501            4 :                 CompactOptions {
    9502            4 :                     flags: dryrun_flags,
    9503            4 :                     ..Default::default()
    9504            4 :                 },
    9505            4 :                 &ctx,
    9506            4 :             )
    9507            4 :             .await
    9508            4 :             .unwrap();
    9509            4 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9510            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9511            4 :         verify_result().await;
    9512            4 : 
    9513            4 :         tline
    9514            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9515            4 :             .await
    9516            4 :             .unwrap();
    9517            4 :         verify_result().await;
    9518            4 : 
    9519            4 :         // compact again
    9520            4 :         tline
    9521            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9522            4 :             .await
    9523            4 :             .unwrap();
    9524            4 :         verify_result().await;
    9525            4 : 
    9526            4 :         // increase GC horizon and compact again
    9527            4 :         {
    9528            4 :             tline
    9529            4 :                 .latest_gc_cutoff_lsn
    9530            4 :                 .lock_for_write()
    9531            4 :                 .store_and_unlock(Lsn(0x38))
    9532            4 :                 .wait()
    9533            4 :                 .await;
    9534            4 :             // Update GC info
    9535            4 :             let mut guard = tline.gc_info.write().unwrap();
    9536            4 :             guard.cutoffs.time = Lsn(0x38);
    9537            4 :             guard.cutoffs.space = Lsn(0x38);
    9538            4 :         }
    9539            4 :         tline
    9540            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9541            4 :             .await
    9542            4 :             .unwrap();
    9543            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9544            4 : 
    9545            4 :         // not increasing the GC horizon and compact again
    9546            4 :         tline
    9547            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9548            4 :             .await
    9549            4 :             .unwrap();
    9550            4 :         verify_result().await;
    9551            4 : 
    9552            4 :         Ok(())
    9553            4 :     }
    9554              : 
    9555              :     #[cfg(feature = "testing")]
    9556              :     #[tokio::test]
    9557            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9558            4 :     {
    9559            4 :         let harness =
    9560            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9561            4 :                 .await?;
    9562            4 :         let (tenant, ctx) = harness.load().await;
    9563            4 : 
    9564          704 :         fn get_key(id: u32) -> Key {
    9565          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9566          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9567          704 :             key.field6 = id;
    9568          704 :             key
    9569          704 :         }
    9570            4 : 
    9571            4 :         let img_layer = (0..10)
    9572           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9573            4 :             .collect_vec();
    9574            4 : 
    9575            4 :         let delta1 = vec![
    9576            4 :             (
    9577            4 :                 get_key(1),
    9578            4 :                 Lsn(0x20),
    9579            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9580            4 :             ),
    9581            4 :             (
    9582            4 :                 get_key(1),
    9583            4 :                 Lsn(0x28),
    9584            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9585            4 :             ),
    9586            4 :         ];
    9587            4 :         let delta2 = vec![
    9588            4 :             (
    9589            4 :                 get_key(1),
    9590            4 :                 Lsn(0x30),
    9591            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9592            4 :             ),
    9593            4 :             (
    9594            4 :                 get_key(1),
    9595            4 :                 Lsn(0x38),
    9596            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9597            4 :             ),
    9598            4 :         ];
    9599            4 :         let delta3 = vec![
    9600            4 :             (
    9601            4 :                 get_key(8),
    9602            4 :                 Lsn(0x48),
    9603            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9604            4 :             ),
    9605            4 :             (
    9606            4 :                 get_key(9),
    9607            4 :                 Lsn(0x48),
    9608            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9609            4 :             ),
    9610            4 :         ];
    9611            4 : 
    9612            4 :         let tline = tenant
    9613            4 :             .create_test_timeline_with_layers(
    9614            4 :                 TIMELINE_ID,
    9615            4 :                 Lsn(0x10),
    9616            4 :                 DEFAULT_PG_VERSION,
    9617            4 :                 &ctx,
    9618            4 :                 vec![
    9619            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9620            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9621            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9622            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9623            4 :                 ], // delta layers
    9624            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9625            4 :                 Lsn(0x50),
    9626            4 :             )
    9627            4 :             .await?;
    9628            4 :         {
    9629            4 :             tline
    9630            4 :                 .latest_gc_cutoff_lsn
    9631            4 :                 .lock_for_write()
    9632            4 :                 .store_and_unlock(Lsn(0x30))
    9633            4 :                 .wait()
    9634            4 :                 .await;
    9635            4 :             // Update GC info
    9636            4 :             let mut guard = tline.gc_info.write().unwrap();
    9637            4 :             *guard = GcInfo {
    9638            4 :                 retain_lsns: vec![
    9639            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9640            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9641            4 :                 ],
    9642            4 :                 cutoffs: GcCutoffs {
    9643            4 :                     time: Lsn(0x30),
    9644            4 :                     space: Lsn(0x30),
    9645            4 :                 },
    9646            4 :                 leases: Default::default(),
    9647            4 :                 within_ancestor_pitr: false,
    9648            4 :             };
    9649            4 :         }
    9650            4 : 
    9651            4 :         let expected_result = [
    9652            4 :             Bytes::from_static(b"value 0@0x10"),
    9653            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9654            4 :             Bytes::from_static(b"value 2@0x10"),
    9655            4 :             Bytes::from_static(b"value 3@0x10"),
    9656            4 :             Bytes::from_static(b"value 4@0x10"),
    9657            4 :             Bytes::from_static(b"value 5@0x10"),
    9658            4 :             Bytes::from_static(b"value 6@0x10"),
    9659            4 :             Bytes::from_static(b"value 7@0x10"),
    9660            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9661            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9662            4 :         ];
    9663            4 : 
    9664            4 :         let expected_result_at_gc_horizon = [
    9665            4 :             Bytes::from_static(b"value 0@0x10"),
    9666            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9667            4 :             Bytes::from_static(b"value 2@0x10"),
    9668            4 :             Bytes::from_static(b"value 3@0x10"),
    9669            4 :             Bytes::from_static(b"value 4@0x10"),
    9670            4 :             Bytes::from_static(b"value 5@0x10"),
    9671            4 :             Bytes::from_static(b"value 6@0x10"),
    9672            4 :             Bytes::from_static(b"value 7@0x10"),
    9673            4 :             Bytes::from_static(b"value 8@0x10"),
    9674            4 :             Bytes::from_static(b"value 9@0x10"),
    9675            4 :         ];
    9676            4 : 
    9677            4 :         let expected_result_at_lsn_20 = [
    9678            4 :             Bytes::from_static(b"value 0@0x10"),
    9679            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9680            4 :             Bytes::from_static(b"value 2@0x10"),
    9681            4 :             Bytes::from_static(b"value 3@0x10"),
    9682            4 :             Bytes::from_static(b"value 4@0x10"),
    9683            4 :             Bytes::from_static(b"value 5@0x10"),
    9684            4 :             Bytes::from_static(b"value 6@0x10"),
    9685            4 :             Bytes::from_static(b"value 7@0x10"),
    9686            4 :             Bytes::from_static(b"value 8@0x10"),
    9687            4 :             Bytes::from_static(b"value 9@0x10"),
    9688            4 :         ];
    9689            4 : 
    9690            4 :         let expected_result_at_lsn_10 = [
    9691            4 :             Bytes::from_static(b"value 0@0x10"),
    9692            4 :             Bytes::from_static(b"value 1@0x10"),
    9693            4 :             Bytes::from_static(b"value 2@0x10"),
    9694            4 :             Bytes::from_static(b"value 3@0x10"),
    9695            4 :             Bytes::from_static(b"value 4@0x10"),
    9696            4 :             Bytes::from_static(b"value 5@0x10"),
    9697            4 :             Bytes::from_static(b"value 6@0x10"),
    9698            4 :             Bytes::from_static(b"value 7@0x10"),
    9699            4 :             Bytes::from_static(b"value 8@0x10"),
    9700            4 :             Bytes::from_static(b"value 9@0x10"),
    9701            4 :         ];
    9702            4 : 
    9703           16 :         let verify_result = || async {
    9704           16 :             let gc_horizon = {
    9705           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9706           16 :                 gc_info.cutoffs.time
    9707            4 :             };
    9708          176 :             for idx in 0..10 {
    9709          160 :                 assert_eq!(
    9710          160 :                     tline
    9711          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9712          160 :                         .await
    9713          160 :                         .unwrap(),
    9714          160 :                     &expected_result[idx]
    9715            4 :                 );
    9716          160 :                 assert_eq!(
    9717          160 :                     tline
    9718          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9719          160 :                         .await
    9720          160 :                         .unwrap(),
    9721          160 :                     &expected_result_at_gc_horizon[idx]
    9722            4 :                 );
    9723          160 :                 assert_eq!(
    9724          160 :                     tline
    9725          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9726          160 :                         .await
    9727          160 :                         .unwrap(),
    9728          160 :                     &expected_result_at_lsn_20[idx]
    9729            4 :                 );
    9730          160 :                 assert_eq!(
    9731          160 :                     tline
    9732          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9733          160 :                         .await
    9734          160 :                         .unwrap(),
    9735          160 :                     &expected_result_at_lsn_10[idx]
    9736            4 :                 );
    9737            4 :             }
    9738           32 :         };
    9739            4 : 
    9740            4 :         verify_result().await;
    9741            4 : 
    9742            4 :         let cancel = CancellationToken::new();
    9743            4 :         let mut dryrun_flags = EnumSet::new();
    9744            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9745            4 : 
    9746            4 :         tline
    9747            4 :             .compact_with_gc(
    9748            4 :                 &cancel,
    9749            4 :                 CompactOptions {
    9750            4 :                     flags: dryrun_flags,
    9751            4 :                     ..Default::default()
    9752            4 :                 },
    9753            4 :                 &ctx,
    9754            4 :             )
    9755            4 :             .await
    9756            4 :             .unwrap();
    9757            4 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9758            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9759            4 :         verify_result().await;
    9760            4 : 
    9761            4 :         tline
    9762            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9763            4 :             .await
    9764            4 :             .unwrap();
    9765            4 :         verify_result().await;
    9766            4 : 
    9767            4 :         // compact again
    9768            4 :         tline
    9769            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9770            4 :             .await
    9771            4 :             .unwrap();
    9772            4 :         verify_result().await;
    9773            4 : 
    9774            4 :         Ok(())
    9775            4 :     }
    9776              : 
    9777              :     #[cfg(feature = "testing")]
    9778              :     #[tokio::test]
    9779            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9780            4 :         use models::CompactLsnRange;
    9781            4 : 
    9782            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9783            4 :         let (tenant, ctx) = harness.load().await;
    9784            4 : 
    9785          332 :         fn get_key(id: u32) -> Key {
    9786          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9787          332 :             key.field6 = id;
    9788          332 :             key
    9789          332 :         }
    9790            4 : 
    9791            4 :         let img_layer = (0..10)
    9792           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9793            4 :             .collect_vec();
    9794            4 : 
    9795            4 :         let delta1 = vec![
    9796            4 :             (
    9797            4 :                 get_key(1),
    9798            4 :                 Lsn(0x20),
    9799            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9800            4 :             ),
    9801            4 :             (
    9802            4 :                 get_key(2),
    9803            4 :                 Lsn(0x30),
    9804            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9805            4 :             ),
    9806            4 :             (
    9807            4 :                 get_key(3),
    9808            4 :                 Lsn(0x28),
    9809            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9810            4 :             ),
    9811            4 :             (
    9812            4 :                 get_key(3),
    9813            4 :                 Lsn(0x30),
    9814            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9815            4 :             ),
    9816            4 :             (
    9817            4 :                 get_key(3),
    9818            4 :                 Lsn(0x40),
    9819            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9820            4 :             ),
    9821            4 :         ];
    9822            4 :         let delta2 = vec![
    9823            4 :             (
    9824            4 :                 get_key(5),
    9825            4 :                 Lsn(0x20),
    9826            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9827            4 :             ),
    9828            4 :             (
    9829            4 :                 get_key(6),
    9830            4 :                 Lsn(0x20),
    9831            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9832            4 :             ),
    9833            4 :         ];
    9834            4 :         let delta3 = vec![
    9835            4 :             (
    9836            4 :                 get_key(8),
    9837            4 :                 Lsn(0x48),
    9838            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9839            4 :             ),
    9840            4 :             (
    9841            4 :                 get_key(9),
    9842            4 :                 Lsn(0x48),
    9843            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9844            4 :             ),
    9845            4 :         ];
    9846            4 : 
    9847            4 :         let parent_tline = tenant
    9848            4 :             .create_test_timeline_with_layers(
    9849            4 :                 TIMELINE_ID,
    9850            4 :                 Lsn(0x10),
    9851            4 :                 DEFAULT_PG_VERSION,
    9852            4 :                 &ctx,
    9853            4 :                 vec![],                       // delta layers
    9854            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9855            4 :                 Lsn(0x18),
    9856            4 :             )
    9857            4 :             .await?;
    9858            4 : 
    9859            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9860            4 : 
    9861            4 :         let branch_tline = tenant
    9862            4 :             .branch_timeline_test_with_layers(
    9863            4 :                 &parent_tline,
    9864            4 :                 NEW_TIMELINE_ID,
    9865            4 :                 Some(Lsn(0x18)),
    9866            4 :                 &ctx,
    9867            4 :                 vec![
    9868            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9869            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9870            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9871            4 :                 ], // delta layers
    9872            4 :                 vec![], // image layers
    9873            4 :                 Lsn(0x50),
    9874            4 :             )
    9875            4 :             .await?;
    9876            4 : 
    9877            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9878            4 : 
    9879            4 :         {
    9880            4 :             parent_tline
    9881            4 :                 .latest_gc_cutoff_lsn
    9882            4 :                 .lock_for_write()
    9883            4 :                 .store_and_unlock(Lsn(0x10))
    9884            4 :                 .wait()
    9885            4 :                 .await;
    9886            4 :             // Update GC info
    9887            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9888            4 :             *guard = GcInfo {
    9889            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9890            4 :                 cutoffs: GcCutoffs {
    9891            4 :                     time: Lsn(0x10),
    9892            4 :                     space: Lsn(0x10),
    9893            4 :                 },
    9894            4 :                 leases: Default::default(),
    9895            4 :                 within_ancestor_pitr: false,
    9896            4 :             };
    9897            4 :         }
    9898            4 : 
    9899            4 :         {
    9900            4 :             branch_tline
    9901            4 :                 .latest_gc_cutoff_lsn
    9902            4 :                 .lock_for_write()
    9903            4 :                 .store_and_unlock(Lsn(0x50))
    9904            4 :                 .wait()
    9905            4 :                 .await;
    9906            4 :             // Update GC info
    9907            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9908            4 :             *guard = GcInfo {
    9909            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9910            4 :                 cutoffs: GcCutoffs {
    9911            4 :                     time: Lsn(0x50),
    9912            4 :                     space: Lsn(0x50),
    9913            4 :                 },
    9914            4 :                 leases: Default::default(),
    9915            4 :                 within_ancestor_pitr: false,
    9916            4 :             };
    9917            4 :         }
    9918            4 : 
    9919            4 :         let expected_result_at_gc_horizon = [
    9920            4 :             Bytes::from_static(b"value 0@0x10"),
    9921            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9922            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9923            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9924            4 :             Bytes::from_static(b"value 4@0x10"),
    9925            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9926            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9927            4 :             Bytes::from_static(b"value 7@0x10"),
    9928            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9929            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9930            4 :         ];
    9931            4 : 
    9932            4 :         let expected_result_at_lsn_40 = [
    9933            4 :             Bytes::from_static(b"value 0@0x10"),
    9934            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9935            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9936            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9937            4 :             Bytes::from_static(b"value 4@0x10"),
    9938            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9939            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9940            4 :             Bytes::from_static(b"value 7@0x10"),
    9941            4 :             Bytes::from_static(b"value 8@0x10"),
    9942            4 :             Bytes::from_static(b"value 9@0x10"),
    9943            4 :         ];
    9944            4 : 
    9945           12 :         let verify_result = || async {
    9946          132 :             for idx in 0..10 {
    9947          120 :                 assert_eq!(
    9948          120 :                     branch_tline
    9949          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9950          120 :                         .await
    9951          120 :                         .unwrap(),
    9952          120 :                     &expected_result_at_gc_horizon[idx]
    9953            4 :                 );
    9954          120 :                 assert_eq!(
    9955          120 :                     branch_tline
    9956          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9957          120 :                         .await
    9958          120 :                         .unwrap(),
    9959          120 :                     &expected_result_at_lsn_40[idx]
    9960            4 :                 );
    9961            4 :             }
    9962           24 :         };
    9963            4 : 
    9964            4 :         verify_result().await;
    9965            4 : 
    9966            4 :         let cancel = CancellationToken::new();
    9967            4 :         branch_tline
    9968            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9969            4 :             .await
    9970            4 :             .unwrap();
    9971            4 : 
    9972            4 :         verify_result().await;
    9973            4 : 
    9974            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
    9975            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
    9976            4 :         branch_tline
    9977            4 :             .compact_with_gc(
    9978            4 :                 &cancel,
    9979            4 :                 CompactOptions {
    9980            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
    9981            4 :                     ..Default::default()
    9982            4 :                 },
    9983            4 :                 &ctx,
    9984            4 :             )
    9985            4 :             .await
    9986            4 :             .unwrap();
    9987            4 : 
    9988            4 :         verify_result().await;
    9989            4 : 
    9990            4 :         Ok(())
    9991            4 :     }
    9992              : 
    9993              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9994              :     // Create an image arrangement where we have to read at different LSN ranges
    9995              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9996              :     // a delta layer. Like so:
    9997              :     //
    9998              :     //     A      B
    9999              :     // +----------------+ -> delta_layer
   10000              :     // |                |                           ^ lsn
   10001              :     // |       =========|-> nested_image_layer      |
   10002              :     // |       C        |                           |
   10003              :     // +----------------+                           |
   10004              :     // ======== -> baseline_image_layer             +-------> key
   10005              :     //
   10006              :     //
   10007              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10008              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10009              :     #[cfg(feature = "testing")]
   10010              :     #[tokio::test]
   10011            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10012            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10013            4 :         let (tenant, ctx) = harness.load().await;
   10014            4 : 
   10015            4 :         let will_init_keys = [2, 6];
   10016           88 :         fn get_key(id: u32) -> Key {
   10017           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10018           88 :             key.field6 = id;
   10019           88 :             key
   10020           88 :         }
   10021            4 : 
   10022            4 :         let mut expected_key_values = HashMap::new();
   10023            4 : 
   10024            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10025            4 :         let mut baseline_img_layer = Vec::new();
   10026           24 :         for i in 0..5 {
   10027           20 :             let key = get_key(i);
   10028           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10029           20 : 
   10030           20 :             let removed = expected_key_values.insert(key, value.clone());
   10031           20 :             assert!(removed.is_none());
   10032            4 : 
   10033           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10034            4 :         }
   10035            4 : 
   10036            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10037            4 :         let mut nested_img_layer = Vec::new();
   10038           24 :         for i in 5..10 {
   10039           20 :             let key = get_key(i);
   10040           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10041           20 : 
   10042           20 :             let removed = expected_key_values.insert(key, value.clone());
   10043           20 :             assert!(removed.is_none());
   10044            4 : 
   10045           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10046            4 :         }
   10047            4 : 
   10048            4 :         let mut delta_layer_spec = Vec::default();
   10049            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10050            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10051            4 : 
   10052           44 :         for i in 0..10 {
   10053           40 :             let key = get_key(i);
   10054           40 :             let key_in_nested = nested_img_layer
   10055           40 :                 .iter()
   10056          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10057           40 :             let lsn = {
   10058           40 :                 if key_in_nested {
   10059           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10060            4 :                 } else {
   10061           20 :                     delta_layer_start_lsn
   10062            4 :                 }
   10063            4 :             };
   10064            4 : 
   10065           40 :             let will_init = will_init_keys.contains(&i);
   10066           40 :             if will_init {
   10067            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10068            8 : 
   10069            8 :                 expected_key_values.insert(key, "".to_string());
   10070           32 :             } else {
   10071           32 :                 let delta = format!("@{lsn}");
   10072           32 :                 delta_layer_spec.push((
   10073           32 :                     key,
   10074           32 :                     lsn,
   10075           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10076           32 :                 ));
   10077           32 : 
   10078           32 :                 expected_key_values
   10079           32 :                     .get_mut(&key)
   10080           32 :                     .expect("An image exists for each key")
   10081           32 :                     .push_str(delta.as_str());
   10082           32 :             }
   10083           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10084            4 :         }
   10085            4 : 
   10086            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10087            4 : 
   10088            4 :         assert!(
   10089            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10090            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10091            4 :         );
   10092            4 : 
   10093            4 :         let tline = tenant
   10094            4 :             .create_test_timeline_with_layers(
   10095            4 :                 TIMELINE_ID,
   10096            4 :                 baseline_image_layer_lsn,
   10097            4 :                 DEFAULT_PG_VERSION,
   10098            4 :                 &ctx,
   10099            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10100            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10101            4 :                     delta_layer_spec,
   10102            4 :                 )], // delta layers
   10103            4 :                 vec![
   10104            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10105            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10106            4 :                 ], // image layers
   10107            4 :                 delta_layer_end_lsn,
   10108            4 :             )
   10109            4 :             .await?;
   10110            4 : 
   10111            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10112            4 :         let results = tline
   10113            4 :             .get_vectored(
   10114            4 :                 keyspace,
   10115            4 :                 delta_layer_end_lsn,
   10116            4 :                 IoConcurrency::sequential(),
   10117            4 :                 &ctx,
   10118            4 :             )
   10119            4 :             .await
   10120            4 :             .expect("No vectored errors");
   10121           44 :         for (key, res) in results {
   10122           40 :             let value = res.expect("No key errors");
   10123           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10124           40 :             assert_eq!(value, Bytes::from(expected_value));
   10125            4 :         }
   10126            4 : 
   10127            4 :         Ok(())
   10128            4 :     }
   10129              : 
   10130          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10131          428 :         (
   10132          428 :             k1.is_delta,
   10133          428 :             k1.key_range.start,
   10134          428 :             k1.key_range.end,
   10135          428 :             k1.lsn_range.start,
   10136          428 :             k1.lsn_range.end,
   10137          428 :         )
   10138          428 :             .cmp(&(
   10139          428 :                 k2.is_delta,
   10140          428 :                 k2.key_range.start,
   10141          428 :                 k2.key_range.end,
   10142          428 :                 k2.lsn_range.start,
   10143          428 :                 k2.lsn_range.end,
   10144          428 :             ))
   10145          428 :     }
   10146              : 
   10147           48 :     async fn inspect_and_sort(
   10148           48 :         tline: &Arc<Timeline>,
   10149           48 :         filter: Option<std::ops::Range<Key>>,
   10150           48 :     ) -> Vec<PersistentLayerKey> {
   10151           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10152           48 :         if let Some(filter) = filter {
   10153          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10154           44 :         }
   10155           48 :         all_layers.sort_by(sort_layer_key);
   10156           48 :         all_layers
   10157           48 :     }
   10158              : 
   10159              :     #[cfg(feature = "testing")]
   10160           44 :     fn check_layer_map_key_eq(
   10161           44 :         mut left: Vec<PersistentLayerKey>,
   10162           44 :         mut right: Vec<PersistentLayerKey>,
   10163           44 :     ) {
   10164           44 :         left.sort_by(sort_layer_key);
   10165           44 :         right.sort_by(sort_layer_key);
   10166           44 :         if left != right {
   10167            0 :             eprintln!("---LEFT---");
   10168            0 :             for left in left.iter() {
   10169            0 :                 eprintln!("{}", left);
   10170            0 :             }
   10171            0 :             eprintln!("---RIGHT---");
   10172            0 :             for right in right.iter() {
   10173            0 :                 eprintln!("{}", right);
   10174            0 :             }
   10175            0 :             assert_eq!(left, right);
   10176           44 :         }
   10177           44 :     }
   10178              : 
   10179              :     #[cfg(feature = "testing")]
   10180              :     #[tokio::test]
   10181            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10182            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10183            4 :         let (tenant, ctx) = harness.load().await;
   10184            4 : 
   10185          364 :         fn get_key(id: u32) -> Key {
   10186          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10187          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10188          364 :             key.field6 = id;
   10189          364 :             key
   10190          364 :         }
   10191            4 : 
   10192            4 :         // img layer at 0x10
   10193            4 :         let img_layer = (0..10)
   10194           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10195            4 :             .collect_vec();
   10196            4 : 
   10197            4 :         let delta1 = vec![
   10198            4 :             (
   10199            4 :                 get_key(1),
   10200            4 :                 Lsn(0x20),
   10201            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10202            4 :             ),
   10203            4 :             (
   10204            4 :                 get_key(2),
   10205            4 :                 Lsn(0x30),
   10206            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10207            4 :             ),
   10208            4 :             (
   10209            4 :                 get_key(3),
   10210            4 :                 Lsn(0x40),
   10211            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10212            4 :             ),
   10213            4 :         ];
   10214            4 :         let delta2 = vec![
   10215            4 :             (
   10216            4 :                 get_key(5),
   10217            4 :                 Lsn(0x20),
   10218            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10219            4 :             ),
   10220            4 :             (
   10221            4 :                 get_key(6),
   10222            4 :                 Lsn(0x20),
   10223            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10224            4 :             ),
   10225            4 :         ];
   10226            4 :         let delta3 = vec![
   10227            4 :             (
   10228            4 :                 get_key(8),
   10229            4 :                 Lsn(0x48),
   10230            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10231            4 :             ),
   10232            4 :             (
   10233            4 :                 get_key(9),
   10234            4 :                 Lsn(0x48),
   10235            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10236            4 :             ),
   10237            4 :         ];
   10238            4 : 
   10239            4 :         let tline = tenant
   10240            4 :             .create_test_timeline_with_layers(
   10241            4 :                 TIMELINE_ID,
   10242            4 :                 Lsn(0x10),
   10243            4 :                 DEFAULT_PG_VERSION,
   10244            4 :                 &ctx,
   10245            4 :                 vec![
   10246            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10247            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10248            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10249            4 :                 ], // delta layers
   10250            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10251            4 :                 Lsn(0x50),
   10252            4 :             )
   10253            4 :             .await?;
   10254            4 : 
   10255            4 :         {
   10256            4 :             tline
   10257            4 :                 .latest_gc_cutoff_lsn
   10258            4 :                 .lock_for_write()
   10259            4 :                 .store_and_unlock(Lsn(0x30))
   10260            4 :                 .wait()
   10261            4 :                 .await;
   10262            4 :             // Update GC info
   10263            4 :             let mut guard = tline.gc_info.write().unwrap();
   10264            4 :             *guard = GcInfo {
   10265            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10266            4 :                 cutoffs: GcCutoffs {
   10267            4 :                     time: Lsn(0x30),
   10268            4 :                     space: Lsn(0x30),
   10269            4 :                 },
   10270            4 :                 leases: Default::default(),
   10271            4 :                 within_ancestor_pitr: false,
   10272            4 :             };
   10273            4 :         }
   10274            4 : 
   10275            4 :         let cancel = CancellationToken::new();
   10276            4 : 
   10277            4 :         // Do a partial compaction on key range 0..2
   10278            4 :         tline
   10279            4 :             .compact_with_gc(
   10280            4 :                 &cancel,
   10281            4 :                 CompactOptions {
   10282            4 :                     flags: EnumSet::new(),
   10283            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10284            4 :                     ..Default::default()
   10285            4 :                 },
   10286            4 :                 &ctx,
   10287            4 :             )
   10288            4 :             .await
   10289            4 :             .unwrap();
   10290            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10291            4 :         check_layer_map_key_eq(
   10292            4 :             all_layers,
   10293            4 :             vec![
   10294            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10295            4 :                 PersistentLayerKey {
   10296            4 :                     key_range: get_key(0)..get_key(2),
   10297            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10298            4 :                     is_delta: false,
   10299            4 :                 },
   10300            4 :                 PersistentLayerKey {
   10301            4 :                     key_range: get_key(0)..get_key(10),
   10302            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10303            4 :                     is_delta: false,
   10304            4 :                 },
   10305            4 :                 // delta1 is split and the second part is rewritten
   10306            4 :                 PersistentLayerKey {
   10307            4 :                     key_range: get_key(2)..get_key(4),
   10308            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10309            4 :                     is_delta: true,
   10310            4 :                 },
   10311            4 :                 PersistentLayerKey {
   10312            4 :                     key_range: get_key(5)..get_key(7),
   10313            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10314            4 :                     is_delta: true,
   10315            4 :                 },
   10316            4 :                 PersistentLayerKey {
   10317            4 :                     key_range: get_key(8)..get_key(10),
   10318            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10319            4 :                     is_delta: true,
   10320            4 :                 },
   10321            4 :             ],
   10322            4 :         );
   10323            4 : 
   10324            4 :         // Do a partial compaction on key range 2..4
   10325            4 :         tline
   10326            4 :             .compact_with_gc(
   10327            4 :                 &cancel,
   10328            4 :                 CompactOptions {
   10329            4 :                     flags: EnumSet::new(),
   10330            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10331            4 :                     ..Default::default()
   10332            4 :                 },
   10333            4 :                 &ctx,
   10334            4 :             )
   10335            4 :             .await
   10336            4 :             .unwrap();
   10337            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10338            4 :         check_layer_map_key_eq(
   10339            4 :             all_layers,
   10340            4 :             vec![
   10341            4 :                 PersistentLayerKey {
   10342            4 :                     key_range: get_key(0)..get_key(2),
   10343            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10344            4 :                     is_delta: false,
   10345            4 :                 },
   10346            4 :                 PersistentLayerKey {
   10347            4 :                     key_range: get_key(0)..get_key(10),
   10348            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10349            4 :                     is_delta: false,
   10350            4 :                 },
   10351            4 :                 // image layer generated for the compaction range 2-4
   10352            4 :                 PersistentLayerKey {
   10353            4 :                     key_range: get_key(2)..get_key(4),
   10354            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10355            4 :                     is_delta: false,
   10356            4 :                 },
   10357            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10358            4 :                 PersistentLayerKey {
   10359            4 :                     key_range: get_key(2)..get_key(4),
   10360            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10361            4 :                     is_delta: true,
   10362            4 :                 },
   10363            4 :                 PersistentLayerKey {
   10364            4 :                     key_range: get_key(5)..get_key(7),
   10365            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10366            4 :                     is_delta: true,
   10367            4 :                 },
   10368            4 :                 PersistentLayerKey {
   10369            4 :                     key_range: get_key(8)..get_key(10),
   10370            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10371            4 :                     is_delta: true,
   10372            4 :                 },
   10373            4 :             ],
   10374            4 :         );
   10375            4 : 
   10376            4 :         // Do a partial compaction on key range 4..9
   10377            4 :         tline
   10378            4 :             .compact_with_gc(
   10379            4 :                 &cancel,
   10380            4 :                 CompactOptions {
   10381            4 :                     flags: EnumSet::new(),
   10382            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10383            4 :                     ..Default::default()
   10384            4 :                 },
   10385            4 :                 &ctx,
   10386            4 :             )
   10387            4 :             .await
   10388            4 :             .unwrap();
   10389            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10390            4 :         check_layer_map_key_eq(
   10391            4 :             all_layers,
   10392            4 :             vec![
   10393            4 :                 PersistentLayerKey {
   10394            4 :                     key_range: get_key(0)..get_key(2),
   10395            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10396            4 :                     is_delta: false,
   10397            4 :                 },
   10398            4 :                 PersistentLayerKey {
   10399            4 :                     key_range: get_key(0)..get_key(10),
   10400            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10401            4 :                     is_delta: false,
   10402            4 :                 },
   10403            4 :                 PersistentLayerKey {
   10404            4 :                     key_range: get_key(2)..get_key(4),
   10405            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10406            4 :                     is_delta: false,
   10407            4 :                 },
   10408            4 :                 PersistentLayerKey {
   10409            4 :                     key_range: get_key(2)..get_key(4),
   10410            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10411            4 :                     is_delta: true,
   10412            4 :                 },
   10413            4 :                 // image layer generated for this compaction range
   10414            4 :                 PersistentLayerKey {
   10415            4 :                     key_range: get_key(4)..get_key(9),
   10416            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10417            4 :                     is_delta: false,
   10418            4 :                 },
   10419            4 :                 PersistentLayerKey {
   10420            4 :                     key_range: get_key(8)..get_key(10),
   10421            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10422            4 :                     is_delta: true,
   10423            4 :                 },
   10424            4 :             ],
   10425            4 :         );
   10426            4 : 
   10427            4 :         // Do a partial compaction on key range 9..10
   10428            4 :         tline
   10429            4 :             .compact_with_gc(
   10430            4 :                 &cancel,
   10431            4 :                 CompactOptions {
   10432            4 :                     flags: EnumSet::new(),
   10433            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10434            4 :                     ..Default::default()
   10435            4 :                 },
   10436            4 :                 &ctx,
   10437            4 :             )
   10438            4 :             .await
   10439            4 :             .unwrap();
   10440            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10441            4 :         check_layer_map_key_eq(
   10442            4 :             all_layers,
   10443            4 :             vec![
   10444            4 :                 PersistentLayerKey {
   10445            4 :                     key_range: get_key(0)..get_key(2),
   10446            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10447            4 :                     is_delta: false,
   10448            4 :                 },
   10449            4 :                 PersistentLayerKey {
   10450            4 :                     key_range: get_key(0)..get_key(10),
   10451            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10452            4 :                     is_delta: false,
   10453            4 :                 },
   10454            4 :                 PersistentLayerKey {
   10455            4 :                     key_range: get_key(2)..get_key(4),
   10456            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10457            4 :                     is_delta: false,
   10458            4 :                 },
   10459            4 :                 PersistentLayerKey {
   10460            4 :                     key_range: get_key(2)..get_key(4),
   10461            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10462            4 :                     is_delta: true,
   10463            4 :                 },
   10464            4 :                 PersistentLayerKey {
   10465            4 :                     key_range: get_key(4)..get_key(9),
   10466            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10467            4 :                     is_delta: false,
   10468            4 :                 },
   10469            4 :                 // image layer generated for the compaction range
   10470            4 :                 PersistentLayerKey {
   10471            4 :                     key_range: get_key(9)..get_key(10),
   10472            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10473            4 :                     is_delta: false,
   10474            4 :                 },
   10475            4 :                 PersistentLayerKey {
   10476            4 :                     key_range: get_key(8)..get_key(10),
   10477            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10478            4 :                     is_delta: true,
   10479            4 :                 },
   10480            4 :             ],
   10481            4 :         );
   10482            4 : 
   10483            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10484            4 :         tline
   10485            4 :             .compact_with_gc(
   10486            4 :                 &cancel,
   10487            4 :                 CompactOptions {
   10488            4 :                     flags: EnumSet::new(),
   10489            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10490            4 :                     ..Default::default()
   10491            4 :                 },
   10492            4 :                 &ctx,
   10493            4 :             )
   10494            4 :             .await
   10495            4 :             .unwrap();
   10496            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10497            4 :         check_layer_map_key_eq(
   10498            4 :             all_layers,
   10499            4 :             vec![
   10500            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10501            4 :                 PersistentLayerKey {
   10502            4 :                     key_range: get_key(0)..get_key(10),
   10503            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10504            4 :                     is_delta: false,
   10505            4 :                 },
   10506            4 :                 PersistentLayerKey {
   10507            4 :                     key_range: get_key(2)..get_key(4),
   10508            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10509            4 :                     is_delta: true,
   10510            4 :                 },
   10511            4 :                 PersistentLayerKey {
   10512            4 :                     key_range: get_key(8)..get_key(10),
   10513            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10514            4 :                     is_delta: true,
   10515            4 :                 },
   10516            4 :             ],
   10517            4 :         );
   10518            4 :         Ok(())
   10519            4 :     }
   10520              : 
   10521              :     #[cfg(feature = "testing")]
   10522              :     #[tokio::test]
   10523            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10524            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10525            4 :             .await
   10526            4 :             .unwrap();
   10527            4 :         let (tenant, ctx) = harness.load().await;
   10528            4 :         let tline_parent = tenant
   10529            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10530            4 :             .await
   10531            4 :             .unwrap();
   10532            4 :         let tline_child = tenant
   10533            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10534            4 :             .await
   10535            4 :             .unwrap();
   10536            4 :         {
   10537            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10538            4 :             assert_eq!(
   10539            4 :                 gc_info_parent.retain_lsns,
   10540            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10541            4 :             );
   10542            4 :         }
   10543            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10544            4 :         tline_child
   10545            4 :             .remote_client
   10546            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10547            4 :             .unwrap();
   10548            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10549            4 :         offload_timeline(&tenant, &tline_child)
   10550            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10551            4 :             .await.unwrap();
   10552            4 :         let child_timeline_id = tline_child.timeline_id;
   10553            4 :         Arc::try_unwrap(tline_child).unwrap();
   10554            4 : 
   10555            4 :         {
   10556            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10557            4 :             assert_eq!(
   10558            4 :                 gc_info_parent.retain_lsns,
   10559            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10560            4 :             );
   10561            4 :         }
   10562            4 : 
   10563            4 :         tenant
   10564            4 :             .get_offloaded_timeline(child_timeline_id)
   10565            4 :             .unwrap()
   10566            4 :             .defuse_for_tenant_drop();
   10567            4 : 
   10568            4 :         Ok(())
   10569            4 :     }
   10570              : 
   10571              :     #[cfg(feature = "testing")]
   10572              :     #[tokio::test]
   10573            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10574            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10575            4 :         let (tenant, ctx) = harness.load().await;
   10576            4 : 
   10577          592 :         fn get_key(id: u32) -> Key {
   10578          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10579          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10580          592 :             key.field6 = id;
   10581          592 :             key
   10582          592 :         }
   10583            4 : 
   10584            4 :         let img_layer = (0..10)
   10585           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10586            4 :             .collect_vec();
   10587            4 : 
   10588            4 :         let delta1 = vec![(
   10589            4 :             get_key(1),
   10590            4 :             Lsn(0x20),
   10591            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10592            4 :         )];
   10593            4 :         let delta4 = vec![(
   10594            4 :             get_key(1),
   10595            4 :             Lsn(0x28),
   10596            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10597            4 :         )];
   10598            4 :         let delta2 = vec![
   10599            4 :             (
   10600            4 :                 get_key(1),
   10601            4 :                 Lsn(0x30),
   10602            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10603            4 :             ),
   10604            4 :             (
   10605            4 :                 get_key(1),
   10606            4 :                 Lsn(0x38),
   10607            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10608            4 :             ),
   10609            4 :         ];
   10610            4 :         let delta3 = vec![
   10611            4 :             (
   10612            4 :                 get_key(8),
   10613            4 :                 Lsn(0x48),
   10614            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10615            4 :             ),
   10616            4 :             (
   10617            4 :                 get_key(9),
   10618            4 :                 Lsn(0x48),
   10619            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10620            4 :             ),
   10621            4 :         ];
   10622            4 : 
   10623            4 :         let tline = tenant
   10624            4 :             .create_test_timeline_with_layers(
   10625            4 :                 TIMELINE_ID,
   10626            4 :                 Lsn(0x10),
   10627            4 :                 DEFAULT_PG_VERSION,
   10628            4 :                 &ctx,
   10629            4 :                 vec![
   10630            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10631            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10632            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10633            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10634            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10635            4 :                 ], // delta layers
   10636            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10637            4 :                 Lsn(0x50),
   10638            4 :             )
   10639            4 :             .await?;
   10640            4 :         {
   10641            4 :             tline
   10642            4 :                 .latest_gc_cutoff_lsn
   10643            4 :                 .lock_for_write()
   10644            4 :                 .store_and_unlock(Lsn(0x30))
   10645            4 :                 .wait()
   10646            4 :                 .await;
   10647            4 :             // Update GC info
   10648            4 :             let mut guard = tline.gc_info.write().unwrap();
   10649            4 :             *guard = GcInfo {
   10650            4 :                 retain_lsns: vec![
   10651            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10652            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10653            4 :                 ],
   10654            4 :                 cutoffs: GcCutoffs {
   10655            4 :                     time: Lsn(0x30),
   10656            4 :                     space: Lsn(0x30),
   10657            4 :                 },
   10658            4 :                 leases: Default::default(),
   10659            4 :                 within_ancestor_pitr: false,
   10660            4 :             };
   10661            4 :         }
   10662            4 : 
   10663            4 :         let expected_result = [
   10664            4 :             Bytes::from_static(b"value 0@0x10"),
   10665            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10666            4 :             Bytes::from_static(b"value 2@0x10"),
   10667            4 :             Bytes::from_static(b"value 3@0x10"),
   10668            4 :             Bytes::from_static(b"value 4@0x10"),
   10669            4 :             Bytes::from_static(b"value 5@0x10"),
   10670            4 :             Bytes::from_static(b"value 6@0x10"),
   10671            4 :             Bytes::from_static(b"value 7@0x10"),
   10672            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10673            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10674            4 :         ];
   10675            4 : 
   10676            4 :         let expected_result_at_gc_horizon = [
   10677            4 :             Bytes::from_static(b"value 0@0x10"),
   10678            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10679            4 :             Bytes::from_static(b"value 2@0x10"),
   10680            4 :             Bytes::from_static(b"value 3@0x10"),
   10681            4 :             Bytes::from_static(b"value 4@0x10"),
   10682            4 :             Bytes::from_static(b"value 5@0x10"),
   10683            4 :             Bytes::from_static(b"value 6@0x10"),
   10684            4 :             Bytes::from_static(b"value 7@0x10"),
   10685            4 :             Bytes::from_static(b"value 8@0x10"),
   10686            4 :             Bytes::from_static(b"value 9@0x10"),
   10687            4 :         ];
   10688            4 : 
   10689            4 :         let expected_result_at_lsn_20 = [
   10690            4 :             Bytes::from_static(b"value 0@0x10"),
   10691            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10692            4 :             Bytes::from_static(b"value 2@0x10"),
   10693            4 :             Bytes::from_static(b"value 3@0x10"),
   10694            4 :             Bytes::from_static(b"value 4@0x10"),
   10695            4 :             Bytes::from_static(b"value 5@0x10"),
   10696            4 :             Bytes::from_static(b"value 6@0x10"),
   10697            4 :             Bytes::from_static(b"value 7@0x10"),
   10698            4 :             Bytes::from_static(b"value 8@0x10"),
   10699            4 :             Bytes::from_static(b"value 9@0x10"),
   10700            4 :         ];
   10701            4 : 
   10702            4 :         let expected_result_at_lsn_10 = [
   10703            4 :             Bytes::from_static(b"value 0@0x10"),
   10704            4 :             Bytes::from_static(b"value 1@0x10"),
   10705            4 :             Bytes::from_static(b"value 2@0x10"),
   10706            4 :             Bytes::from_static(b"value 3@0x10"),
   10707            4 :             Bytes::from_static(b"value 4@0x10"),
   10708            4 :             Bytes::from_static(b"value 5@0x10"),
   10709            4 :             Bytes::from_static(b"value 6@0x10"),
   10710            4 :             Bytes::from_static(b"value 7@0x10"),
   10711            4 :             Bytes::from_static(b"value 8@0x10"),
   10712            4 :             Bytes::from_static(b"value 9@0x10"),
   10713            4 :         ];
   10714            4 : 
   10715           12 :         let verify_result = || async {
   10716           12 :             let gc_horizon = {
   10717           12 :                 let gc_info = tline.gc_info.read().unwrap();
   10718           12 :                 gc_info.cutoffs.time
   10719            4 :             };
   10720          132 :             for idx in 0..10 {
   10721          120 :                 assert_eq!(
   10722          120 :                     tline
   10723          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10724          120 :                         .await
   10725          120 :                         .unwrap(),
   10726          120 :                     &expected_result[idx]
   10727            4 :                 );
   10728          120 :                 assert_eq!(
   10729          120 :                     tline
   10730          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10731          120 :                         .await
   10732          120 :                         .unwrap(),
   10733          120 :                     &expected_result_at_gc_horizon[idx]
   10734            4 :                 );
   10735          120 :                 assert_eq!(
   10736          120 :                     tline
   10737          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10738          120 :                         .await
   10739          120 :                         .unwrap(),
   10740          120 :                     &expected_result_at_lsn_20[idx]
   10741            4 :                 );
   10742          120 :                 assert_eq!(
   10743          120 :                     tline
   10744          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10745          120 :                         .await
   10746          120 :                         .unwrap(),
   10747          120 :                     &expected_result_at_lsn_10[idx]
   10748            4 :                 );
   10749            4 :             }
   10750           24 :         };
   10751            4 : 
   10752            4 :         verify_result().await;
   10753            4 : 
   10754            4 :         let cancel = CancellationToken::new();
   10755            4 :         tline
   10756            4 :             .compact_with_gc(
   10757            4 :                 &cancel,
   10758            4 :                 CompactOptions {
   10759            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10760            4 :                     ..Default::default()
   10761            4 :                 },
   10762            4 :                 &ctx,
   10763            4 :             )
   10764            4 :             .await
   10765            4 :             .unwrap();
   10766            4 :         verify_result().await;
   10767            4 : 
   10768            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10769            4 :         check_layer_map_key_eq(
   10770            4 :             all_layers,
   10771            4 :             vec![
   10772            4 :                 // The original image layer, not compacted
   10773            4 :                 PersistentLayerKey {
   10774            4 :                     key_range: get_key(0)..get_key(10),
   10775            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10776            4 :                     is_delta: false,
   10777            4 :                 },
   10778            4 :                 // Delta layer below the specified above_lsn not compacted
   10779            4 :                 PersistentLayerKey {
   10780            4 :                     key_range: get_key(1)..get_key(2),
   10781            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10782            4 :                     is_delta: true,
   10783            4 :                 },
   10784            4 :                 // Delta layer compacted above the LSN
   10785            4 :                 PersistentLayerKey {
   10786            4 :                     key_range: get_key(1)..get_key(10),
   10787            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10788            4 :                     is_delta: true,
   10789            4 :                 },
   10790            4 :             ],
   10791            4 :         );
   10792            4 : 
   10793            4 :         // compact again
   10794            4 :         tline
   10795            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10796            4 :             .await
   10797            4 :             .unwrap();
   10798            4 :         verify_result().await;
   10799            4 : 
   10800            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10801            4 :         check_layer_map_key_eq(
   10802            4 :             all_layers,
   10803            4 :             vec![
   10804            4 :                 // The compacted image layer (full key range)
   10805            4 :                 PersistentLayerKey {
   10806            4 :                     key_range: Key::MIN..Key::MAX,
   10807            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10808            4 :                     is_delta: false,
   10809            4 :                 },
   10810            4 :                 // All other data in the delta layer
   10811            4 :                 PersistentLayerKey {
   10812            4 :                     key_range: get_key(1)..get_key(10),
   10813            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10814            4 :                     is_delta: true,
   10815            4 :                 },
   10816            4 :             ],
   10817            4 :         );
   10818            4 : 
   10819            4 :         Ok(())
   10820            4 :     }
   10821              : 
   10822              :     #[cfg(feature = "testing")]
   10823              :     #[tokio::test]
   10824            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   10825            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   10826            4 :         let (tenant, ctx) = harness.load().await;
   10827            4 : 
   10828         1016 :         fn get_key(id: u32) -> Key {
   10829         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10830         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10831         1016 :             key.field6 = id;
   10832         1016 :             key
   10833         1016 :         }
   10834            4 : 
   10835            4 :         let img_layer = (0..10)
   10836           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10837            4 :             .collect_vec();
   10838            4 : 
   10839            4 :         let delta1 = vec![(
   10840            4 :             get_key(1),
   10841            4 :             Lsn(0x20),
   10842            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10843            4 :         )];
   10844            4 :         let delta4 = vec![(
   10845            4 :             get_key(1),
   10846            4 :             Lsn(0x28),
   10847            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10848            4 :         )];
   10849            4 :         let delta2 = vec![
   10850            4 :             (
   10851            4 :                 get_key(1),
   10852            4 :                 Lsn(0x30),
   10853            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10854            4 :             ),
   10855            4 :             (
   10856            4 :                 get_key(1),
   10857            4 :                 Lsn(0x38),
   10858            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10859            4 :             ),
   10860            4 :         ];
   10861            4 :         let delta3 = vec![
   10862            4 :             (
   10863            4 :                 get_key(8),
   10864            4 :                 Lsn(0x48),
   10865            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10866            4 :             ),
   10867            4 :             (
   10868            4 :                 get_key(9),
   10869            4 :                 Lsn(0x48),
   10870            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10871            4 :             ),
   10872            4 :         ];
   10873            4 : 
   10874            4 :         let tline = tenant
   10875            4 :             .create_test_timeline_with_layers(
   10876            4 :                 TIMELINE_ID,
   10877            4 :                 Lsn(0x10),
   10878            4 :                 DEFAULT_PG_VERSION,
   10879            4 :                 &ctx,
   10880            4 :                 vec![
   10881            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10882            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10883            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10884            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10885            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10886            4 :                 ], // delta layers
   10887            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10888            4 :                 Lsn(0x50),
   10889            4 :             )
   10890            4 :             .await?;
   10891            4 :         {
   10892            4 :             tline
   10893            4 :                 .latest_gc_cutoff_lsn
   10894            4 :                 .lock_for_write()
   10895            4 :                 .store_and_unlock(Lsn(0x30))
   10896            4 :                 .wait()
   10897            4 :                 .await;
   10898            4 :             // Update GC info
   10899            4 :             let mut guard = tline.gc_info.write().unwrap();
   10900            4 :             *guard = GcInfo {
   10901            4 :                 retain_lsns: vec![
   10902            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10903            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10904            4 :                 ],
   10905            4 :                 cutoffs: GcCutoffs {
   10906            4 :                     time: Lsn(0x30),
   10907            4 :                     space: Lsn(0x30),
   10908            4 :                 },
   10909            4 :                 leases: Default::default(),
   10910            4 :                 within_ancestor_pitr: false,
   10911            4 :             };
   10912            4 :         }
   10913            4 : 
   10914            4 :         let expected_result = [
   10915            4 :             Bytes::from_static(b"value 0@0x10"),
   10916            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10917            4 :             Bytes::from_static(b"value 2@0x10"),
   10918            4 :             Bytes::from_static(b"value 3@0x10"),
   10919            4 :             Bytes::from_static(b"value 4@0x10"),
   10920            4 :             Bytes::from_static(b"value 5@0x10"),
   10921            4 :             Bytes::from_static(b"value 6@0x10"),
   10922            4 :             Bytes::from_static(b"value 7@0x10"),
   10923            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10924            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10925            4 :         ];
   10926            4 : 
   10927            4 :         let expected_result_at_gc_horizon = [
   10928            4 :             Bytes::from_static(b"value 0@0x10"),
   10929            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10930            4 :             Bytes::from_static(b"value 2@0x10"),
   10931            4 :             Bytes::from_static(b"value 3@0x10"),
   10932            4 :             Bytes::from_static(b"value 4@0x10"),
   10933            4 :             Bytes::from_static(b"value 5@0x10"),
   10934            4 :             Bytes::from_static(b"value 6@0x10"),
   10935            4 :             Bytes::from_static(b"value 7@0x10"),
   10936            4 :             Bytes::from_static(b"value 8@0x10"),
   10937            4 :             Bytes::from_static(b"value 9@0x10"),
   10938            4 :         ];
   10939            4 : 
   10940            4 :         let expected_result_at_lsn_20 = [
   10941            4 :             Bytes::from_static(b"value 0@0x10"),
   10942            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10943            4 :             Bytes::from_static(b"value 2@0x10"),
   10944            4 :             Bytes::from_static(b"value 3@0x10"),
   10945            4 :             Bytes::from_static(b"value 4@0x10"),
   10946            4 :             Bytes::from_static(b"value 5@0x10"),
   10947            4 :             Bytes::from_static(b"value 6@0x10"),
   10948            4 :             Bytes::from_static(b"value 7@0x10"),
   10949            4 :             Bytes::from_static(b"value 8@0x10"),
   10950            4 :             Bytes::from_static(b"value 9@0x10"),
   10951            4 :         ];
   10952            4 : 
   10953            4 :         let expected_result_at_lsn_10 = [
   10954            4 :             Bytes::from_static(b"value 0@0x10"),
   10955            4 :             Bytes::from_static(b"value 1@0x10"),
   10956            4 :             Bytes::from_static(b"value 2@0x10"),
   10957            4 :             Bytes::from_static(b"value 3@0x10"),
   10958            4 :             Bytes::from_static(b"value 4@0x10"),
   10959            4 :             Bytes::from_static(b"value 5@0x10"),
   10960            4 :             Bytes::from_static(b"value 6@0x10"),
   10961            4 :             Bytes::from_static(b"value 7@0x10"),
   10962            4 :             Bytes::from_static(b"value 8@0x10"),
   10963            4 :             Bytes::from_static(b"value 9@0x10"),
   10964            4 :         ];
   10965            4 : 
   10966           20 :         let verify_result = || async {
   10967           20 :             let gc_horizon = {
   10968           20 :                 let gc_info = tline.gc_info.read().unwrap();
   10969           20 :                 gc_info.cutoffs.time
   10970            4 :             };
   10971          220 :             for idx in 0..10 {
   10972          200 :                 assert_eq!(
   10973          200 :                     tline
   10974          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10975          200 :                         .await
   10976          200 :                         .unwrap(),
   10977          200 :                     &expected_result[idx]
   10978            4 :                 );
   10979          200 :                 assert_eq!(
   10980          200 :                     tline
   10981          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10982          200 :                         .await
   10983          200 :                         .unwrap(),
   10984          200 :                     &expected_result_at_gc_horizon[idx]
   10985            4 :                 );
   10986          200 :                 assert_eq!(
   10987          200 :                     tline
   10988          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10989          200 :                         .await
   10990          200 :                         .unwrap(),
   10991          200 :                     &expected_result_at_lsn_20[idx]
   10992            4 :                 );
   10993          200 :                 assert_eq!(
   10994          200 :                     tline
   10995          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10996          200 :                         .await
   10997          200 :                         .unwrap(),
   10998          200 :                     &expected_result_at_lsn_10[idx]
   10999            4 :                 );
   11000            4 :             }
   11001           40 :         };
   11002            4 : 
   11003            4 :         verify_result().await;
   11004            4 : 
   11005            4 :         let cancel = CancellationToken::new();
   11006            4 : 
   11007            4 :         tline
   11008            4 :             .compact_with_gc(
   11009            4 :                 &cancel,
   11010            4 :                 CompactOptions {
   11011            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11012            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11013            4 :                     ..Default::default()
   11014            4 :                 },
   11015            4 :                 &ctx,
   11016            4 :             )
   11017            4 :             .await
   11018            4 :             .unwrap();
   11019            4 :         verify_result().await;
   11020            4 : 
   11021            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11022            4 :         check_layer_map_key_eq(
   11023            4 :             all_layers,
   11024            4 :             vec![
   11025            4 :                 // The original image layer, not compacted
   11026            4 :                 PersistentLayerKey {
   11027            4 :                     key_range: get_key(0)..get_key(10),
   11028            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11029            4 :                     is_delta: false,
   11030            4 :                 },
   11031            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11032            4 :                 // the layer 0x28-0x30 into one.
   11033            4 :                 PersistentLayerKey {
   11034            4 :                     key_range: get_key(1)..get_key(2),
   11035            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11036            4 :                     is_delta: true,
   11037            4 :                 },
   11038            4 :                 // Above the upper bound and untouched
   11039            4 :                 PersistentLayerKey {
   11040            4 :                     key_range: get_key(1)..get_key(2),
   11041            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11042            4 :                     is_delta: true,
   11043            4 :                 },
   11044            4 :                 // This layer is untouched
   11045            4 :                 PersistentLayerKey {
   11046            4 :                     key_range: get_key(8)..get_key(10),
   11047            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11048            4 :                     is_delta: true,
   11049            4 :                 },
   11050            4 :             ],
   11051            4 :         );
   11052            4 : 
   11053            4 :         tline
   11054            4 :             .compact_with_gc(
   11055            4 :                 &cancel,
   11056            4 :                 CompactOptions {
   11057            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11058            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11059            4 :                     ..Default::default()
   11060            4 :                 },
   11061            4 :                 &ctx,
   11062            4 :             )
   11063            4 :             .await
   11064            4 :             .unwrap();
   11065            4 :         verify_result().await;
   11066            4 : 
   11067            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11068            4 :         check_layer_map_key_eq(
   11069            4 :             all_layers,
   11070            4 :             vec![
   11071            4 :                 // The original image layer, not compacted
   11072            4 :                 PersistentLayerKey {
   11073            4 :                     key_range: get_key(0)..get_key(10),
   11074            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11075            4 :                     is_delta: false,
   11076            4 :                 },
   11077            4 :                 // Not in the compaction key range, uncompacted
   11078            4 :                 PersistentLayerKey {
   11079            4 :                     key_range: get_key(1)..get_key(2),
   11080            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11081            4 :                     is_delta: true,
   11082            4 :                 },
   11083            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11084            4 :                 PersistentLayerKey {
   11085            4 :                     key_range: get_key(1)..get_key(2),
   11086            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11087            4 :                     is_delta: true,
   11088            4 :                 },
   11089            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11090            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11091            4 :                 // becomes 0x50.
   11092            4 :                 PersistentLayerKey {
   11093            4 :                     key_range: get_key(8)..get_key(10),
   11094            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11095            4 :                     is_delta: true,
   11096            4 :                 },
   11097            4 :             ],
   11098            4 :         );
   11099            4 : 
   11100            4 :         // compact again
   11101            4 :         tline
   11102            4 :             .compact_with_gc(
   11103            4 :                 &cancel,
   11104            4 :                 CompactOptions {
   11105            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11106            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11107            4 :                     ..Default::default()
   11108            4 :                 },
   11109            4 :                 &ctx,
   11110            4 :             )
   11111            4 :             .await
   11112            4 :             .unwrap();
   11113            4 :         verify_result().await;
   11114            4 : 
   11115            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11116            4 :         check_layer_map_key_eq(
   11117            4 :             all_layers,
   11118            4 :             vec![
   11119            4 :                 // The original image layer, not compacted
   11120            4 :                 PersistentLayerKey {
   11121            4 :                     key_range: get_key(0)..get_key(10),
   11122            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11123            4 :                     is_delta: false,
   11124            4 :                 },
   11125            4 :                 // The range gets compacted
   11126            4 :                 PersistentLayerKey {
   11127            4 :                     key_range: get_key(1)..get_key(2),
   11128            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11129            4 :                     is_delta: true,
   11130            4 :                 },
   11131            4 :                 // Not touched during this iteration of compaction
   11132            4 :                 PersistentLayerKey {
   11133            4 :                     key_range: get_key(8)..get_key(10),
   11134            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11135            4 :                     is_delta: true,
   11136            4 :                 },
   11137            4 :             ],
   11138            4 :         );
   11139            4 : 
   11140            4 :         // final full compaction
   11141            4 :         tline
   11142            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11143            4 :             .await
   11144            4 :             .unwrap();
   11145            4 :         verify_result().await;
   11146            4 : 
   11147            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11148            4 :         check_layer_map_key_eq(
   11149            4 :             all_layers,
   11150            4 :             vec![
   11151            4 :                 // The compacted image layer (full key range)
   11152            4 :                 PersistentLayerKey {
   11153            4 :                     key_range: Key::MIN..Key::MAX,
   11154            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11155            4 :                     is_delta: false,
   11156            4 :                 },
   11157            4 :                 // All other data in the delta layer
   11158            4 :                 PersistentLayerKey {
   11159            4 :                     key_range: get_key(1)..get_key(10),
   11160            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11161            4 :                     is_delta: true,
   11162            4 :                 },
   11163            4 :             ],
   11164            4 :         );
   11165            4 : 
   11166            4 :         Ok(())
   11167            4 :     }
   11168              : }
        

Generated by: LCOV version 2.1-beta