LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: f5f94ec0366b63fd2cbbe02edc2087dbd893d04d.info Lines: 76.1 % 7324 5571
Test Date: 2024-11-20 05:34:23 Functions: 58.6 % 428 251

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

Generated by: LCOV version 2.1-beta