LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: d3863ebe0efe476e2f785dedc32e86b3a6fbc249.info Lines: 76.1 % 7305 5557
Test Date: 2024-11-19 16:58:45 Functions: 58.8 % 427 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            3 :             .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            5 :             .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            6 :             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          173 :             .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          165 :             .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 :             .context("wait for timeline initial uploads to complete")?;
    2450              : 
    2451              :         // The creating task is responsible for activating the timeline.
    2452              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2453              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2454            0 :         let activated_timeline = match result {
    2455            0 :             CreateTimelineResult::Created(timeline) => {
    2456            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2457            0 :                 timeline
    2458              :             }
    2459            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2460            0 :                 info!(
    2461            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2462              :                 );
    2463            0 :                 timeline
    2464              :             }
    2465              :         };
    2466              : 
    2467            0 :         Ok(activated_timeline)
    2468            0 :     }
    2469              : 
    2470            0 :     pub(crate) async fn delete_timeline(
    2471            0 :         self: Arc<Self>,
    2472            0 :         timeline_id: TimelineId,
    2473            0 :     ) -> Result<(), DeleteTimelineError> {
    2474            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2475              : 
    2476            0 :         Ok(())
    2477            0 :     }
    2478              : 
    2479              :     /// perform one garbage collection iteration, removing old data files from disk.
    2480              :     /// this function is periodically called by gc task.
    2481              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2482              :     ///
    2483              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2484              :     ///
    2485              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2486              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2487              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2488              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2489              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2490              :     /// requires more history to be retained.
    2491              :     //
    2492          754 :     pub(crate) async fn gc_iteration(
    2493          754 :         &self,
    2494          754 :         target_timeline_id: Option<TimelineId>,
    2495          754 :         horizon: u64,
    2496          754 :         pitr: Duration,
    2497          754 :         cancel: &CancellationToken,
    2498          754 :         ctx: &RequestContext,
    2499          754 :     ) -> Result<GcResult, GcError> {
    2500          754 :         // Don't start doing work during shutdown
    2501          754 :         if let TenantState::Stopping { .. } = self.current_state() {
    2502            0 :             return Ok(GcResult::default());
    2503          754 :         }
    2504          754 : 
    2505          754 :         // there is a global allowed_error for this
    2506          754 :         if !self.is_active() {
    2507            0 :             return Err(GcError::NotActive);
    2508          754 :         }
    2509          754 : 
    2510          754 :         {
    2511          754 :             let conf = self.tenant_conf.load();
    2512          754 : 
    2513          754 :             if !conf.location.may_delete_layers_hint() {
    2514            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2515            0 :                 return Ok(GcResult::default());
    2516          754 :             }
    2517          754 : 
    2518          754 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2519          750 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2520          750 :                 return Ok(GcResult::default());
    2521            4 :             }
    2522              :         }
    2523              : 
    2524            4 :         let _guard = match self.gc_block.start().await {
    2525            4 :             Ok(guard) => guard,
    2526            0 :             Err(reasons) => {
    2527            0 :                 info!("Skipping GC: {reasons}");
    2528            0 :                 return Ok(GcResult::default());
    2529              :             }
    2530              :         };
    2531              : 
    2532            4 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2533            4 :             .await
    2534          754 :     }
    2535              : 
    2536              :     /// Perform one compaction iteration.
    2537              :     /// This function is periodically called by compactor task.
    2538              :     /// Also it can be explicitly requested per timeline through page server
    2539              :     /// api's 'compact' command.
    2540              :     ///
    2541              :     /// Returns whether we have pending compaction task.
    2542            0 :     async fn compaction_iteration(
    2543            0 :         self: &Arc<Self>,
    2544            0 :         cancel: &CancellationToken,
    2545            0 :         ctx: &RequestContext,
    2546            0 :     ) -> Result<bool, timeline::CompactionError> {
    2547            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2548            0 :         if !self.is_active() {
    2549            0 :             return Ok(false);
    2550            0 :         }
    2551            0 : 
    2552            0 :         {
    2553            0 :             let conf = self.tenant_conf.load();
    2554            0 :             if !conf.location.may_delete_layers_hint() || !conf.location.may_upload_layers_hint() {
    2555            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2556            0 :                 return Ok(false);
    2557            0 :             }
    2558            0 :         }
    2559            0 : 
    2560            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2561            0 :         // while holding the lock. Then drop the lock and actually perform the
    2562            0 :         // compactions.  We don't want to block everything else while the
    2563            0 :         // compaction runs.
    2564            0 :         let timelines_to_compact_or_offload;
    2565            0 :         {
    2566            0 :             let timelines = self.timelines.lock().unwrap();
    2567            0 :             timelines_to_compact_or_offload = timelines
    2568            0 :                 .iter()
    2569            0 :                 .filter_map(|(timeline_id, timeline)| {
    2570            0 :                     let (is_active, (can_offload, _)) =
    2571            0 :                         (timeline.is_active(), timeline.can_offload());
    2572            0 :                     let has_no_unoffloaded_children = {
    2573            0 :                         !timelines
    2574            0 :                             .iter()
    2575            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2576              :                     };
    2577            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2578            0 :                         || self
    2579            0 :                             .tenant_conf
    2580            0 :                             .load()
    2581            0 :                             .tenant_conf
    2582            0 :                             .timeline_offloading
    2583            0 :                             .unwrap_or_default();
    2584            0 :                     let can_offload =
    2585            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2586            0 :                     if (is_active, can_offload) == (false, false) {
    2587            0 :                         None
    2588              :                     } else {
    2589            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2590              :                     }
    2591            0 :                 })
    2592            0 :                 .collect::<Vec<_>>();
    2593            0 :             drop(timelines);
    2594            0 :         }
    2595            0 : 
    2596            0 :         // Before doing any I/O work, check our circuit breaker
    2597            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2598            0 :             info!("Skipping compaction due to previous failures");
    2599            0 :             return Ok(false);
    2600            0 :         }
    2601            0 : 
    2602            0 :         let mut has_pending_task = false;
    2603              : 
    2604            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2605              :         {
    2606            0 :             let pending_task_left = if *can_compact {
    2607              :                 Some(
    2608            0 :                     timeline
    2609            0 :                         .compact(cancel, EnumSet::empty(), ctx)
    2610            0 :                         .instrument(info_span!("compact_timeline", %timeline_id))
    2611            0 :                         .await
    2612            0 :                         .inspect_err(|e| match e {
    2613            0 :                             timeline::CompactionError::ShuttingDown => (),
    2614            0 :                             timeline::CompactionError::Offload(_) => {
    2615            0 :                                 // Failures to offload timelines do not trip the circuit breaker, because
    2616            0 :                                 // they do not do lots of writes the way compaction itself does: it is cheap
    2617            0 :                                 // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2618            0 :                             }
    2619            0 :                             timeline::CompactionError::Other(e) => {
    2620            0 :                                 self.compaction_circuit_breaker
    2621            0 :                                     .lock()
    2622            0 :                                     .unwrap()
    2623            0 :                                     .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2624            0 :                             }
    2625            0 :                         })?,
    2626              :                 )
    2627              :             } else {
    2628            0 :                 None
    2629              :             };
    2630            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    2631            0 :             if pending_task_left == Some(false) && *can_offload {
    2632            0 :                 offload_timeline(self, timeline)
    2633            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    2634            0 :                     .await?;
    2635            0 :             }
    2636              :         }
    2637              : 
    2638            0 :         self.compaction_circuit_breaker
    2639            0 :             .lock()
    2640            0 :             .unwrap()
    2641            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    2642            0 : 
    2643            0 :         Ok(has_pending_task)
    2644            0 :     }
    2645              : 
    2646              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    2647              :     // this happens during ingest: this background housekeeping is for freezing layers
    2648              :     // that are open but haven't been written to for some time.
    2649            0 :     async fn ingest_housekeeping(&self) {
    2650            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2651            0 :         // while holding the lock. Then drop the lock and actually perform the
    2652            0 :         // compactions.  We don't want to block everything else while the
    2653            0 :         // compaction runs.
    2654            0 :         let timelines = {
    2655            0 :             self.timelines
    2656            0 :                 .lock()
    2657            0 :                 .unwrap()
    2658            0 :                 .values()
    2659            0 :                 .filter_map(|timeline| {
    2660            0 :                     if timeline.is_active() {
    2661            0 :                         Some(timeline.clone())
    2662              :                     } else {
    2663            0 :                         None
    2664              :                     }
    2665            0 :                 })
    2666            0 :                 .collect::<Vec<_>>()
    2667              :         };
    2668              : 
    2669            0 :         for timeline in &timelines {
    2670            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    2671              :         }
    2672            0 :     }
    2673              : 
    2674            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    2675            0 :         let timelines = self.timelines.lock().unwrap();
    2676            0 :         !timelines
    2677            0 :             .iter()
    2678            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    2679            0 :     }
    2680              : 
    2681         1702 :     pub fn current_state(&self) -> TenantState {
    2682         1702 :         self.state.borrow().clone()
    2683         1702 :     }
    2684              : 
    2685          942 :     pub fn is_active(&self) -> bool {
    2686          942 :         self.current_state() == TenantState::Active
    2687          942 :     }
    2688              : 
    2689            0 :     pub fn generation(&self) -> Generation {
    2690            0 :         self.generation
    2691            0 :     }
    2692              : 
    2693            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    2694            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    2695            0 :     }
    2696              : 
    2697              :     /// Changes tenant status to active, unless shutdown was already requested.
    2698              :     ///
    2699              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    2700              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    2701            0 :     fn activate(
    2702            0 :         self: &Arc<Self>,
    2703            0 :         broker_client: BrokerClientChannel,
    2704            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    2705            0 :         ctx: &RequestContext,
    2706            0 :     ) {
    2707            0 :         span::debug_assert_current_span_has_tenant_id();
    2708            0 : 
    2709            0 :         let mut activating = false;
    2710            0 :         self.state.send_modify(|current_state| {
    2711              :             use pageserver_api::models::ActivatingFrom;
    2712            0 :             match &*current_state {
    2713              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    2714            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    2715              :                 }
    2716            0 :                 TenantState::Attaching => {
    2717            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    2718            0 :                 }
    2719            0 :             }
    2720            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    2721            0 :             activating = true;
    2722            0 :             // Continue outside the closure. We need to grab timelines.lock()
    2723            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    2724            0 :         });
    2725            0 : 
    2726            0 :         if activating {
    2727            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    2728            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    2729            0 :             let timelines_to_activate = timelines_accessor
    2730            0 :                 .values()
    2731            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    2732            0 : 
    2733            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    2734            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    2735            0 : 
    2736            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    2737            0 :             // down when they notice that the tenant is inactive.
    2738            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    2739            0 : 
    2740            0 :             let mut activated_timelines = 0;
    2741              : 
    2742            0 :             for timeline in timelines_to_activate {
    2743            0 :                 timeline.activate(
    2744            0 :                     self.clone(),
    2745            0 :                     broker_client.clone(),
    2746            0 :                     background_jobs_can_start,
    2747            0 :                     ctx,
    2748            0 :                 );
    2749            0 :                 activated_timelines += 1;
    2750            0 :             }
    2751              : 
    2752            0 :             self.state.send_modify(move |current_state| {
    2753            0 :                 assert!(
    2754            0 :                     matches!(current_state, TenantState::Activating(_)),
    2755            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    2756              :                 );
    2757            0 :                 *current_state = TenantState::Active;
    2758            0 : 
    2759            0 :                 let elapsed = self.constructed_at.elapsed();
    2760            0 :                 let total_timelines = timelines_accessor.len();
    2761            0 : 
    2762            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    2763            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    2764            0 :                 info!(
    2765            0 :                     since_creation_millis = elapsed.as_millis(),
    2766            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    2767            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    2768            0 :                     activated_timelines,
    2769            0 :                     total_timelines,
    2770            0 :                     post_state = <&'static str>::from(&*current_state),
    2771            0 :                     "activation attempt finished"
    2772              :                 );
    2773              : 
    2774            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    2775            0 :             });
    2776            0 :         }
    2777            0 :     }
    2778              : 
    2779              :     /// Shutdown the tenant and join all of the spawned tasks.
    2780              :     ///
    2781              :     /// The method caters for all use-cases:
    2782              :     /// - pageserver shutdown (freeze_and_flush == true)
    2783              :     /// - detach + ignore (freeze_and_flush == false)
    2784              :     ///
    2785              :     /// This will attempt to shutdown even if tenant is broken.
    2786              :     ///
    2787              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    2788              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    2789              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    2790              :     /// the ongoing shutdown.
    2791            6 :     async fn shutdown(
    2792            6 :         &self,
    2793            6 :         shutdown_progress: completion::Barrier,
    2794            6 :         shutdown_mode: timeline::ShutdownMode,
    2795            6 :     ) -> Result<(), completion::Barrier> {
    2796            6 :         span::debug_assert_current_span_has_tenant_id();
    2797              : 
    2798              :         // Set tenant (and its timlines) to Stoppping state.
    2799              :         //
    2800              :         // Since we can only transition into Stopping state after activation is complete,
    2801              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    2802              :         //
    2803              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    2804              :         // 1. Lock out any new requests to the tenants.
    2805              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    2806              :         // 3. Signal cancellation for other tenant background loops.
    2807              :         // 4. ???
    2808              :         //
    2809              :         // The waiting for the cancellation is not done uniformly.
    2810              :         // We certainly wait for WAL receivers to shut down.
    2811              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    2812              :         // But the tenant background loops are joined-on in our caller.
    2813              :         // It's mesed up.
    2814              :         // we just ignore the failure to stop
    2815              : 
    2816              :         // If we're still attaching, fire the cancellation token early to drop out: this
    2817              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    2818              :         // is very slow.
    2819            6 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    2820            0 :             self.cancel.cancel();
    2821            0 : 
    2822            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    2823            0 :             // are children of ours, so their flush loops will have shut down already
    2824            0 :             timeline::ShutdownMode::Hard
    2825              :         } else {
    2826            6 :             shutdown_mode
    2827              :         };
    2828              : 
    2829            6 :         match self.set_stopping(shutdown_progress, false, false).await {
    2830            6 :             Ok(()) => {}
    2831            0 :             Err(SetStoppingError::Broken) => {
    2832            0 :                 // assume that this is acceptable
    2833            0 :             }
    2834            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    2835            0 :                 // give caller the option to wait for this this shutdown
    2836            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    2837            0 :                 return Err(other);
    2838              :             }
    2839              :         };
    2840              : 
    2841            6 :         let mut js = tokio::task::JoinSet::new();
    2842            6 :         {
    2843            6 :             let timelines = self.timelines.lock().unwrap();
    2844            6 :             timelines.values().for_each(|timeline| {
    2845            6 :                 let timeline = Arc::clone(timeline);
    2846            6 :                 let timeline_id = timeline.timeline_id;
    2847            6 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    2848           10 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    2849            6 :             });
    2850            6 :         }
    2851            6 :         {
    2852            6 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    2853            6 :             timelines_offloaded.values().for_each(|timeline| {
    2854            0 :                 timeline.defuse_for_tenant_drop();
    2855            6 :             });
    2856            6 :         }
    2857            6 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    2858            6 :         tracing::info!("Waiting for timelines...");
    2859           12 :         while let Some(res) = js.join_next().await {
    2860            0 :             match res {
    2861            6 :                 Ok(()) => {}
    2862            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    2863            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    2864            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    2865              :             }
    2866              :         }
    2867              : 
    2868              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    2869              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    2870            6 :         tracing::debug!("Cancelling CancellationToken");
    2871            6 :         self.cancel.cancel();
    2872            6 : 
    2873            6 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    2874            6 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    2875            6 :         //
    2876            6 :         // this will additionally shutdown and await all timeline tasks.
    2877            6 :         tracing::debug!("Waiting for tasks...");
    2878            6 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    2879              : 
    2880            6 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    2881            6 :             walredo_mgr.shutdown().await;
    2882            0 :         }
    2883              : 
    2884              :         // Wait for any in-flight operations to complete
    2885            6 :         self.gate.close().await;
    2886              : 
    2887            6 :         remove_tenant_metrics(&self.tenant_shard_id);
    2888            6 : 
    2889            6 :         Ok(())
    2890            6 :     }
    2891              : 
    2892              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    2893              :     ///
    2894              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    2895              :     ///
    2896              :     /// This function is not cancel-safe!
    2897              :     ///
    2898              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    2899              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    2900            6 :     async fn set_stopping(
    2901            6 :         &self,
    2902            6 :         progress: completion::Barrier,
    2903            6 :         _allow_transition_from_loading: bool,
    2904            6 :         allow_transition_from_attaching: bool,
    2905            6 :     ) -> Result<(), SetStoppingError> {
    2906            6 :         let mut rx = self.state.subscribe();
    2907            6 : 
    2908            6 :         // cannot stop before we're done activating, so wait out until we're done activating
    2909            6 :         rx.wait_for(|state| match state {
    2910            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    2911              :             TenantState::Activating(_) | TenantState::Attaching => {
    2912            0 :                 info!(
    2913            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    2914            0 :                     <&'static str>::from(state)
    2915              :                 );
    2916            0 :                 false
    2917              :             }
    2918            6 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    2919            6 :         })
    2920            0 :         .await
    2921            6 :         .expect("cannot drop self.state while on a &self method");
    2922            6 : 
    2923            6 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    2924            6 :         let mut err = None;
    2925            6 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    2926              :             TenantState::Activating(_) => {
    2927            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    2928              :             }
    2929              :             TenantState::Attaching => {
    2930            0 :                 if !allow_transition_from_attaching {
    2931            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    2932            0 :                 };
    2933            0 :                 *current_state = TenantState::Stopping { progress };
    2934            0 :                 true
    2935              :             }
    2936              :             TenantState::Active => {
    2937              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    2938              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    2939              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    2940            6 :                 *current_state = TenantState::Stopping { progress };
    2941            6 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    2942            6 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    2943            6 :                 true
    2944              :             }
    2945            0 :             TenantState::Broken { reason, .. } => {
    2946            0 :                 info!(
    2947            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    2948              :                 );
    2949            0 :                 err = Some(SetStoppingError::Broken);
    2950            0 :                 false
    2951              :             }
    2952            0 :             TenantState::Stopping { progress } => {
    2953            0 :                 info!("Tenant is already in Stopping state");
    2954            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    2955            0 :                 false
    2956              :             }
    2957            6 :         });
    2958            6 :         match (stopping, err) {
    2959            6 :             (true, None) => {} // continue
    2960            0 :             (false, Some(err)) => return Err(err),
    2961            0 :             (true, Some(_)) => unreachable!(
    2962            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    2963            0 :             ),
    2964            0 :             (false, None) => unreachable!(
    2965            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    2966            0 :             ),
    2967              :         }
    2968              : 
    2969            6 :         let timelines_accessor = self.timelines.lock().unwrap();
    2970            6 :         let not_broken_timelines = timelines_accessor
    2971            6 :             .values()
    2972            6 :             .filter(|timeline| !timeline.is_broken());
    2973           12 :         for timeline in not_broken_timelines {
    2974            6 :             timeline.set_state(TimelineState::Stopping);
    2975            6 :         }
    2976            6 :         Ok(())
    2977            6 :     }
    2978              : 
    2979              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    2980              :     /// `remove_tenant_from_memory`
    2981              :     ///
    2982              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    2983              :     ///
    2984              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    2985            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    2986            0 :         let mut rx = self.state.subscribe();
    2987            0 : 
    2988            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    2989            0 :         // So, wait until it's done.
    2990            0 :         rx.wait_for(|state| match state {
    2991              :             TenantState::Activating(_) | TenantState::Attaching => {
    2992            0 :                 info!(
    2993            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    2994            0 :                     <&'static str>::from(state)
    2995              :                 );
    2996            0 :                 false
    2997              :             }
    2998            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    2999            0 :         })
    3000            0 :         .await
    3001            0 :         .expect("cannot drop self.state while on a &self method");
    3002            0 : 
    3003            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3004            0 :         self.set_broken_no_wait(reason)
    3005            0 :     }
    3006              : 
    3007            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3008            0 :         let reason = reason.to_string();
    3009            0 :         self.state.send_modify(|current_state| {
    3010            0 :             match *current_state {
    3011              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3012            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3013              :                 }
    3014              :                 TenantState::Active => {
    3015            0 :                     if cfg!(feature = "testing") {
    3016            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3017            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3018              :                     } else {
    3019            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3020              :                     }
    3021              :                 }
    3022              :                 TenantState::Broken { .. } => {
    3023            0 :                     warn!("Tenant is already in Broken state");
    3024              :                 }
    3025              :                 // This is the only "expected" path, any other path is a bug.
    3026              :                 TenantState::Stopping { .. } => {
    3027            0 :                     warn!(
    3028            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3029              :                         reason
    3030              :                     );
    3031            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3032              :                 }
    3033              :            }
    3034            0 :         });
    3035            0 :     }
    3036              : 
    3037            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3038            0 :         self.state.subscribe()
    3039            0 :     }
    3040              : 
    3041              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3042              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3043            0 :     pub(crate) fn activate_now(&self) {
    3044            0 :         self.activate_now_sem.add_permits(1);
    3045            0 :     }
    3046              : 
    3047            0 :     pub(crate) async fn wait_to_become_active(
    3048            0 :         &self,
    3049            0 :         timeout: Duration,
    3050            0 :     ) -> Result<(), GetActiveTenantError> {
    3051            0 :         let mut receiver = self.state.subscribe();
    3052              :         loop {
    3053            0 :             let current_state = receiver.borrow_and_update().clone();
    3054            0 :             match current_state {
    3055              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3056              :                     // in these states, there's a chance that we can reach ::Active
    3057            0 :                     self.activate_now();
    3058            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3059            0 :                         Ok(r) => {
    3060            0 :                             r.map_err(
    3061            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3062              :                                 // Tenant existed but was dropped: report it as non-existent
    3063            0 :                                 GetActiveTenantError::NotFound(GetTenantError::NotFound(self.tenant_shard_id.tenant_id))
    3064            0 :                         )?
    3065              :                         }
    3066              :                         Err(TimeoutCancellableError::Cancelled) => {
    3067            0 :                             return Err(GetActiveTenantError::Cancelled);
    3068              :                         }
    3069              :                         Err(TimeoutCancellableError::Timeout) => {
    3070            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3071            0 :                                 latest_state: Some(self.current_state()),
    3072            0 :                                 wait_time: timeout,
    3073            0 :                             });
    3074              :                         }
    3075              :                     }
    3076              :                 }
    3077              :                 TenantState::Active { .. } => {
    3078            0 :                     return Ok(());
    3079              :                 }
    3080            0 :                 TenantState::Broken { reason, .. } => {
    3081            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3082            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3083            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3084              :                 }
    3085              :                 TenantState::Stopping { .. } => {
    3086              :                     // There's no chance the tenant can transition back into ::Active
    3087            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3088              :                 }
    3089              :             }
    3090              :         }
    3091            0 :     }
    3092              : 
    3093            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3094            0 :         self.tenant_conf.load().location.attach_mode
    3095            0 :     }
    3096              : 
    3097              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3098              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3099              :     /// rare external API calls, like a reconciliation at startup.
    3100            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3101            0 :         let conf = self.tenant_conf.load();
    3102              : 
    3103            0 :         let location_config_mode = match conf.location.attach_mode {
    3104            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3105            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3106            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3107              :         };
    3108              : 
    3109              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3110            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3111            0 : 
    3112            0 :         models::LocationConfig {
    3113            0 :             mode: location_config_mode,
    3114            0 :             generation: self.generation.into(),
    3115            0 :             secondary_conf: None,
    3116            0 :             shard_number: self.shard_identity.number.0,
    3117            0 :             shard_count: self.shard_identity.count.literal(),
    3118            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3119            0 :             tenant_conf: tenant_config,
    3120            0 :         }
    3121            0 :     }
    3122              : 
    3123            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3124            0 :         &self.tenant_shard_id
    3125            0 :     }
    3126              : 
    3127            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3128            0 :         self.shard_identity.stripe_size
    3129            0 :     }
    3130              : 
    3131            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3132            0 :         self.generation
    3133            0 :     }
    3134              : 
    3135              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3136              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3137              :     /// resetting this tenant to a valid state if we fail.
    3138            0 :     pub(crate) async fn split_prepare(
    3139            0 :         &self,
    3140            0 :         child_shards: &Vec<TenantShardId>,
    3141            0 :     ) -> anyhow::Result<()> {
    3142            0 :         let (timelines, offloaded) = {
    3143            0 :             let timelines = self.timelines.lock().unwrap();
    3144            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3145            0 :             (timelines.clone(), offloaded.clone())
    3146            0 :         };
    3147            0 :         let timelines_iter = timelines
    3148            0 :             .values()
    3149            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3150            0 :             .chain(
    3151            0 :                 offloaded
    3152            0 :                     .values()
    3153            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3154            0 :             );
    3155            0 :         for timeline in timelines_iter {
    3156              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3157              :             // to ensure that they do not start a split if currently in the process of doing these.
    3158              : 
    3159            0 :             let timeline_id = timeline.timeline_id();
    3160              : 
    3161            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3162              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3163              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3164              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3165            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3166            0 :                 timeline
    3167            0 :                     .remote_client
    3168            0 :                     .schedule_index_upload_for_file_changes()?;
    3169            0 :                 timeline.remote_client.wait_completion().await?;
    3170            0 :             }
    3171              : 
    3172            0 :             let remote_client = match timeline {
    3173            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3174            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3175            0 :                     let remote_client = self
    3176            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3177            0 :                     Arc::new(remote_client)
    3178              :                 }
    3179              :             };
    3180              : 
    3181              :             // Shut down the timeline's remote client: this means that the indices we write
    3182              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3183            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3184            0 :             remote_client.shutdown().await;
    3185              : 
    3186              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3187              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3188              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3189              :             // we use here really is the remotely persistent one).
    3190            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3191            0 :             let result = remote_client
    3192            0 :                 .download_index_file(&self.cancel)
    3193            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))
    3194            0 :                 .await?;
    3195            0 :             let index_part = match result {
    3196              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3197            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3198              :                 }
    3199            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3200              :             };
    3201              : 
    3202            0 :             for child_shard in child_shards {
    3203            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3204            0 :                 upload_index_part(
    3205            0 :                     &self.remote_storage,
    3206            0 :                     child_shard,
    3207            0 :                     &timeline_id,
    3208            0 :                     self.generation,
    3209            0 :                     &index_part,
    3210            0 :                     &self.cancel,
    3211            0 :                 )
    3212            0 :                 .await?;
    3213              :             }
    3214              :         }
    3215              : 
    3216            0 :         let tenant_manifest = self.build_tenant_manifest();
    3217            0 :         for child_shard in child_shards {
    3218            0 :             tracing::info!(
    3219            0 :                 "Uploading tenant manifest for child {}",
    3220            0 :                 child_shard.to_index()
    3221              :             );
    3222            0 :             upload_tenant_manifest(
    3223            0 :                 &self.remote_storage,
    3224            0 :                 child_shard,
    3225            0 :                 self.generation,
    3226            0 :                 &tenant_manifest,
    3227            0 :                 &self.cancel,
    3228            0 :             )
    3229            0 :             .await?;
    3230              :         }
    3231              : 
    3232            0 :         Ok(())
    3233            0 :     }
    3234              : 
    3235            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3236            0 :         let mut result = TopTenantShardItem {
    3237            0 :             id: self.tenant_shard_id,
    3238            0 :             resident_size: 0,
    3239            0 :             physical_size: 0,
    3240            0 :             max_logical_size: 0,
    3241            0 :         };
    3242              : 
    3243            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3244            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3245            0 : 
    3246            0 :             result.physical_size += timeline
    3247            0 :                 .remote_client
    3248            0 :                 .metrics
    3249            0 :                 .remote_physical_size_gauge
    3250            0 :                 .get();
    3251            0 :             result.max_logical_size = std::cmp::max(
    3252            0 :                 result.max_logical_size,
    3253            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3254            0 :             );
    3255            0 :         }
    3256              : 
    3257            0 :         result
    3258            0 :     }
    3259              : }
    3260              : 
    3261              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3262              : /// perform a topological sort, so that the parent of each timeline comes
    3263              : /// before the children.
    3264              : /// E extracts the ancestor from T
    3265              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3266          192 : fn tree_sort_timelines<T, E>(
    3267          192 :     timelines: HashMap<TimelineId, T>,
    3268          192 :     extractor: E,
    3269          192 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3270          192 : where
    3271          192 :     E: Fn(&T) -> Option<TimelineId>,
    3272          192 : {
    3273          192 :     let mut result = Vec::with_capacity(timelines.len());
    3274          192 : 
    3275          192 :     let mut now = Vec::with_capacity(timelines.len());
    3276          192 :     // (ancestor, children)
    3277          192 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3278          192 :         HashMap::with_capacity(timelines.len());
    3279              : 
    3280          198 :     for (timeline_id, value) in timelines {
    3281            6 :         if let Some(ancestor_id) = extractor(&value) {
    3282            2 :             let children = later.entry(ancestor_id).or_default();
    3283            2 :             children.push((timeline_id, value));
    3284            4 :         } else {
    3285            4 :             now.push((timeline_id, value));
    3286            4 :         }
    3287              :     }
    3288              : 
    3289          198 :     while let Some((timeline_id, metadata)) = now.pop() {
    3290            6 :         result.push((timeline_id, metadata));
    3291              :         // All children of this can be loaded now
    3292            6 :         if let Some(mut children) = later.remove(&timeline_id) {
    3293            2 :             now.append(&mut children);
    3294            4 :         }
    3295              :     }
    3296              : 
    3297              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3298          192 :     if !later.is_empty() {
    3299            0 :         for (missing_id, orphan_ids) in later {
    3300            0 :             for (orphan_id, _) in orphan_ids {
    3301            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3302              :             }
    3303              :         }
    3304            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3305          192 :     }
    3306          192 : 
    3307          192 :     Ok(result)
    3308          192 : }
    3309              : 
    3310              : impl Tenant {
    3311            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3312            0 :         self.tenant_conf.load().tenant_conf.clone()
    3313            0 :     }
    3314              : 
    3315            0 :     pub fn effective_config(&self) -> TenantConf {
    3316            0 :         self.tenant_specific_overrides()
    3317            0 :             .merge(self.conf.default_tenant_conf.clone())
    3318            0 :     }
    3319              : 
    3320            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3321            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3322            0 :         tenant_conf
    3323            0 :             .checkpoint_distance
    3324            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3325            0 :     }
    3326              : 
    3327            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3328            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3329            0 :         tenant_conf
    3330            0 :             .checkpoint_timeout
    3331            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3332            0 :     }
    3333              : 
    3334            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3335            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3336            0 :         tenant_conf
    3337            0 :             .compaction_target_size
    3338            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3339            0 :     }
    3340              : 
    3341            0 :     pub fn get_compaction_period(&self) -> Duration {
    3342            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3343            0 :         tenant_conf
    3344            0 :             .compaction_period
    3345            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3346            0 :     }
    3347              : 
    3348            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3349            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3350            0 :         tenant_conf
    3351            0 :             .compaction_threshold
    3352            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3353            0 :     }
    3354              : 
    3355            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3356            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3357            0 :         tenant_conf
    3358            0 :             .gc_horizon
    3359            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3360            0 :     }
    3361              : 
    3362            0 :     pub fn get_gc_period(&self) -> Duration {
    3363            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3364            0 :         tenant_conf
    3365            0 :             .gc_period
    3366            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3367            0 :     }
    3368              : 
    3369            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3370            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3371            0 :         tenant_conf
    3372            0 :             .image_creation_threshold
    3373            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3374            0 :     }
    3375              : 
    3376            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3377            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3378            0 :         tenant_conf
    3379            0 :             .pitr_interval
    3380            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3381            0 :     }
    3382              : 
    3383            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3384            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3385            0 :         tenant_conf
    3386            0 :             .min_resident_size_override
    3387            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3388            0 :     }
    3389              : 
    3390            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3391            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3392            0 :         let heatmap_period = tenant_conf
    3393            0 :             .heatmap_period
    3394            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3395            0 :         if heatmap_period.is_zero() {
    3396            0 :             None
    3397              :         } else {
    3398            0 :             Some(heatmap_period)
    3399              :         }
    3400            0 :     }
    3401              : 
    3402            4 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3403            4 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3404            4 :         tenant_conf
    3405            4 :             .lsn_lease_length
    3406            4 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3407            4 :     }
    3408              : 
    3409              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3410            2 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3411            2 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3412            2 : 
    3413            2 :         let mut timeline_manifests = timelines_offloaded
    3414            2 :             .iter()
    3415            2 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3416            2 :             .collect::<Vec<_>>();
    3417            2 :         // Sort the manifests so that our output is deterministic
    3418            2 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3419            2 : 
    3420            2 :         TenantManifest {
    3421            2 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3422            2 :             offloaded_timelines: timeline_manifests,
    3423            2 :         }
    3424            2 :     }
    3425              : 
    3426            0 :     pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
    3427            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3428            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3429            0 :         // this race is not possible if both request types come from the storage
    3430            0 :         // controller (as they should!) because an exclusive op lock is required
    3431            0 :         // on the storage controller side.
    3432            0 :         self.tenant_conf.rcu(|inner| {
    3433            0 :             Arc::new(AttachedTenantConf {
    3434            0 :                 tenant_conf: new_tenant_conf.clone(),
    3435            0 :                 location: inner.location,
    3436            0 :                 // Attached location is not changed, no need to update lsn lease deadline.
    3437            0 :                 lsn_lease_deadline: inner.lsn_lease_deadline,
    3438            0 :             })
    3439            0 :         });
    3440            0 : 
    3441            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3442            0 :         // Don't hold self.timelines.lock() during the notifies.
    3443            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3444            0 :         // mutexes in struct Timeline in the future.
    3445            0 :         let timelines = self.list_timelines();
    3446            0 :         for timeline in timelines {
    3447            0 :             timeline.tenant_conf_updated(&new_tenant_conf);
    3448            0 :         }
    3449            0 :     }
    3450              : 
    3451            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3452            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3453            0 : 
    3454            0 :         self.tenant_conf.store(Arc::new(new_conf));
    3455            0 : 
    3456            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3457            0 :         // Don't hold self.timelines.lock() during the notifies.
    3458            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3459            0 :         // mutexes in struct Timeline in the future.
    3460            0 :         let timelines = self.list_timelines();
    3461            0 :         for timeline in timelines {
    3462            0 :             timeline.tenant_conf_updated(&new_tenant_conf);
    3463            0 :         }
    3464            0 :     }
    3465              : 
    3466          192 :     fn get_timeline_get_throttle_config(
    3467          192 :         psconf: &'static PageServerConf,
    3468          192 :         overrides: &TenantConfOpt,
    3469          192 :     ) -> throttle::Config {
    3470          192 :         overrides
    3471          192 :             .timeline_get_throttle
    3472          192 :             .clone()
    3473          192 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3474          192 :     }
    3475              : 
    3476            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3477            0 :         let conf = Self::get_timeline_get_throttle_config(self.conf, new_conf);
    3478            0 :         self.timeline_get_throttle.reconfigure(conf)
    3479            0 :     }
    3480              : 
    3481              :     /// Helper function to create a new Timeline struct.
    3482              :     ///
    3483              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3484              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3485              :     /// map.
    3486              :     ///
    3487              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3488              :     /// and we might not have the ancestor present anymore which is fine for to be
    3489              :     /// deleted timelines.
    3490          418 :     fn create_timeline_struct(
    3491          418 :         &self,
    3492          418 :         new_timeline_id: TimelineId,
    3493          418 :         new_metadata: &TimelineMetadata,
    3494          418 :         ancestor: Option<Arc<Timeline>>,
    3495          418 :         resources: TimelineResources,
    3496          418 :         cause: CreateTimelineCause,
    3497          418 :         create_idempotency: CreateTimelineIdempotency,
    3498          418 :     ) -> anyhow::Result<Arc<Timeline>> {
    3499          418 :         let state = match cause {
    3500              :             CreateTimelineCause::Load => {
    3501          418 :                 let ancestor_id = new_metadata.ancestor_timeline();
    3502          418 :                 anyhow::ensure!(
    3503          418 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    3504            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    3505              :                 );
    3506          418 :                 TimelineState::Loading
    3507              :             }
    3508            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    3509              :         };
    3510              : 
    3511          418 :         let pg_version = new_metadata.pg_version();
    3512          418 : 
    3513          418 :         let timeline = Timeline::new(
    3514          418 :             self.conf,
    3515          418 :             Arc::clone(&self.tenant_conf),
    3516          418 :             new_metadata,
    3517          418 :             ancestor,
    3518          418 :             new_timeline_id,
    3519          418 :             self.tenant_shard_id,
    3520          418 :             self.generation,
    3521          418 :             self.shard_identity,
    3522          418 :             self.walredo_mgr.clone(),
    3523          418 :             resources,
    3524          418 :             pg_version,
    3525          418 :             state,
    3526          418 :             self.attach_wal_lag_cooldown.clone(),
    3527          418 :             create_idempotency,
    3528          418 :             self.cancel.child_token(),
    3529          418 :         );
    3530          418 : 
    3531          418 :         Ok(timeline)
    3532          418 :     }
    3533              : 
    3534              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    3535              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    3536              :     #[allow(clippy::too_many_arguments)]
    3537          192 :     fn new(
    3538          192 :         state: TenantState,
    3539          192 :         conf: &'static PageServerConf,
    3540          192 :         attached_conf: AttachedTenantConf,
    3541          192 :         shard_identity: ShardIdentity,
    3542          192 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    3543          192 :         tenant_shard_id: TenantShardId,
    3544          192 :         remote_storage: GenericRemoteStorage,
    3545          192 :         deletion_queue_client: DeletionQueueClient,
    3546          192 :         l0_flush_global_state: L0FlushGlobalState,
    3547          192 :     ) -> Tenant {
    3548          192 :         debug_assert!(
    3549          192 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    3550              :         );
    3551              : 
    3552          192 :         let (state, mut rx) = watch::channel(state);
    3553          192 : 
    3554          192 :         tokio::spawn(async move {
    3555          192 :             // reflect tenant state in metrics:
    3556          192 :             // - global per tenant state: TENANT_STATE_METRIC
    3557          192 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    3558          192 :             //
    3559          192 :             // set of broken tenants should not have zero counts so that it remains accessible for
    3560          192 :             // alerting.
    3561          192 : 
    3562          192 :             let tid = tenant_shard_id.to_string();
    3563          192 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    3564          192 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    3565              : 
    3566          384 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    3567          384 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    3568          384 :             }
    3569              : 
    3570          192 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    3571          192 : 
    3572          192 :             let is_broken = tuple.1;
    3573          192 :             let mut counted_broken = if is_broken {
    3574              :                 // add the id to the set right away, there should not be any updates on the channel
    3575              :                 // after before tenant is removed, if ever
    3576            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    3577            0 :                 true
    3578              :             } else {
    3579          192 :                 false
    3580              :             };
    3581              : 
    3582              :             loop {
    3583          384 :                 let labels = &tuple.0;
    3584          384 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    3585          384 :                 current.inc();
    3586          384 : 
    3587          384 :                 if rx.changed().await.is_err() {
    3588              :                     // tenant has been dropped
    3589           16 :                     current.dec();
    3590           16 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    3591           16 :                     break;
    3592          192 :                 }
    3593          192 : 
    3594          192 :                 current.dec();
    3595          192 :                 tuple = inspect_state(&rx.borrow_and_update());
    3596          192 : 
    3597          192 :                 let is_broken = tuple.1;
    3598          192 :                 if is_broken && !counted_broken {
    3599            0 :                     counted_broken = true;
    3600            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    3601            0 :                     // access
    3602            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    3603          192 :                 }
    3604              :             }
    3605          192 :         });
    3606          192 : 
    3607          192 :         Tenant {
    3608          192 :             tenant_shard_id,
    3609          192 :             shard_identity,
    3610          192 :             generation: attached_conf.location.generation,
    3611          192 :             conf,
    3612          192 :             // using now here is good enough approximation to catch tenants with really long
    3613          192 :             // activation times.
    3614          192 :             constructed_at: Instant::now(),
    3615          192 :             timelines: Mutex::new(HashMap::new()),
    3616          192 :             timelines_creating: Mutex::new(HashSet::new()),
    3617          192 :             timelines_offloaded: Mutex::new(HashMap::new()),
    3618          192 :             tenant_manifest_upload: Default::default(),
    3619          192 :             gc_cs: tokio::sync::Mutex::new(()),
    3620          192 :             walredo_mgr,
    3621          192 :             remote_storage,
    3622          192 :             deletion_queue_client,
    3623          192 :             state,
    3624          192 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    3625          192 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    3626          192 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    3627          192 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    3628          192 :                 format!("compaction-{tenant_shard_id}"),
    3629          192 :                 5,
    3630          192 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    3631          192 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    3632          192 :                 // use an extremely long backoff.
    3633          192 :                 Some(Duration::from_secs(3600 * 24)),
    3634          192 :             )),
    3635          192 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    3636          192 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    3637          192 :             cancel: CancellationToken::default(),
    3638          192 :             gate: Gate::default(),
    3639          192 :             timeline_get_throttle: Arc::new(throttle::Throttle::new(
    3640          192 :                 Tenant::get_timeline_get_throttle_config(conf, &attached_conf.tenant_conf),
    3641          192 :                 crate::metrics::tenant_throttling::TimelineGet::new(&tenant_shard_id),
    3642          192 :             )),
    3643          192 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    3644          192 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    3645          192 :             gc_block: Default::default(),
    3646          192 :             l0_flush_global_state,
    3647          192 :         }
    3648          192 :     }
    3649              : 
    3650              :     /// Locate and load config
    3651            0 :     pub(super) fn load_tenant_config(
    3652            0 :         conf: &'static PageServerConf,
    3653            0 :         tenant_shard_id: &TenantShardId,
    3654            0 :     ) -> Result<LocationConf, LoadConfigError> {
    3655            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    3656            0 : 
    3657            0 :         info!("loading tenant configuration from {config_path}");
    3658              : 
    3659              :         // load and parse file
    3660            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    3661            0 :             match e.kind() {
    3662              :                 std::io::ErrorKind::NotFound => {
    3663              :                     // The config should almost always exist for a tenant directory:
    3664              :                     //  - When attaching a tenant, the config is the first thing we write
    3665              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    3666              :                     //    before deleting contents.
    3667              :                     //
    3668              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    3669              :                     // between creating directory and writing config.  Callers should handle that as if the
    3670              :                     // directory didn't exist.
    3671              : 
    3672            0 :                     LoadConfigError::NotFound(config_path)
    3673              :                 }
    3674              :                 _ => {
    3675              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    3676              :                     // that we cannot cleanly recover
    3677            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    3678              :                 }
    3679              :             }
    3680            0 :         })?;
    3681              : 
    3682            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    3683            0 :     }
    3684              : 
    3685            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    3686              :     pub(super) async fn persist_tenant_config(
    3687              :         conf: &'static PageServerConf,
    3688              :         tenant_shard_id: &TenantShardId,
    3689              :         location_conf: &LocationConf,
    3690              :     ) -> std::io::Result<()> {
    3691              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    3692              : 
    3693              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    3694              :     }
    3695              : 
    3696            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    3697              :     pub(super) async fn persist_tenant_config_at(
    3698              :         tenant_shard_id: &TenantShardId,
    3699              :         config_path: &Utf8Path,
    3700              :         location_conf: &LocationConf,
    3701              :     ) -> std::io::Result<()> {
    3702              :         debug!("persisting tenantconf to {config_path}");
    3703              : 
    3704              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    3705              : #  It is read in case of pageserver restart.
    3706              : "#
    3707              :         .to_string();
    3708              : 
    3709            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    3710            0 :             Err(std::io::Error::new(
    3711            0 :                 std::io::ErrorKind::Other,
    3712            0 :                 "tenant-config-before-write",
    3713            0 :             ))
    3714            0 :         });
    3715              : 
    3716              :         // Convert the config to a toml file.
    3717              :         conf_content +=
    3718              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    3719              : 
    3720              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    3721              : 
    3722              :         let conf_content = conf_content.into_bytes();
    3723              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    3724              :     }
    3725              : 
    3726              :     //
    3727              :     // How garbage collection works:
    3728              :     //
    3729              :     //                    +--bar------------->
    3730              :     //                   /
    3731              :     //             +----+-----foo---------------->
    3732              :     //            /
    3733              :     // ----main--+-------------------------->
    3734              :     //                \
    3735              :     //                 +-----baz-------->
    3736              :     //
    3737              :     //
    3738              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    3739              :     //    `gc_infos` are being refreshed
    3740              :     // 2. Scan collected timelines, and on each timeline, make note of the
    3741              :     //    all the points where other timelines have been branched off.
    3742              :     //    We will refrain from removing page versions at those LSNs.
    3743              :     // 3. For each timeline, scan all layer files on the timeline.
    3744              :     //    Remove all files for which a newer file exists and which
    3745              :     //    don't cover any branch point LSNs.
    3746              :     //
    3747              :     // TODO:
    3748              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    3749              :     //   don't need to keep that in the parent anymore. But currently
    3750              :     //   we do.
    3751            4 :     async fn gc_iteration_internal(
    3752            4 :         &self,
    3753            4 :         target_timeline_id: Option<TimelineId>,
    3754            4 :         horizon: u64,
    3755            4 :         pitr: Duration,
    3756            4 :         cancel: &CancellationToken,
    3757            4 :         ctx: &RequestContext,
    3758            4 :     ) -> Result<GcResult, GcError> {
    3759            4 :         let mut totals: GcResult = Default::default();
    3760            4 :         let now = Instant::now();
    3761              : 
    3762            4 :         let gc_timelines = self
    3763            4 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3764            4 :             .await?;
    3765              : 
    3766            4 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    3767              : 
    3768              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    3769            4 :         if !gc_timelines.is_empty() {
    3770            4 :             info!("{} timelines need GC", gc_timelines.len());
    3771              :         } else {
    3772            0 :             debug!("{} timelines need GC", gc_timelines.len());
    3773              :         }
    3774              : 
    3775              :         // Perform GC for each timeline.
    3776              :         //
    3777              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    3778              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    3779              :         // with branch creation.
    3780              :         //
    3781              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    3782              :         // creation task can run concurrently with timeline's GC iteration.
    3783            8 :         for timeline in gc_timelines {
    3784            4 :             if cancel.is_cancelled() {
    3785              :                 // We were requested to shut down. Stop and return with the progress we
    3786              :                 // made.
    3787            0 :                 break;
    3788            4 :             }
    3789            4 :             let result = match timeline.gc().await {
    3790              :                 Err(GcError::TimelineCancelled) => {
    3791            0 :                     if target_timeline_id.is_some() {
    3792              :                         // If we were targetting this specific timeline, surface cancellation to caller
    3793            0 :                         return Err(GcError::TimelineCancelled);
    3794              :                     } else {
    3795              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    3796              :                         // skip past this and proceed to try GC on other timelines.
    3797            0 :                         continue;
    3798              :                     }
    3799              :                 }
    3800            4 :                 r => r?,
    3801              :             };
    3802            4 :             totals += result;
    3803              :         }
    3804              : 
    3805            4 :         totals.elapsed = now.elapsed();
    3806            4 :         Ok(totals)
    3807            4 :     }
    3808              : 
    3809              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    3810              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    3811              :     /// [`Tenant::get_gc_horizon`].
    3812              :     ///
    3813              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    3814            0 :     pub(crate) async fn refresh_gc_info(
    3815            0 :         &self,
    3816            0 :         cancel: &CancellationToken,
    3817            0 :         ctx: &RequestContext,
    3818            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    3819            0 :         // since this method can now be called at different rates than the configured gc loop, it
    3820            0 :         // might be that these configuration values get applied faster than what it was previously,
    3821            0 :         // since these were only read from the gc task.
    3822            0 :         let horizon = self.get_gc_horizon();
    3823            0 :         let pitr = self.get_pitr_interval();
    3824            0 : 
    3825            0 :         // refresh all timelines
    3826            0 :         let target_timeline_id = None;
    3827            0 : 
    3828            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3829            0 :             .await
    3830            0 :     }
    3831              : 
    3832              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    3833              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    3834              :     ///
    3835              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    3836            0 :     fn initialize_gc_info(
    3837            0 :         &self,
    3838            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    3839            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    3840            0 :         restrict_to_timeline: Option<TimelineId>,
    3841            0 :     ) {
    3842            0 :         if restrict_to_timeline.is_none() {
    3843              :             // This function must be called before activation: after activation timeline create/delete operations
    3844              :             // might happen, and this function is not safe to run concurrently with those.
    3845            0 :             assert!(!self.is_active());
    3846            0 :         }
    3847              : 
    3848              :         // Scan all timelines. For each timeline, remember the timeline ID and
    3849              :         // the branch point where it was created.
    3850            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    3851            0 :             BTreeMap::new();
    3852            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    3853            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    3854            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    3855            0 :                 ancestor_children.push((
    3856            0 :                     timeline_entry.get_ancestor_lsn(),
    3857            0 :                     *timeline_id,
    3858            0 :                     MaybeOffloaded::No,
    3859            0 :                 ));
    3860            0 :             }
    3861            0 :         });
    3862            0 :         timelines_offloaded
    3863            0 :             .iter()
    3864            0 :             .for_each(|(timeline_id, timeline_entry)| {
    3865            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    3866            0 :                     return;
    3867              :                 };
    3868            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    3869            0 :                     return;
    3870              :                 };
    3871            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    3872            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    3873            0 :             });
    3874            0 : 
    3875            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    3876            0 :         let horizon = self.get_gc_horizon();
    3877              : 
    3878              :         // Populate each timeline's GcInfo with information about its child branches
    3879            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    3880            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    3881              :         } else {
    3882            0 :             itertools::Either::Right(timelines.values())
    3883              :         };
    3884            0 :         for timeline in timelines_to_write {
    3885            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    3886            0 :                 .remove(&timeline.timeline_id)
    3887            0 :                 .unwrap_or_default();
    3888            0 : 
    3889            0 :             branchpoints.sort_by_key(|b| b.0);
    3890            0 : 
    3891            0 :             let mut target = timeline.gc_info.write().unwrap();
    3892            0 : 
    3893            0 :             target.retain_lsns = branchpoints;
    3894            0 : 
    3895            0 :             let space_cutoff = timeline
    3896            0 :                 .get_last_record_lsn()
    3897            0 :                 .checked_sub(horizon)
    3898            0 :                 .unwrap_or(Lsn(0));
    3899            0 : 
    3900            0 :             target.cutoffs = GcCutoffs {
    3901            0 :                 space: space_cutoff,
    3902            0 :                 time: Lsn::INVALID,
    3903            0 :             };
    3904            0 :         }
    3905            0 :     }
    3906              : 
    3907            4 :     async fn refresh_gc_info_internal(
    3908            4 :         &self,
    3909            4 :         target_timeline_id: Option<TimelineId>,
    3910            4 :         horizon: u64,
    3911            4 :         pitr: Duration,
    3912            4 :         cancel: &CancellationToken,
    3913            4 :         ctx: &RequestContext,
    3914            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    3915            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    3916            4 :         // currently visible timelines.
    3917            4 :         let timelines = self
    3918            4 :             .timelines
    3919            4 :             .lock()
    3920            4 :             .unwrap()
    3921            4 :             .values()
    3922            4 :             .filter(|tl| match target_timeline_id.as_ref() {
    3923            4 :                 Some(target) => &tl.timeline_id == target,
    3924            0 :                 None => true,
    3925            4 :             })
    3926            4 :             .cloned()
    3927            4 :             .collect::<Vec<_>>();
    3928            4 : 
    3929            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    3930              :             // We were to act on a particular timeline and it wasn't found
    3931            0 :             return Err(GcError::TimelineNotFound);
    3932            4 :         }
    3933            4 : 
    3934            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    3935            4 :             HashMap::with_capacity(timelines.len());
    3936              : 
    3937            4 :         for timeline in timelines.iter() {
    3938            4 :             let cutoff = timeline
    3939            4 :                 .get_last_record_lsn()
    3940            4 :                 .checked_sub(horizon)
    3941            4 :                 .unwrap_or(Lsn(0));
    3942              : 
    3943            4 :             let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
    3944            4 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    3945            4 :             assert!(old.is_none());
    3946              :         }
    3947              : 
    3948            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    3949            0 :             return Err(GcError::TenantCancelled);
    3950            4 :         }
    3951              : 
    3952              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    3953              :         // because that will stall branch creation.
    3954            4 :         let gc_cs = self.gc_cs.lock().await;
    3955              : 
    3956              :         // Ok, we now know all the branch points.
    3957              :         // Update the GC information for each timeline.
    3958            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    3959            8 :         for timeline in timelines {
    3960              :             // We filtered the timeline list above
    3961            4 :             if let Some(target_timeline_id) = target_timeline_id {
    3962            4 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    3963            0 :             }
    3964              : 
    3965              :             {
    3966            4 :                 let mut target = timeline.gc_info.write().unwrap();
    3967            4 : 
    3968            4 :                 // Cull any expired leases
    3969            4 :                 let now = SystemTime::now();
    3970            6 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    3971            4 : 
    3972            4 :                 timeline
    3973            4 :                     .metrics
    3974            4 :                     .valid_lsn_lease_count_gauge
    3975            4 :                     .set(target.leases.len() as u64);
    3976              : 
    3977              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    3978            4 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    3979            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    3980            0 :                         target.within_ancestor_pitr =
    3981            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    3982            0 :                     }
    3983            4 :                 }
    3984              : 
    3985              :                 // Update metrics that depend on GC state
    3986            4 :                 timeline
    3987            4 :                     .metrics
    3988            4 :                     .archival_size
    3989            4 :                     .set(if target.within_ancestor_pitr {
    3990            0 :                         timeline.metrics.current_logical_size_gauge.get()
    3991              :                     } else {
    3992            4 :                         0
    3993              :                     });
    3994            4 :                 timeline.metrics.pitr_history_size.set(
    3995            4 :                     timeline
    3996            4 :                         .get_last_record_lsn()
    3997            4 :                         .checked_sub(target.cutoffs.time)
    3998            4 :                         .unwrap_or(Lsn(0))
    3999            4 :                         .0,
    4000            4 :                 );
    4001              : 
    4002              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4003              :                 // - this timeline was created while we were finding cutoffs
    4004              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4005            4 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4006            4 :                     target.cutoffs = cutoffs.clone();
    4007            4 :                 }
    4008              :             }
    4009              : 
    4010            4 :             gc_timelines.push(timeline);
    4011              :         }
    4012            4 :         drop(gc_cs);
    4013            4 :         Ok(gc_timelines)
    4014            4 :     }
    4015              : 
    4016              :     /// A substitute for `branch_timeline` for use in unit tests.
    4017              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4018              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4019              :     /// timeline background tasks are launched, except the flush loop.
    4020              :     #[cfg(test)]
    4021          232 :     async fn branch_timeline_test(
    4022          232 :         self: &Arc<Self>,
    4023          232 :         src_timeline: &Arc<Timeline>,
    4024          232 :         dst_id: TimelineId,
    4025          232 :         ancestor_lsn: Option<Lsn>,
    4026          232 :         ctx: &RequestContext,
    4027          232 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4028          232 :         let tl = self
    4029          232 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4030          185 :             .await?
    4031          228 :             .into_timeline_for_test();
    4032          228 :         tl.set_state(TimelineState::Active);
    4033          228 :         Ok(tl)
    4034          232 :     }
    4035              : 
    4036              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4037              :     #[cfg(test)]
    4038              :     #[allow(clippy::too_many_arguments)]
    4039            6 :     pub async fn branch_timeline_test_with_layers(
    4040            6 :         self: &Arc<Self>,
    4041            6 :         src_timeline: &Arc<Timeline>,
    4042            6 :         dst_id: TimelineId,
    4043            6 :         ancestor_lsn: Option<Lsn>,
    4044            6 :         ctx: &RequestContext,
    4045            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4046            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4047            6 :         end_lsn: Lsn,
    4048            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4049              :         use checks::check_valid_layermap;
    4050              :         use itertools::Itertools;
    4051              : 
    4052            6 :         let tline = self
    4053            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4054            5 :             .await?;
    4055            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4056            6 :             ancestor_lsn
    4057              :         } else {
    4058            0 :             tline.get_last_record_lsn()
    4059              :         };
    4060            6 :         assert!(end_lsn >= ancestor_lsn);
    4061            6 :         tline.force_advance_lsn(end_lsn);
    4062           12 :         for deltas in delta_layer_desc {
    4063            6 :             tline
    4064            6 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4065           18 :                 .await?;
    4066              :         }
    4067           10 :         for (lsn, images) in image_layer_desc {
    4068            4 :             tline
    4069            4 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4070           14 :                 .await?;
    4071              :         }
    4072            6 :         let layer_names = tline
    4073            6 :             .layers
    4074            6 :             .read()
    4075            0 :             .await
    4076            6 :             .layer_map()
    4077            6 :             .unwrap()
    4078            6 :             .iter_historic_layers()
    4079           10 :             .map(|layer| layer.layer_name())
    4080            6 :             .collect_vec();
    4081            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4082            0 :             bail!("invalid layermap: {err}");
    4083            6 :         }
    4084            6 :         Ok(tline)
    4085            6 :     }
    4086              : 
    4087              :     /// Branch an existing timeline.
    4088            0 :     async fn branch_timeline(
    4089            0 :         self: &Arc<Self>,
    4090            0 :         src_timeline: &Arc<Timeline>,
    4091            0 :         dst_id: TimelineId,
    4092            0 :         start_lsn: Option<Lsn>,
    4093            0 :         ctx: &RequestContext,
    4094            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4095            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4096            0 :             .await
    4097            0 :     }
    4098              : 
    4099          232 :     async fn branch_timeline_impl(
    4100          232 :         self: &Arc<Self>,
    4101          232 :         src_timeline: &Arc<Timeline>,
    4102          232 :         dst_id: TimelineId,
    4103          232 :         start_lsn: Option<Lsn>,
    4104          232 :         _ctx: &RequestContext,
    4105          232 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4106          232 :         let src_id = src_timeline.timeline_id;
    4107              : 
    4108              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4109              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4110              :         // valid while we are creating the branch.
    4111          232 :         let _gc_cs = self.gc_cs.lock().await;
    4112              : 
    4113              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4114          232 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4115            2 :             let lsn = src_timeline.get_last_record_lsn();
    4116            2 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4117            2 :             lsn
    4118          232 :         });
    4119              : 
    4120              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4121          232 :         let timeline_create_guard = match self
    4122          232 :             .start_creating_timeline(
    4123          232 :                 dst_id,
    4124          232 :                 CreateTimelineIdempotency::Branch {
    4125          232 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4126          232 :                     ancestor_start_lsn: start_lsn,
    4127          232 :                 },
    4128          232 :             )
    4129          185 :             .await?
    4130              :         {
    4131          232 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4132            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4133            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4134              :             }
    4135              :         };
    4136              : 
    4137              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4138              :         // horizon on the source timeline
    4139              :         //
    4140              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4141              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4142              :         // planned GC cutoff in 'gc_info' is normally larger than
    4143              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4144              :         // changed the GC settings for the tenant to make the PITR window
    4145              :         // larger, but some of the data was already removed by an earlier GC
    4146              :         // iteration.
    4147              : 
    4148              :         // check against last actual 'latest_gc_cutoff' first
    4149          232 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4150          232 :         src_timeline
    4151          232 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4152          232 :             .context(format!(
    4153          232 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4154          232 :                 *latest_gc_cutoff_lsn,
    4155          232 :             ))
    4156          232 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4157              : 
    4158              :         // and then the planned GC cutoff
    4159              :         {
    4160          228 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4161          228 :             let cutoff = gc_info.min_cutoff();
    4162          228 :             if start_lsn < cutoff {
    4163            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4164            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4165            0 :                 )));
    4166          228 :             }
    4167          228 :         }
    4168          228 : 
    4169          228 :         //
    4170          228 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4171          228 :         // so that GC cannot advance the GC cutoff until we are finished.
    4172          228 :         // Proceed with the branch creation.
    4173          228 :         //
    4174          228 : 
    4175          228 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4176          228 :         // the timeline was branched at the current end of the source timeline.
    4177          228 :         let RecordLsn {
    4178          228 :             last: src_last,
    4179          228 :             prev: src_prev,
    4180          228 :         } = src_timeline.get_last_record_rlsn();
    4181          228 :         let dst_prev = if src_last == start_lsn {
    4182          216 :             Some(src_prev)
    4183              :         } else {
    4184           12 :             None
    4185              :         };
    4186              : 
    4187              :         // Create the metadata file, noting the ancestor of the new timeline.
    4188              :         // There is initially no data in it, but all the read-calls know to look
    4189              :         // into the ancestor.
    4190          228 :         let metadata = TimelineMetadata::new(
    4191          228 :             start_lsn,
    4192          228 :             dst_prev,
    4193          228 :             Some(src_id),
    4194          228 :             start_lsn,
    4195          228 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4196          228 :             src_timeline.initdb_lsn,
    4197          228 :             src_timeline.pg_version,
    4198          228 :         );
    4199              : 
    4200          228 :         let uninitialized_timeline = self
    4201          228 :             .prepare_new_timeline(
    4202          228 :                 dst_id,
    4203          228 :                 &metadata,
    4204          228 :                 timeline_create_guard,
    4205          228 :                 start_lsn + 1,
    4206          228 :                 Some(Arc::clone(src_timeline)),
    4207          228 :             )
    4208            0 :             .await?;
    4209              : 
    4210          228 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4211              : 
    4212              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4213              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4214              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4215              :         // could get incorrect information and remove more layers, than needed.
    4216              :         // See also https://github.com/neondatabase/neon/issues/3865
    4217          228 :         new_timeline
    4218          228 :             .remote_client
    4219          228 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4220          228 :             .context("branch initial metadata upload")?;
    4221              : 
    4222              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4223              : 
    4224          228 :         Ok(CreateTimelineResult::Created(new_timeline))
    4225          232 :     }
    4226              : 
    4227              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4228              :     #[cfg(test)]
    4229            2 :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4230              :     pub(crate) async fn bootstrap_timeline_test(
    4231              :         self: &Arc<Self>,
    4232              :         timeline_id: TimelineId,
    4233              :         pg_version: u32,
    4234              :         load_existing_initdb: Option<TimelineId>,
    4235              :         ctx: &RequestContext,
    4236              :     ) -> anyhow::Result<Arc<Timeline>> {
    4237              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4238              :             .await
    4239              :             .map_err(anyhow::Error::new)
    4240            2 :             .map(|r| r.into_timeline_for_test())
    4241              :     }
    4242              : 
    4243              :     /// Get exclusive access to the timeline ID for creation.
    4244              :     ///
    4245              :     /// Timeline-creating code paths must use this function before making changes
    4246              :     /// to in-memory or persistent state.
    4247              :     ///
    4248              :     /// The `state` parameter is a description of the timeline creation operation
    4249              :     /// we intend to perform.
    4250              :     /// If the timeline was already created in the meantime, we check whether this
    4251              :     /// request conflicts or is idempotent , based on `state`.
    4252          418 :     async fn start_creating_timeline(
    4253          418 :         &self,
    4254          418 :         new_timeline_id: TimelineId,
    4255          418 :         idempotency: CreateTimelineIdempotency,
    4256          418 :     ) -> Result<StartCreatingTimelineResult<'_>, CreateTimelineError> {
    4257          418 :         let allow_offloaded = false;
    4258          418 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4259          416 :             Ok(create_guard) => {
    4260          416 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4261          416 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4262              :             }
    4263              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4264              :                 // Creation is in progress, we cannot create it again, and we cannot
    4265              :                 // check if this request matches the existing one, so caller must try
    4266              :                 // again later.
    4267            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4268              :             }
    4269            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4270              :             Err(TimelineExclusionError::AlreadyExists {
    4271            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4272            0 :                 ..
    4273            0 :             }) => {
    4274            0 :                 info!("timeline already exists but is offloaded");
    4275            0 :                 Err(CreateTimelineError::Conflict)
    4276              :             }
    4277              :             Err(TimelineExclusionError::AlreadyExists {
    4278            2 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4279            2 :                 arg,
    4280            2 :             }) => {
    4281            2 :                 {
    4282            2 :                     let existing = &existing.create_idempotency;
    4283            2 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4284            2 :                     debug!("timeline already exists");
    4285              : 
    4286            2 :                     match (existing, &arg) {
    4287              :                         // FailWithConflict => no idempotency check
    4288              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4289              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4290            2 :                             warn!("timeline already exists, failing request");
    4291            2 :                             return Err(CreateTimelineError::Conflict);
    4292              :                         }
    4293              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4294            0 :                         (x, y) if x == y => {
    4295            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4296              :                             // fallthrough
    4297              :                         }
    4298              :                         (_, _) => {
    4299            0 :                             warn!("idempotency conflict, failing request");
    4300            0 :                             return Err(CreateTimelineError::Conflict);
    4301              :                         }
    4302              :                     }
    4303              :                 }
    4304              : 
    4305            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4306              :             }
    4307              :         }
    4308          418 :     }
    4309              : 
    4310            0 :     async fn upload_initdb(
    4311            0 :         &self,
    4312            0 :         timelines_path: &Utf8PathBuf,
    4313            0 :         pgdata_path: &Utf8PathBuf,
    4314            0 :         timeline_id: &TimelineId,
    4315            0 :     ) -> anyhow::Result<()> {
    4316            0 :         let temp_path = timelines_path.join(format!(
    4317            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4318            0 :         ));
    4319            0 : 
    4320            0 :         scopeguard::defer! {
    4321            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4322            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4323            0 :             }
    4324            0 :         }
    4325              : 
    4326            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4327              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4328            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4329            0 :             warn!(
    4330            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4331              :             );
    4332            0 :         }
    4333              : 
    4334            0 :         pausable_failpoint!("before-initdb-upload");
    4335              : 
    4336            0 :         backoff::retry(
    4337            0 :             || async {
    4338            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4339            0 :                     &self.remote_storage,
    4340            0 :                     &self.tenant_shard_id.tenant_id,
    4341            0 :                     timeline_id,
    4342            0 :                     pgdata_zstd.try_clone().await?,
    4343            0 :                     tar_zst_size,
    4344            0 :                     &self.cancel,
    4345              :                 )
    4346            0 :                 .await
    4347            0 :             },
    4348            0 :             |_| false,
    4349            0 :             3,
    4350            0 :             u32::MAX,
    4351            0 :             "persist_initdb_tar_zst",
    4352            0 :             &self.cancel,
    4353            0 :         )
    4354            0 :         .await
    4355            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4356            0 :         .and_then(|x| x)
    4357            0 :     }
    4358              : 
    4359              :     /// - run initdb to init temporary instance and get bootstrap data
    4360              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4361            2 :     async fn bootstrap_timeline(
    4362            2 :         self: &Arc<Self>,
    4363            2 :         timeline_id: TimelineId,
    4364            2 :         pg_version: u32,
    4365            2 :         load_existing_initdb: Option<TimelineId>,
    4366            2 :         ctx: &RequestContext,
    4367            2 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4368            2 :         let timeline_create_guard = match self
    4369            2 :             .start_creating_timeline(
    4370            2 :                 timeline_id,
    4371            2 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4372            2 :             )
    4373            1 :             .await?
    4374              :         {
    4375            2 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4376            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4377            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4378              :             }
    4379              :         };
    4380              : 
    4381              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4382              :         // temporary directory for basebackup files for the given timeline.
    4383              : 
    4384            2 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4385            2 :         let pgdata_path = path_with_suffix_extension(
    4386            2 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4387            2 :             TEMP_FILE_SUFFIX,
    4388            2 :         );
    4389            2 : 
    4390            2 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4391            2 :         // we won't race with other creations or existent timelines with the same path.
    4392            2 :         if pgdata_path.exists() {
    4393            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4394            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4395            0 :             })?;
    4396            2 :         }
    4397              : 
    4398              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4399            2 :         scopeguard::defer! {
    4400            2 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4401            2 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4402            2 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4403            2 :             }
    4404            2 :         }
    4405            2 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4406            2 :             if existing_initdb_timeline_id != timeline_id {
    4407            0 :                 let source_path = &remote_initdb_archive_path(
    4408            0 :                     &self.tenant_shard_id.tenant_id,
    4409            0 :                     &existing_initdb_timeline_id,
    4410            0 :                 );
    4411            0 :                 let dest_path =
    4412            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4413            0 : 
    4414            0 :                 // if this fails, it will get retried by retried control plane requests
    4415            0 :                 self.remote_storage
    4416            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4417            0 :                     .await
    4418            0 :                     .context("copy initdb tar")?;
    4419            2 :             }
    4420            2 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4421            2 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4422            2 :                     self.conf,
    4423            2 :                     &self.remote_storage,
    4424            2 :                     &self.tenant_shard_id,
    4425            2 :                     &existing_initdb_timeline_id,
    4426            2 :                     &self.cancel,
    4427            2 :                 )
    4428          268 :                 .await
    4429            2 :                 .context("download initdb tar")?;
    4430              : 
    4431            2 :             scopeguard::defer! {
    4432            2 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4433            2 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4434            2 :                 }
    4435            2 :             }
    4436            2 : 
    4437            2 :             let buf_read =
    4438            2 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4439            2 :             extract_zst_tarball(&pgdata_path, buf_read)
    4440         9512 :                 .await
    4441            2 :                 .context("extract initdb tar")?;
    4442              :         } else {
    4443              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4444            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4445            0 :                 .await
    4446            0 :                 .context("run initdb")?;
    4447              : 
    4448              :             // Upload the created data dir to S3
    4449            0 :             if self.tenant_shard_id().is_shard_zero() {
    4450            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4451            0 :                     .await?;
    4452            0 :             }
    4453              :         }
    4454            2 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4455            2 : 
    4456            2 :         // Import the contents of the data directory at the initial checkpoint
    4457            2 :         // LSN, and any WAL after that.
    4458            2 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4459            2 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4460            2 :         let new_metadata = TimelineMetadata::new(
    4461            2 :             Lsn(0),
    4462            2 :             None,
    4463            2 :             None,
    4464            2 :             Lsn(0),
    4465            2 :             pgdata_lsn,
    4466            2 :             pgdata_lsn,
    4467            2 :             pg_version,
    4468            2 :         );
    4469            2 :         let raw_timeline = self
    4470            2 :             .prepare_new_timeline(
    4471            2 :                 timeline_id,
    4472            2 :                 &new_metadata,
    4473            2 :                 timeline_create_guard,
    4474            2 :                 pgdata_lsn,
    4475            2 :                 None,
    4476            2 :             )
    4477            0 :             .await?;
    4478              : 
    4479            2 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4480            2 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4481              : 
    4482              :         // Flush the new layer files to disk, before we make the timeline as available to
    4483              :         // the outside world.
    4484              :         //
    4485              :         // Flush loop needs to be spawned in order to be able to flush.
    4486            2 :         unfinished_timeline.maybe_spawn_flush_loop();
    4487            2 : 
    4488            2 :         import_datadir::import_timeline_from_postgres_datadir(
    4489            2 :             unfinished_timeline,
    4490            2 :             &pgdata_path,
    4491            2 :             pgdata_lsn,
    4492            2 :             ctx,
    4493            2 :         )
    4494         7880 :         .await
    4495            2 :         .with_context(|| {
    4496            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    4497            2 :         })?;
    4498              : 
    4499            2 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    4500            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    4501            0 :                 "failpoint before-checkpoint-new-timeline"
    4502            0 :             )))
    4503            2 :         });
    4504              : 
    4505            2 :         unfinished_timeline
    4506            2 :             .freeze_and_flush()
    4507            2 :             .await
    4508            2 :             .with_context(|| {
    4509            0 :                 format!(
    4510            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    4511            0 :                 )
    4512            2 :             })?;
    4513              : 
    4514              :         // All done!
    4515            2 :         let timeline = raw_timeline.finish_creation()?;
    4516              : 
    4517              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4518              : 
    4519            2 :         Ok(CreateTimelineResult::Created(timeline))
    4520            2 :     }
    4521              : 
    4522          412 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    4523          412 :         RemoteTimelineClient::new(
    4524          412 :             self.remote_storage.clone(),
    4525          412 :             self.deletion_queue_client.clone(),
    4526          412 :             self.conf,
    4527          412 :             self.tenant_shard_id,
    4528          412 :             timeline_id,
    4529          412 :             self.generation,
    4530          412 :         )
    4531          412 :     }
    4532              : 
    4533              :     /// Call this before constructing a timeline, to build its required structures
    4534          412 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    4535          412 :         TimelineResources {
    4536          412 :             remote_client: self.build_timeline_remote_client(timeline_id),
    4537          412 :             timeline_get_throttle: self.timeline_get_throttle.clone(),
    4538          412 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    4539          412 :         }
    4540          412 :     }
    4541              : 
    4542              :     /// Creates intermediate timeline structure and its files.
    4543              :     ///
    4544              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    4545              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    4546              :     /// `finish_creation` to insert the Timeline into the timelines map.
    4547          412 :     async fn prepare_new_timeline<'a>(
    4548          412 :         &'a self,
    4549          412 :         new_timeline_id: TimelineId,
    4550          412 :         new_metadata: &TimelineMetadata,
    4551          412 :         create_guard: TimelineCreateGuard<'a>,
    4552          412 :         start_lsn: Lsn,
    4553          412 :         ancestor: Option<Arc<Timeline>>,
    4554          412 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    4555          412 :         let tenant_shard_id = self.tenant_shard_id;
    4556          412 : 
    4557          412 :         let resources = self.build_timeline_resources(new_timeline_id);
    4558          412 :         resources
    4559          412 :             .remote_client
    4560          412 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    4561              : 
    4562          412 :         let timeline_struct = self
    4563          412 :             .create_timeline_struct(
    4564          412 :                 new_timeline_id,
    4565          412 :                 new_metadata,
    4566          412 :                 ancestor,
    4567          412 :                 resources,
    4568          412 :                 CreateTimelineCause::Load,
    4569          412 :                 create_guard.idempotency.clone(),
    4570          412 :             )
    4571          412 :             .context("Failed to create timeline data structure")?;
    4572              : 
    4573          412 :         timeline_struct.init_empty_layer_map(start_lsn);
    4574              : 
    4575          412 :         if let Err(e) = self
    4576          412 :             .create_timeline_files(&create_guard.timeline_path)
    4577            0 :             .await
    4578              :         {
    4579            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    4580            0 :             cleanup_timeline_directory(create_guard);
    4581            0 :             return Err(e);
    4582          412 :         }
    4583          412 : 
    4584          412 :         debug!(
    4585            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    4586              :         );
    4587              : 
    4588          412 :         Ok(UninitializedTimeline::new(
    4589          412 :             self,
    4590          412 :             new_timeline_id,
    4591          412 :             Some((timeline_struct, create_guard)),
    4592          412 :         ))
    4593          412 :     }
    4594              : 
    4595          412 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    4596          412 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    4597              : 
    4598          412 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    4599            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    4600          412 :         });
    4601              : 
    4602          412 :         Ok(())
    4603          412 :     }
    4604              : 
    4605              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    4606              :     /// concurrent attempts to create the same timeline.
    4607              :     ///
    4608              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    4609              :     /// offloaded timelines or not.
    4610          418 :     fn create_timeline_create_guard(
    4611          418 :         &self,
    4612          418 :         timeline_id: TimelineId,
    4613          418 :         idempotency: CreateTimelineIdempotency,
    4614          418 :         allow_offloaded: bool,
    4615          418 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    4616          418 :         let tenant_shard_id = self.tenant_shard_id;
    4617          418 : 
    4618          418 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    4619              : 
    4620          418 :         let create_guard = TimelineCreateGuard::new(
    4621          418 :             self,
    4622          418 :             timeline_id,
    4623          418 :             timeline_path.clone(),
    4624          418 :             idempotency,
    4625          418 :             allow_offloaded,
    4626          418 :         )?;
    4627              : 
    4628              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    4629              :         // for creation.
    4630              :         // A timeline directory should never exist on disk already:
    4631              :         // - a previous failed creation would have cleaned up after itself
    4632              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    4633              :         //
    4634              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    4635              :         // this error may indicate a bug in cleanup on failed creations.
    4636          416 :         if timeline_path.exists() {
    4637            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    4638            0 :                 "Timeline directory already exists! This is a bug."
    4639            0 :             )));
    4640          416 :         }
    4641          416 : 
    4642          416 :         Ok(create_guard)
    4643          418 :     }
    4644              : 
    4645              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    4646              :     ///
    4647              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    4648            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    4649              :     pub async fn gather_size_inputs(
    4650              :         &self,
    4651              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    4652              :         // (only if it is shorter than the real cutoff).
    4653              :         max_retention_period: Option<u64>,
    4654              :         cause: LogicalSizeCalculationCause,
    4655              :         cancel: &CancellationToken,
    4656              :         ctx: &RequestContext,
    4657              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    4658              :         let logical_sizes_at_once = self
    4659              :             .conf
    4660              :             .concurrent_tenant_size_logical_size_queries
    4661              :             .inner();
    4662              : 
    4663              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    4664              :         //
    4665              :         // But the only case where we need to run multiple of these at once is when we
    4666              :         // request a size for a tenant manually via API, while another background calculation
    4667              :         // is in progress (which is not a common case).
    4668              :         //
    4669              :         // See more for on the issue #2748 condenced out of the initial PR review.
    4670              :         let mut shared_cache = tokio::select! {
    4671              :             locked = self.cached_logical_sizes.lock() => locked,
    4672              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    4673              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    4674              :         };
    4675              : 
    4676              :         size::gather_inputs(
    4677              :             self,
    4678              :             logical_sizes_at_once,
    4679              :             max_retention_period,
    4680              :             &mut shared_cache,
    4681              :             cause,
    4682              :             cancel,
    4683              :             ctx,
    4684              :         )
    4685              :         .await
    4686              :     }
    4687              : 
    4688              :     /// Calculate synthetic tenant size and cache the result.
    4689              :     /// This is periodically called by background worker.
    4690              :     /// result is cached in tenant struct
    4691            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    4692              :     pub async fn calculate_synthetic_size(
    4693              :         &self,
    4694              :         cause: LogicalSizeCalculationCause,
    4695              :         cancel: &CancellationToken,
    4696              :         ctx: &RequestContext,
    4697              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    4698              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    4699              : 
    4700              :         let size = inputs.calculate();
    4701              : 
    4702              :         self.set_cached_synthetic_size(size);
    4703              : 
    4704              :         Ok(size)
    4705              :     }
    4706              : 
    4707              :     /// Cache given synthetic size and update the metric value
    4708            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    4709            0 :         self.cached_synthetic_tenant_size
    4710            0 :             .store(size, Ordering::Relaxed);
    4711            0 : 
    4712            0 :         // Only shard zero should be calculating synthetic sizes
    4713            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    4714              : 
    4715            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    4716            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    4717            0 :             .unwrap()
    4718            0 :             .set(size);
    4719            0 :     }
    4720              : 
    4721            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    4722            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    4723            0 :     }
    4724              : 
    4725              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    4726              :     ///
    4727              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    4728              :     /// from an external API handler.
    4729              :     ///
    4730              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    4731              :     /// still bounded by tenant/timeline shutdown.
    4732            0 :     #[tracing::instrument(skip_all)]
    4733              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    4734              :         let timelines = self.timelines.lock().unwrap().clone();
    4735              : 
    4736            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    4737            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    4738            0 :             timeline.freeze_and_flush().await?;
    4739            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    4740            0 :             timeline.remote_client.wait_completion().await?;
    4741              : 
    4742            0 :             Ok(())
    4743            0 :         }
    4744              : 
    4745              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    4746              :         // aborted when this function's future is cancelled: they should stay alive
    4747              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    4748              :         // before Timeline shutdown completes.
    4749              :         let mut results = FuturesUnordered::new();
    4750              : 
    4751              :         for (_timeline_id, timeline) in timelines {
    4752              :             // Run each timeline's flush in a task holding the timeline's gate: this
    4753              :             // means that if this function's future is cancelled, the Timeline shutdown
    4754              :             // will still wait for any I/O in here to complete.
    4755              :             let Ok(gate) = timeline.gate.enter() else {
    4756              :                 continue;
    4757              :             };
    4758            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    4759              :             results.push(jh);
    4760              :         }
    4761              : 
    4762              :         while let Some(r) = results.next().await {
    4763              :             if let Err(e) = r {
    4764              :                 if !e.is_cancelled() && !e.is_panic() {
    4765              :                     tracing::error!("unexpected join error: {e:?}");
    4766              :                 }
    4767              :             }
    4768              :         }
    4769              : 
    4770              :         // The flushes we did above were just writes, but the Tenant might have had
    4771              :         // pending deletions as well from recent compaction/gc: we want to flush those
    4772              :         // as well.  This requires flushing the global delete queue.  This is cheap
    4773              :         // because it's typically a no-op.
    4774              :         match self.deletion_queue_client.flush_execute().await {
    4775              :             Ok(_) => {}
    4776              :             Err(DeletionQueueError::ShuttingDown) => {}
    4777              :         }
    4778              : 
    4779              :         Ok(())
    4780              :     }
    4781              : 
    4782            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    4783            0 :         self.tenant_conf.load().tenant_conf.clone()
    4784            0 :     }
    4785              : 
    4786              :     /// How much local storage would this tenant like to have?  It can cope with
    4787              :     /// less than this (via eviction and on-demand downloads), but this function enables
    4788              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    4789              :     /// by keeping important things on local disk.
    4790              :     ///
    4791              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    4792              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    4793              :     /// actually use more than they report here.
    4794            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    4795            0 :         let timelines = self.timelines.lock().unwrap();
    4796            0 : 
    4797            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    4798            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    4799            0 :         // of them is used actively enough to occupy space on disk.
    4800            0 :         timelines
    4801            0 :             .values()
    4802            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    4803            0 :             .max()
    4804            0 :             .unwrap_or(0)
    4805            0 :     }
    4806              : 
    4807              :     /// Serialize and write the latest TenantManifest to remote storage.
    4808            2 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    4809              :         // Only one manifest write may be done at at time, and the contents of the manifest
    4810              :         // must be loaded while holding this lock. This makes it safe to call this function
    4811              :         // from anywhere without worrying about colliding updates.
    4812            2 :         let mut guard = tokio::select! {
    4813            2 :             g = self.tenant_manifest_upload.lock() => {
    4814            2 :                 g
    4815              :             },
    4816            2 :             _ = self.cancel.cancelled() => {
    4817            0 :                 return Err(TenantManifestError::Cancelled);
    4818              :             }
    4819              :         };
    4820              : 
    4821            2 :         let manifest = self.build_tenant_manifest();
    4822            2 :         if Some(&manifest) == (*guard).as_ref() {
    4823              :             // Optimisation: skip uploads that don't change anything.
    4824            0 :             return Ok(());
    4825            2 :         }
    4826            2 : 
    4827            2 :         upload_tenant_manifest(
    4828            2 :             &self.remote_storage,
    4829            2 :             &self.tenant_shard_id,
    4830            2 :             self.generation,
    4831            2 :             &manifest,
    4832            2 :             &self.cancel,
    4833            2 :         )
    4834            6 :         .await
    4835            2 :         .map_err(|e| {
    4836            0 :             if self.cancel.is_cancelled() {
    4837            0 :                 TenantManifestError::Cancelled
    4838              :             } else {
    4839            0 :                 TenantManifestError::RemoteStorage(e)
    4840              :             }
    4841            2 :         })?;
    4842              : 
    4843              :         // Store the successfully uploaded manifest, so that future callers can avoid
    4844              :         // re-uploading the same thing.
    4845            2 :         *guard = Some(manifest);
    4846            2 : 
    4847            2 :         Ok(())
    4848            2 :     }
    4849              : }
    4850              : 
    4851              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    4852              : /// to get bootstrap data for timeline initialization.
    4853            0 : async fn run_initdb(
    4854            0 :     conf: &'static PageServerConf,
    4855            0 :     initdb_target_dir: &Utf8Path,
    4856            0 :     pg_version: u32,
    4857            0 :     cancel: &CancellationToken,
    4858            0 : ) -> Result<(), InitdbError> {
    4859            0 :     let initdb_bin_path = conf
    4860            0 :         .pg_bin_dir(pg_version)
    4861            0 :         .map_err(InitdbError::Other)?
    4862            0 :         .join("initdb");
    4863            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    4864            0 :     info!(
    4865            0 :         "running {} in {}, libdir: {}",
    4866              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    4867              :     );
    4868              : 
    4869            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    4870              : 
    4871            0 :     let mut initdb_command = tokio::process::Command::new(&initdb_bin_path);
    4872            0 :     initdb_command
    4873            0 :         .args(["--pgdata", initdb_target_dir.as_ref()])
    4874            0 :         .args(["--username", &conf.superuser])
    4875            0 :         .args(["--encoding", "utf8"])
    4876            0 :         .args(["--locale", &conf.locale])
    4877            0 :         .arg("--no-instructions")
    4878            0 :         .arg("--no-sync")
    4879            0 :         .env_clear()
    4880            0 :         .env("LD_LIBRARY_PATH", &initdb_lib_dir)
    4881            0 :         .env("DYLD_LIBRARY_PATH", &initdb_lib_dir)
    4882            0 :         .stdin(std::process::Stdio::null())
    4883            0 :         // stdout invocation produces the same output every time, we don't need it
    4884            0 :         .stdout(std::process::Stdio::null())
    4885            0 :         // we would be interested in the stderr output, if there was any
    4886            0 :         .stderr(std::process::Stdio::piped());
    4887            0 : 
    4888            0 :     // Before version 14, only the libc provide was available.
    4889            0 :     if pg_version > 14 {
    4890              :         // Version 17 brought with it a builtin locale provider which only provides
    4891              :         // C and C.UTF-8. While being safer for collation purposes since it is
    4892              :         // guaranteed to be consistent throughout a major release, it is also more
    4893              :         // performant.
    4894            0 :         let locale_provider = if pg_version >= 17 { "builtin" } else { "libc" };
    4895              : 
    4896            0 :         initdb_command.args(["--locale-provider", locale_provider]);
    4897            0 :     }
    4898              : 
    4899            0 :     let initdb_proc = initdb_command.spawn()?;
    4900              : 
    4901              :     // Ideally we'd select here with the cancellation token, but the problem is that
    4902              :     // we can't safely terminate initdb: it launches processes of its own, and killing
    4903              :     // initdb doesn't kill them. After we return from this function, we want the target
    4904              :     // directory to be able to be cleaned up.
    4905              :     // See https://github.com/neondatabase/neon/issues/6385
    4906            0 :     let initdb_output = initdb_proc.wait_with_output().await?;
    4907            0 :     if !initdb_output.status.success() {
    4908            0 :         return Err(InitdbError::Failed(
    4909            0 :             initdb_output.status,
    4910            0 :             initdb_output.stderr,
    4911            0 :         ));
    4912            0 :     }
    4913            0 : 
    4914            0 :     // This isn't true cancellation support, see above. Still return an error to
    4915            0 :     // excercise the cancellation code path.
    4916            0 :     if cancel.is_cancelled() {
    4917            0 :         return Err(InitdbError::Cancelled);
    4918            0 :     }
    4919            0 : 
    4920            0 :     Ok(())
    4921            0 : }
    4922              : 
    4923              : /// Dump contents of a layer file to stdout.
    4924            0 : pub async fn dump_layerfile_from_path(
    4925            0 :     path: &Utf8Path,
    4926            0 :     verbose: bool,
    4927            0 :     ctx: &RequestContext,
    4928            0 : ) -> anyhow::Result<()> {
    4929              :     use std::os::unix::fs::FileExt;
    4930              : 
    4931              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    4932              :     // file.
    4933            0 :     let file = File::open(path)?;
    4934            0 :     let mut header_buf = [0u8; 2];
    4935            0 :     file.read_exact_at(&mut header_buf, 0)?;
    4936              : 
    4937            0 :     match u16::from_be_bytes(header_buf) {
    4938              :         crate::IMAGE_FILE_MAGIC => {
    4939            0 :             ImageLayer::new_for_path(path, file)?
    4940            0 :                 .dump(verbose, ctx)
    4941            0 :                 .await?
    4942              :         }
    4943              :         crate::DELTA_FILE_MAGIC => {
    4944            0 :             DeltaLayer::new_for_path(path, file)?
    4945            0 :                 .dump(verbose, ctx)
    4946            0 :                 .await?
    4947              :         }
    4948            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    4949              :     }
    4950              : 
    4951            0 :     Ok(())
    4952            0 : }
    4953              : 
    4954              : #[cfg(test)]
    4955              : pub(crate) mod harness {
    4956              :     use bytes::{Bytes, BytesMut};
    4957              :     use once_cell::sync::OnceCell;
    4958              :     use pageserver_api::models::ShardParameters;
    4959              :     use pageserver_api::shard::ShardIndex;
    4960              :     use utils::logging;
    4961              : 
    4962              :     use crate::deletion_queue::mock::MockDeletionQueue;
    4963              :     use crate::l0_flush::L0FlushConfig;
    4964              :     use crate::walredo::apply_neon;
    4965              :     use pageserver_api::key::Key;
    4966              :     use pageserver_api::record::NeonWalRecord;
    4967              : 
    4968              :     use super::*;
    4969              :     use hex_literal::hex;
    4970              :     use utils::id::TenantId;
    4971              : 
    4972              :     pub const TIMELINE_ID: TimelineId =
    4973              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    4974              :     pub const NEW_TIMELINE_ID: TimelineId =
    4975              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    4976              : 
    4977              :     /// Convenience function to create a page image with given string as the only content
    4978      5028700 :     pub fn test_img(s: &str) -> Bytes {
    4979      5028700 :         let mut buf = BytesMut::new();
    4980      5028700 :         buf.extend_from_slice(s.as_bytes());
    4981      5028700 :         buf.resize(64, 0);
    4982      5028700 : 
    4983      5028700 :         buf.freeze()
    4984      5028700 :     }
    4985              : 
    4986              :     impl From<TenantConf> for TenantConfOpt {
    4987          192 :         fn from(tenant_conf: TenantConf) -> Self {
    4988          192 :             Self {
    4989          192 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    4990          192 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    4991          192 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    4992          192 :                 compaction_period: Some(tenant_conf.compaction_period),
    4993          192 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    4994          192 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    4995          192 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    4996          192 :                 gc_period: Some(tenant_conf.gc_period),
    4997          192 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    4998          192 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    4999          192 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5000          192 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5001          192 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5002          192 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5003          192 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5004          192 :                 evictions_low_residence_duration_metric_threshold: Some(
    5005          192 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5006          192 :                 ),
    5007          192 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5008          192 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5009          192 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5010          192 :                 image_layer_creation_check_threshold: Some(
    5011          192 :                     tenant_conf.image_layer_creation_check_threshold,
    5012          192 :                 ),
    5013          192 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5014          192 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5015          192 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5016          192 :             }
    5017          192 :         }
    5018              :     }
    5019              : 
    5020              :     pub struct TenantHarness {
    5021              :         pub conf: &'static PageServerConf,
    5022              :         pub tenant_conf: TenantConf,
    5023              :         pub tenant_shard_id: TenantShardId,
    5024              :         pub generation: Generation,
    5025              :         pub shard: ShardIndex,
    5026              :         pub remote_storage: GenericRemoteStorage,
    5027              :         pub remote_fs_dir: Utf8PathBuf,
    5028              :         pub deletion_queue: MockDeletionQueue,
    5029              :     }
    5030              : 
    5031              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5032              : 
    5033          208 :     pub(crate) fn setup_logging() {
    5034          208 :         LOG_HANDLE.get_or_init(|| {
    5035          196 :             logging::init(
    5036          196 :                 logging::LogFormat::Test,
    5037          196 :                 // enable it in case the tests exercise code paths that use
    5038          196 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5039          196 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5040          196 :                 logging::Output::Stdout,
    5041          196 :             )
    5042          196 :             .expect("Failed to init test logging")
    5043          208 :         });
    5044          208 :     }
    5045              : 
    5046              :     impl TenantHarness {
    5047          192 :         pub async fn create_custom(
    5048          192 :             test_name: &'static str,
    5049          192 :             tenant_conf: TenantConf,
    5050          192 :             tenant_id: TenantId,
    5051          192 :             shard_identity: ShardIdentity,
    5052          192 :             generation: Generation,
    5053          192 :         ) -> anyhow::Result<Self> {
    5054          192 :             setup_logging();
    5055          192 : 
    5056          192 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5057          192 :             let _ = fs::remove_dir_all(&repo_dir);
    5058          192 :             fs::create_dir_all(&repo_dir)?;
    5059              : 
    5060          192 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5061          192 :             // Make a static copy of the config. This can never be free'd, but that's
    5062          192 :             // OK in a test.
    5063          192 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5064          192 : 
    5065          192 :             let shard = shard_identity.shard_index();
    5066          192 :             let tenant_shard_id = TenantShardId {
    5067          192 :                 tenant_id,
    5068          192 :                 shard_number: shard.shard_number,
    5069          192 :                 shard_count: shard.shard_count,
    5070          192 :             };
    5071          192 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5072          192 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5073              : 
    5074              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5075          192 :             let remote_fs_dir = conf.workdir.join("localfs");
    5076          192 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5077          192 :             let config = RemoteStorageConfig {
    5078          192 :                 storage: RemoteStorageKind::LocalFs {
    5079          192 :                     local_path: remote_fs_dir.clone(),
    5080          192 :                 },
    5081          192 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5082          192 :             };
    5083          192 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5084          192 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5085          192 : 
    5086          192 :             Ok(Self {
    5087          192 :                 conf,
    5088          192 :                 tenant_conf,
    5089          192 :                 tenant_shard_id,
    5090          192 :                 generation,
    5091          192 :                 shard,
    5092          192 :                 remote_storage,
    5093          192 :                 remote_fs_dir,
    5094          192 :                 deletion_queue,
    5095          192 :             })
    5096          192 :         }
    5097              : 
    5098          180 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5099          180 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5100          180 :             // The tests perform them manually if needed.
    5101          180 :             let tenant_conf = TenantConf {
    5102          180 :                 gc_period: Duration::ZERO,
    5103          180 :                 compaction_period: Duration::ZERO,
    5104          180 :                 ..TenantConf::default()
    5105          180 :             };
    5106          180 :             let tenant_id = TenantId::generate();
    5107          180 :             let shard = ShardIdentity::unsharded();
    5108          180 :             Self::create_custom(
    5109          180 :                 test_name,
    5110          180 :                 tenant_conf,
    5111          180 :                 tenant_id,
    5112          180 :                 shard,
    5113          180 :                 Generation::new(0xdeadbeef),
    5114          180 :             )
    5115            0 :             .await
    5116          180 :         }
    5117              : 
    5118           20 :         pub fn span(&self) -> tracing::Span {
    5119           20 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5120           20 :         }
    5121              : 
    5122          192 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5123          192 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5124          192 :             (
    5125          192 :                 self.do_try_load(&ctx)
    5126         1865 :                     .await
    5127          192 :                     .expect("failed to load test tenant"),
    5128          192 :                 ctx,
    5129          192 :             )
    5130          192 :         }
    5131              : 
    5132          192 :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5133              :         pub(crate) async fn do_try_load(
    5134              :             &self,
    5135              :             ctx: &RequestContext,
    5136              :         ) -> anyhow::Result<Arc<Tenant>> {
    5137              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5138              : 
    5139              :             let tenant = Arc::new(Tenant::new(
    5140              :                 TenantState::Attaching,
    5141              :                 self.conf,
    5142              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5143              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5144              :                     self.generation,
    5145              :                     &ShardParameters::default(),
    5146              :                 ))
    5147              :                 .unwrap(),
    5148              :                 // This is a legacy/test code path: sharding isn't supported here.
    5149              :                 ShardIdentity::unsharded(),
    5150              :                 Some(walredo_mgr),
    5151              :                 self.tenant_shard_id,
    5152              :                 self.remote_storage.clone(),
    5153              :                 self.deletion_queue.new_client(),
    5154              :                 // TODO: ideally we should run all unit tests with both configs
    5155              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5156              :             ));
    5157              : 
    5158              :             let preload = tenant
    5159              :                 .preload(&self.remote_storage, CancellationToken::new())
    5160              :                 .await?;
    5161              :             tenant.attach(Some(preload), ctx).await?;
    5162              : 
    5163              :             tenant.state.send_replace(TenantState::Active);
    5164              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5165              :                 timeline.set_state(TimelineState::Active);
    5166              :             }
    5167              :             Ok(tenant)
    5168              :         }
    5169              : 
    5170            2 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5171            2 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5172            2 :         }
    5173              :     }
    5174              : 
    5175              :     // Mock WAL redo manager that doesn't do much
    5176              :     pub(crate) struct TestRedoManager;
    5177              : 
    5178              :     impl TestRedoManager {
    5179              :         /// # Cancel-Safety
    5180              :         ///
    5181              :         /// This method is cancellation-safe.
    5182          410 :         pub async fn request_redo(
    5183          410 :             &self,
    5184          410 :             key: Key,
    5185          410 :             lsn: Lsn,
    5186          410 :             base_img: Option<(Lsn, Bytes)>,
    5187          410 :             records: Vec<(Lsn, NeonWalRecord)>,
    5188          410 :             _pg_version: u32,
    5189          410 :         ) -> Result<Bytes, walredo::Error> {
    5190          570 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5191          410 :             if records_neon {
    5192              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5193          410 :                 let mut page = match (base_img, records.first()) {
    5194          344 :                     (Some((_lsn, img)), _) => {
    5195          344 :                         let mut page = BytesMut::new();
    5196          344 :                         page.extend_from_slice(&img);
    5197          344 :                         page
    5198              :                     }
    5199           66 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5200              :                     _ => {
    5201            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5202              :                     }
    5203              :                 };
    5204              : 
    5205          980 :                 for (record_lsn, record) in records {
    5206          570 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5207              :                 }
    5208          410 :                 Ok(page.freeze())
    5209              :             } else {
    5210              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5211            0 :                 let s = format!(
    5212            0 :                     "redo for {} to get to {}, with {} and {} records",
    5213            0 :                     key,
    5214            0 :                     lsn,
    5215            0 :                     if base_img.is_some() {
    5216            0 :                         "base image"
    5217              :                     } else {
    5218            0 :                         "no base image"
    5219              :                     },
    5220            0 :                     records.len()
    5221            0 :                 );
    5222            0 :                 println!("{s}");
    5223            0 : 
    5224            0 :                 Ok(test_img(&s))
    5225              :             }
    5226          410 :         }
    5227              :     }
    5228              : }
    5229              : 
    5230              : #[cfg(test)]
    5231              : mod tests {
    5232              :     use std::collections::{BTreeMap, BTreeSet};
    5233              : 
    5234              :     use super::*;
    5235              :     use crate::keyspace::KeySpaceAccum;
    5236              :     use crate::tenant::harness::*;
    5237              :     use crate::tenant::timeline::CompactFlags;
    5238              :     use crate::DEFAULT_PG_VERSION;
    5239              :     use bytes::{Bytes, BytesMut};
    5240              :     use hex_literal::hex;
    5241              :     use itertools::Itertools;
    5242              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
    5243              :     use pageserver_api::keyspace::KeySpace;
    5244              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5245              :     use pageserver_api::value::Value;
    5246              :     use pageserver_compaction::helpers::overlaps_with;
    5247              :     use rand::{thread_rng, Rng};
    5248              :     use storage_layer::PersistentLayerKey;
    5249              :     use tests::storage_layer::ValuesReconstructState;
    5250              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5251              :     use timeline::DeltaLayerTestDesc;
    5252              :     use utils::id::TenantId;
    5253              : 
    5254              :     #[cfg(feature = "testing")]
    5255              :     use pageserver_api::record::NeonWalRecord;
    5256              :     #[cfg(feature = "testing")]
    5257              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5258              :     #[cfg(feature = "testing")]
    5259              :     use timeline::GcInfo;
    5260              : 
    5261              :     static TEST_KEY: Lazy<Key> =
    5262           18 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5263              : 
    5264              :     #[tokio::test]
    5265            2 :     async fn test_basic() -> anyhow::Result<()> {
    5266           14 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5267            2 :         let tline = tenant
    5268            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5269            6 :             .await?;
    5270            2 : 
    5271            2 :         let mut writer = tline.writer().await;
    5272            2 :         writer
    5273            2 :             .put(
    5274            2 :                 *TEST_KEY,
    5275            2 :                 Lsn(0x10),
    5276            2 :                 &Value::Image(test_img("foo at 0x10")),
    5277            2 :                 &ctx,
    5278            2 :             )
    5279            2 :             .await?;
    5280            2 :         writer.finish_write(Lsn(0x10));
    5281            2 :         drop(writer);
    5282            2 : 
    5283            2 :         let mut writer = tline.writer().await;
    5284            2 :         writer
    5285            2 :             .put(
    5286            2 :                 *TEST_KEY,
    5287            2 :                 Lsn(0x20),
    5288            2 :                 &Value::Image(test_img("foo at 0x20")),
    5289            2 :                 &ctx,
    5290            2 :             )
    5291            2 :             .await?;
    5292            2 :         writer.finish_write(Lsn(0x20));
    5293            2 :         drop(writer);
    5294            2 : 
    5295            2 :         assert_eq!(
    5296            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5297            2 :             test_img("foo at 0x10")
    5298            2 :         );
    5299            2 :         assert_eq!(
    5300            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5301            2 :             test_img("foo at 0x10")
    5302            2 :         );
    5303            2 :         assert_eq!(
    5304            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5305            2 :             test_img("foo at 0x20")
    5306            2 :         );
    5307            2 : 
    5308            2 :         Ok(())
    5309            2 :     }
    5310              : 
    5311              :     #[tokio::test]
    5312            2 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5313            2 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5314            2 :             .await?
    5315            2 :             .load()
    5316           20 :             .await;
    5317            2 :         let _ = tenant
    5318            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5319            6 :             .await?;
    5320            2 : 
    5321            2 :         match tenant
    5322            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5323            2 :             .await
    5324            2 :         {
    5325            2 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5326            2 :             Err(e) => assert_eq!(
    5327            2 :                 e.to_string(),
    5328            2 :                 "timeline already exists with different parameters".to_string()
    5329            2 :             ),
    5330            2 :         }
    5331            2 : 
    5332            2 :         Ok(())
    5333            2 :     }
    5334              : 
    5335              :     /// Convenience function to create a page image with given string as the only content
    5336           10 :     pub fn test_value(s: &str) -> Value {
    5337           10 :         let mut buf = BytesMut::new();
    5338           10 :         buf.extend_from_slice(s.as_bytes());
    5339           10 :         Value::Image(buf.freeze())
    5340           10 :     }
    5341              : 
    5342              :     ///
    5343              :     /// Test branch creation
    5344              :     ///
    5345              :     #[tokio::test]
    5346            2 :     async fn test_branch() -> anyhow::Result<()> {
    5347            2 :         use std::str::from_utf8;
    5348            2 : 
    5349           20 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5350            2 :         let tline = tenant
    5351            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5352            6 :             .await?;
    5353            2 :         let mut writer = tline.writer().await;
    5354            2 : 
    5355            2 :         #[allow(non_snake_case)]
    5356            2 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5357            2 :         #[allow(non_snake_case)]
    5358            2 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5359            2 : 
    5360            2 :         // Insert a value on the timeline
    5361            2 :         writer
    5362            2 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5363            2 :             .await?;
    5364            2 :         writer
    5365            2 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5366            2 :             .await?;
    5367            2 :         writer.finish_write(Lsn(0x20));
    5368            2 : 
    5369            2 :         writer
    5370            2 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5371            2 :             .await?;
    5372            2 :         writer.finish_write(Lsn(0x30));
    5373            2 :         writer
    5374            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5375            2 :             .await?;
    5376            2 :         writer.finish_write(Lsn(0x40));
    5377            2 : 
    5378            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5379            2 : 
    5380            2 :         // Branch the history, modify relation differently on the new timeline
    5381            2 :         tenant
    5382            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5383            2 :             .await?;
    5384            2 :         let newtline = tenant
    5385            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5386            2 :             .expect("Should have a local timeline");
    5387            2 :         let mut new_writer = newtline.writer().await;
    5388            2 :         new_writer
    5389            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5390            2 :             .await?;
    5391            2 :         new_writer.finish_write(Lsn(0x40));
    5392            2 : 
    5393            2 :         // Check page contents on both branches
    5394            2 :         assert_eq!(
    5395            2 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5396            2 :             "foo at 0x40"
    5397            2 :         );
    5398            2 :         assert_eq!(
    5399            2 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5400            2 :             "bar at 0x40"
    5401            2 :         );
    5402            2 :         assert_eq!(
    5403            2 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5404            2 :             "foobar at 0x20"
    5405            2 :         );
    5406            2 : 
    5407            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5408            2 : 
    5409            2 :         Ok(())
    5410            2 :     }
    5411              : 
    5412           20 :     async fn make_some_layers(
    5413           20 :         tline: &Timeline,
    5414           20 :         start_lsn: Lsn,
    5415           20 :         ctx: &RequestContext,
    5416           20 :     ) -> anyhow::Result<()> {
    5417           20 :         let mut lsn = start_lsn;
    5418              :         {
    5419           20 :             let mut writer = tline.writer().await;
    5420              :             // Create a relation on the timeline
    5421           20 :             writer
    5422           20 :                 .put(
    5423           20 :                     *TEST_KEY,
    5424           20 :                     lsn,
    5425           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5426           20 :                     ctx,
    5427           20 :                 )
    5428           10 :                 .await?;
    5429           20 :             writer.finish_write(lsn);
    5430           20 :             lsn += 0x10;
    5431           20 :             writer
    5432           20 :                 .put(
    5433           20 :                     *TEST_KEY,
    5434           20 :                     lsn,
    5435           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5436           20 :                     ctx,
    5437           20 :                 )
    5438            0 :                 .await?;
    5439           20 :             writer.finish_write(lsn);
    5440           20 :             lsn += 0x10;
    5441           20 :         }
    5442           20 :         tline.freeze_and_flush().await?;
    5443              :         {
    5444           20 :             let mut writer = tline.writer().await;
    5445           20 :             writer
    5446           20 :                 .put(
    5447           20 :                     *TEST_KEY,
    5448           20 :                     lsn,
    5449           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5450           20 :                     ctx,
    5451           20 :                 )
    5452           10 :                 .await?;
    5453           20 :             writer.finish_write(lsn);
    5454           20 :             lsn += 0x10;
    5455           20 :             writer
    5456           20 :                 .put(
    5457           20 :                     *TEST_KEY,
    5458           20 :                     lsn,
    5459           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5460           20 :                     ctx,
    5461           20 :                 )
    5462            0 :                 .await?;
    5463           20 :             writer.finish_write(lsn);
    5464           20 :         }
    5465           21 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5466           20 :     }
    5467              : 
    5468              :     #[tokio::test(start_paused = true)]
    5469            2 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5470            2 :         let (tenant, ctx) =
    5471            2 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5472            2 :                 .await?
    5473            2 :                 .load()
    5474           20 :                 .await;
    5475            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5476            2 :         // initial transition into AttachedSingle.
    5477            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5478            2 :         tokio::time::resume();
    5479            2 :         let tline = tenant
    5480            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5481            6 :             .await?;
    5482            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5483            2 : 
    5484            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5485            2 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5486            2 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5487            2 :         // below should fail.
    5488            2 :         tenant
    5489            2 :             .gc_iteration(
    5490            2 :                 Some(TIMELINE_ID),
    5491            2 :                 0x10,
    5492            2 :                 Duration::ZERO,
    5493            2 :                 &CancellationToken::new(),
    5494            2 :                 &ctx,
    5495            2 :             )
    5496            2 :             .await?;
    5497            2 : 
    5498            2 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5499            2 :         match tenant
    5500            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5501            2 :             .await
    5502            2 :         {
    5503            2 :             Ok(_) => panic!("branching should have failed"),
    5504            2 :             Err(err) => {
    5505            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5506            2 :                     panic!("wrong error type")
    5507            2 :                 };
    5508            2 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    5509            2 :                 assert!(err
    5510            2 :                     .source()
    5511            2 :                     .unwrap()
    5512            2 :                     .to_string()
    5513            2 :                     .contains("we might've already garbage collected needed data"))
    5514            2 :             }
    5515            2 :         }
    5516            2 : 
    5517            2 :         Ok(())
    5518            2 :     }
    5519              : 
    5520              :     #[tokio::test]
    5521            2 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    5522            2 :         let (tenant, ctx) =
    5523            2 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    5524            2 :                 .await?
    5525            2 :                 .load()
    5526           20 :                 .await;
    5527            2 : 
    5528            2 :         let tline = tenant
    5529            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    5530            5 :             .await?;
    5531            2 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    5532            2 :         match tenant
    5533            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5534            2 :             .await
    5535            2 :         {
    5536            2 :             Ok(_) => panic!("branching should have failed"),
    5537            2 :             Err(err) => {
    5538            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5539            2 :                     panic!("wrong error type");
    5540            2 :                 };
    5541            2 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    5542            2 :                 assert!(&err
    5543            2 :                     .source()
    5544            2 :                     .unwrap()
    5545            2 :                     .to_string()
    5546            2 :                     .contains("is earlier than latest GC cutoff"));
    5547            2 :             }
    5548            2 :         }
    5549            2 : 
    5550            2 :         Ok(())
    5551            2 :     }
    5552              : 
    5553              :     /*
    5554              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    5555              :     // remove the old value, we'd need to work a little harder
    5556              :     #[tokio::test]
    5557              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    5558              :         let repo =
    5559              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    5560              :             .load();
    5561              : 
    5562              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    5563              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5564              : 
    5565              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    5566              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    5567              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    5568              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    5569              :             Ok(_) => panic!("request for page should have failed"),
    5570              :             Err(err) => assert!(err.to_string().contains("not found at")),
    5571              :         }
    5572              :         Ok(())
    5573              :     }
    5574              :      */
    5575              : 
    5576              :     #[tokio::test]
    5577            2 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    5578            2 :         let (tenant, ctx) =
    5579            2 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    5580            2 :                 .await?
    5581            2 :                 .load()
    5582           20 :                 .await;
    5583            2 :         let tline = tenant
    5584            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5585            6 :             .await?;
    5586            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5587            2 : 
    5588            2 :         tenant
    5589            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5590            2 :             .await?;
    5591            2 :         let newtline = tenant
    5592            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5593            2 :             .expect("Should have a local timeline");
    5594            2 : 
    5595            6 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5596            2 : 
    5597            2 :         tline.set_broken("test".to_owned());
    5598            2 : 
    5599            2 :         tenant
    5600            2 :             .gc_iteration(
    5601            2 :                 Some(TIMELINE_ID),
    5602            2 :                 0x10,
    5603            2 :                 Duration::ZERO,
    5604            2 :                 &CancellationToken::new(),
    5605            2 :                 &ctx,
    5606            2 :             )
    5607            2 :             .await?;
    5608            2 : 
    5609            2 :         // The branchpoints should contain all timelines, even ones marked
    5610            2 :         // as Broken.
    5611            2 :         {
    5612            2 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    5613            2 :             assert_eq!(branchpoints.len(), 1);
    5614            2 :             assert_eq!(
    5615            2 :                 branchpoints[0],
    5616            2 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    5617            2 :             );
    5618            2 :         }
    5619            2 : 
    5620            2 :         // You can read the key from the child branch even though the parent is
    5621            2 :         // Broken, as long as you don't need to access data from the parent.
    5622            2 :         assert_eq!(
    5623            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    5624            2 :             test_img(&format!("foo at {}", Lsn(0x70)))
    5625            2 :         );
    5626            2 : 
    5627            2 :         // This needs to traverse to the parent, and fails.
    5628            2 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    5629            2 :         assert!(
    5630            2 :             err.to_string().starts_with(&format!(
    5631            2 :                 "bad state on timeline {}: Broken",
    5632            2 :                 tline.timeline_id
    5633            2 :             )),
    5634            2 :             "{err}"
    5635            2 :         );
    5636            2 : 
    5637            2 :         Ok(())
    5638            2 :     }
    5639              : 
    5640              :     #[tokio::test]
    5641            2 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    5642            2 :         let (tenant, ctx) =
    5643            2 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    5644            2 :                 .await?
    5645            2 :                 .load()
    5646           20 :                 .await;
    5647            2 :         let tline = tenant
    5648            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5649            6 :             .await?;
    5650            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5651            2 : 
    5652            2 :         tenant
    5653            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5654            2 :             .await?;
    5655            2 :         let newtline = tenant
    5656            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5657            2 :             .expect("Should have a local timeline");
    5658            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5659            2 :         tenant
    5660            2 :             .gc_iteration(
    5661            2 :                 Some(TIMELINE_ID),
    5662            2 :                 0x10,
    5663            2 :                 Duration::ZERO,
    5664            2 :                 &CancellationToken::new(),
    5665            2 :                 &ctx,
    5666            2 :             )
    5667            2 :             .await?;
    5668            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    5669            2 : 
    5670            2 :         Ok(())
    5671            2 :     }
    5672              :     #[tokio::test]
    5673            2 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    5674            2 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    5675            2 :             .await?
    5676            2 :             .load()
    5677           20 :             .await;
    5678            2 :         let tline = tenant
    5679            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5680            6 :             .await?;
    5681            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5682            2 : 
    5683            2 :         tenant
    5684            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5685            2 :             .await?;
    5686            2 :         let newtline = tenant
    5687            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5688            2 :             .expect("Should have a local timeline");
    5689            2 : 
    5690            6 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5691            2 : 
    5692            2 :         // run gc on parent
    5693            2 :         tenant
    5694            2 :             .gc_iteration(
    5695            2 :                 Some(TIMELINE_ID),
    5696            2 :                 0x10,
    5697            2 :                 Duration::ZERO,
    5698            2 :                 &CancellationToken::new(),
    5699            2 :                 &ctx,
    5700            2 :             )
    5701            2 :             .await?;
    5702            2 : 
    5703            2 :         // Check that the data is still accessible on the branch.
    5704            2 :         assert_eq!(
    5705            7 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    5706            2 :             test_img(&format!("foo at {}", Lsn(0x40)))
    5707            2 :         );
    5708            2 : 
    5709            2 :         Ok(())
    5710            2 :     }
    5711              : 
    5712              :     #[tokio::test]
    5713            2 :     async fn timeline_load() -> anyhow::Result<()> {
    5714            2 :         const TEST_NAME: &str = "timeline_load";
    5715            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    5716            2 :         {
    5717           20 :             let (tenant, ctx) = harness.load().await;
    5718            2 :             let tline = tenant
    5719            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    5720            6 :                 .await?;
    5721            6 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    5722            2 :             // so that all uploads finish & we can call harness.load() below again
    5723            2 :             tenant
    5724            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    5725            2 :                 .instrument(harness.span())
    5726            2 :                 .await
    5727            2 :                 .ok()
    5728            2 :                 .unwrap();
    5729            2 :         }
    5730            2 : 
    5731           17 :         let (tenant, _ctx) = harness.load().await;
    5732            2 :         tenant
    5733            2 :             .get_timeline(TIMELINE_ID, true)
    5734            2 :             .expect("cannot load timeline");
    5735            2 : 
    5736            2 :         Ok(())
    5737            2 :     }
    5738              : 
    5739              :     #[tokio::test]
    5740            2 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    5741            2 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    5742            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    5743            2 :         // create two timelines
    5744            2 :         {
    5745           11 :             let (tenant, ctx) = harness.load().await;
    5746            2 :             let tline = tenant
    5747            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5748            5 :                 .await?;
    5749            2 : 
    5750            7 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5751            2 : 
    5752            2 :             let child_tline = tenant
    5753            2 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    5754            2 :                 .await?;
    5755            2 :             child_tline.set_state(TimelineState::Active);
    5756            2 : 
    5757            2 :             let newtline = tenant
    5758            2 :                 .get_timeline(NEW_TIMELINE_ID, true)
    5759            2 :                 .expect("Should have a local timeline");
    5760            2 : 
    5761            6 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    5762            2 : 
    5763            2 :             // so that all uploads finish & we can call harness.load() below again
    5764            2 :             tenant
    5765            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    5766            2 :                 .instrument(harness.span())
    5767            2 :                 .await
    5768            2 :                 .ok()
    5769            2 :                 .unwrap();
    5770            2 :         }
    5771            2 : 
    5772            2 :         // check that both of them are initially unloaded
    5773            6 :         let (tenant, _ctx) = harness.load().await;
    5774            2 : 
    5775            2 :         // check that both, child and ancestor are loaded
    5776            2 :         let _child_tline = tenant
    5777            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5778            2 :             .expect("cannot get child timeline loaded");
    5779            2 : 
    5780            2 :         let _ancestor_tline = tenant
    5781            2 :             .get_timeline(TIMELINE_ID, true)
    5782            2 :             .expect("cannot get ancestor timeline loaded");
    5783            2 : 
    5784            2 :         Ok(())
    5785            2 :     }
    5786              : 
    5787              :     #[tokio::test]
    5788            2 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    5789            2 :         use storage_layer::AsLayerDesc;
    5790            2 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    5791            2 :             .await?
    5792            2 :             .load()
    5793           20 :             .await;
    5794            2 :         let tline = tenant
    5795            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5796            6 :             .await?;
    5797            6 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5798            2 : 
    5799            2 :         let layer_map = tline.layers.read().await;
    5800            2 :         let level0_deltas = layer_map
    5801            2 :             .layer_map()?
    5802            2 :             .level0_deltas()
    5803            2 :             .iter()
    5804            4 :             .map(|desc| layer_map.get_from_desc(desc))
    5805            2 :             .collect::<Vec<_>>();
    5806            2 : 
    5807            2 :         assert!(!level0_deltas.is_empty());
    5808            2 : 
    5809            6 :         for delta in level0_deltas {
    5810            2 :             // Ensure we are dumping a delta layer here
    5811            4 :             assert!(delta.layer_desc().is_delta);
    5812            8 :             delta.dump(true, &ctx).await.unwrap();
    5813            2 :         }
    5814            2 : 
    5815            2 :         Ok(())
    5816            2 :     }
    5817              : 
    5818              :     #[tokio::test]
    5819            2 :     async fn test_images() -> anyhow::Result<()> {
    5820           20 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    5821            2 :         let tline = tenant
    5822            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5823            6 :             .await?;
    5824            2 : 
    5825            2 :         let mut writer = tline.writer().await;
    5826            2 :         writer
    5827            2 :             .put(
    5828            2 :                 *TEST_KEY,
    5829            2 :                 Lsn(0x10),
    5830            2 :                 &Value::Image(test_img("foo at 0x10")),
    5831            2 :                 &ctx,
    5832            2 :             )
    5833            2 :             .await?;
    5834            2 :         writer.finish_write(Lsn(0x10));
    5835            2 :         drop(writer);
    5836            2 : 
    5837            3 :         tline.freeze_and_flush().await?;
    5838            2 :         tline
    5839            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5840            2 :             .await?;
    5841            2 : 
    5842            2 :         let mut writer = tline.writer().await;
    5843            2 :         writer
    5844            2 :             .put(
    5845            2 :                 *TEST_KEY,
    5846            2 :                 Lsn(0x20),
    5847            2 :                 &Value::Image(test_img("foo at 0x20")),
    5848            2 :                 &ctx,
    5849            2 :             )
    5850            2 :             .await?;
    5851            2 :         writer.finish_write(Lsn(0x20));
    5852            2 :         drop(writer);
    5853            2 : 
    5854            2 :         tline.freeze_and_flush().await?;
    5855            2 :         tline
    5856            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5857            2 :             .await?;
    5858            2 : 
    5859            2 :         let mut writer = tline.writer().await;
    5860            2 :         writer
    5861            2 :             .put(
    5862            2 :                 *TEST_KEY,
    5863            2 :                 Lsn(0x30),
    5864            2 :                 &Value::Image(test_img("foo at 0x30")),
    5865            2 :                 &ctx,
    5866            2 :             )
    5867            2 :             .await?;
    5868            2 :         writer.finish_write(Lsn(0x30));
    5869            2 :         drop(writer);
    5870            2 : 
    5871            2 :         tline.freeze_and_flush().await?;
    5872            2 :         tline
    5873            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5874            2 :             .await?;
    5875            2 : 
    5876            2 :         let mut writer = tline.writer().await;
    5877            2 :         writer
    5878            2 :             .put(
    5879            2 :                 *TEST_KEY,
    5880            2 :                 Lsn(0x40),
    5881            2 :                 &Value::Image(test_img("foo at 0x40")),
    5882            2 :                 &ctx,
    5883            2 :             )
    5884            2 :             .await?;
    5885            2 :         writer.finish_write(Lsn(0x40));
    5886            2 :         drop(writer);
    5887            2 : 
    5888            2 :         tline.freeze_and_flush().await?;
    5889            2 :         tline
    5890            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    5891            2 :             .await?;
    5892            2 : 
    5893            2 :         assert_eq!(
    5894            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5895            2 :             test_img("foo at 0x10")
    5896            2 :         );
    5897            2 :         assert_eq!(
    5898            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5899            2 :             test_img("foo at 0x10")
    5900            2 :         );
    5901            2 :         assert_eq!(
    5902            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5903            2 :             test_img("foo at 0x20")
    5904            2 :         );
    5905            2 :         assert_eq!(
    5906            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    5907            2 :             test_img("foo at 0x30")
    5908            2 :         );
    5909            2 :         assert_eq!(
    5910            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    5911            2 :             test_img("foo at 0x40")
    5912            2 :         );
    5913            2 : 
    5914            2 :         Ok(())
    5915            2 :     }
    5916              : 
    5917            4 :     async fn bulk_insert_compact_gc(
    5918            4 :         tenant: &Tenant,
    5919            4 :         timeline: &Arc<Timeline>,
    5920            4 :         ctx: &RequestContext,
    5921            4 :         lsn: Lsn,
    5922            4 :         repeat: usize,
    5923            4 :         key_count: usize,
    5924            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    5925            4 :         let compact = true;
    5926        40718 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    5927            4 :     }
    5928              : 
    5929            8 :     async fn bulk_insert_maybe_compact_gc(
    5930            8 :         tenant: &Tenant,
    5931            8 :         timeline: &Arc<Timeline>,
    5932            8 :         ctx: &RequestContext,
    5933            8 :         mut lsn: Lsn,
    5934            8 :         repeat: usize,
    5935            8 :         key_count: usize,
    5936            8 :         compact: bool,
    5937            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    5938            8 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    5939            8 : 
    5940            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    5941            8 :         let mut blknum = 0;
    5942            8 : 
    5943            8 :         // Enforce that key range is monotonously increasing
    5944            8 :         let mut keyspace = KeySpaceAccum::new();
    5945            8 : 
    5946            8 :         let cancel = CancellationToken::new();
    5947            8 : 
    5948            8 :         for _ in 0..repeat {
    5949          400 :             for _ in 0..key_count {
    5950      4000000 :                 test_key.field6 = blknum;
    5951      4000000 :                 let mut writer = timeline.writer().await;
    5952      4000000 :                 writer
    5953      4000000 :                     .put(
    5954      4000000 :                         test_key,
    5955      4000000 :                         lsn,
    5956      4000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    5957      4000000 :                         ctx,
    5958      4000000 :                     )
    5959         3426 :                     .await?;
    5960      4000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    5961      4000000 :                 writer.finish_write(lsn);
    5962      4000000 :                 drop(writer);
    5963      4000000 : 
    5964      4000000 :                 keyspace.add_key(test_key);
    5965      4000000 : 
    5966      4000000 :                 lsn = Lsn(lsn.0 + 0x10);
    5967      4000000 :                 blknum += 1;
    5968              :             }
    5969              : 
    5970          400 :             timeline.freeze_and_flush().await?;
    5971          400 :             if compact {
    5972              :                 // this requires timeline to be &Arc<Timeline>
    5973         8618 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    5974          200 :             }
    5975              : 
    5976              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    5977              :             // originally was.
    5978          400 :             let res = tenant
    5979          400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    5980            0 :                 .await?;
    5981              : 
    5982          400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    5983              :         }
    5984              : 
    5985            8 :         Ok(inserted)
    5986            8 :     }
    5987              : 
    5988              :     //
    5989              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    5990              :     // Repeat 50 times.
    5991              :     //
    5992              :     #[tokio::test]
    5993            2 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    5994            2 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    5995           20 :         let (tenant, ctx) = harness.load().await;
    5996            2 :         let tline = tenant
    5997            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5998            6 :             .await?;
    5999            2 : 
    6000            2 :         let lsn = Lsn(0x10);
    6001        20359 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6002            2 : 
    6003            2 :         Ok(())
    6004            2 :     }
    6005              : 
    6006              :     // Test the vectored get real implementation against a simple sequential implementation.
    6007              :     //
    6008              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6009              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6010              :     // grow to the right on the X axis.
    6011              :     //                       [Delta]
    6012              :     //                 [Delta]
    6013              :     //           [Delta]
    6014              :     //    [Delta]
    6015              :     // ------------ Image ---------------
    6016              :     //
    6017              :     // After layer generation we pick the ranges to query as follows:
    6018              :     // 1. The beginning of each delta layer
    6019              :     // 2. At the seam between two adjacent delta layers
    6020              :     //
    6021              :     // There's one major downside to this test: delta layers only contains images,
    6022              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6023              :     #[tokio::test]
    6024            2 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6025            2 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6026           14 :         let (tenant, ctx) = harness.load().await;
    6027            2 :         let tline = tenant
    6028            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6029            5 :             .await?;
    6030            2 : 
    6031            2 :         let lsn = Lsn(0x10);
    6032        20359 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6033            2 : 
    6034            2 :         let guard = tline.layers.read().await;
    6035            2 :         let lm = guard.layer_map()?;
    6036            2 : 
    6037            2 :         lm.dump(true, &ctx).await?;
    6038            2 : 
    6039            2 :         let mut reads = Vec::new();
    6040            2 :         let mut prev = None;
    6041           12 :         lm.iter_historic_layers().for_each(|desc| {
    6042           12 :             if !desc.is_delta() {
    6043            2 :                 prev = Some(desc.clone());
    6044            2 :                 return;
    6045           10 :             }
    6046           10 : 
    6047           10 :             let start = desc.key_range.start;
    6048           10 :             let end = desc
    6049           10 :                 .key_range
    6050           10 :                 .start
    6051           10 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6052           10 :             reads.push(KeySpace {
    6053           10 :                 ranges: vec![start..end],
    6054           10 :             });
    6055            2 : 
    6056           10 :             if let Some(prev) = &prev {
    6057           10 :                 if !prev.is_delta() {
    6058           10 :                     return;
    6059            2 :                 }
    6060            0 : 
    6061            0 :                 let first_range = Key {
    6062            0 :                     field6: prev.key_range.end.field6 - 4,
    6063            0 :                     ..prev.key_range.end
    6064            0 :                 }..prev.key_range.end;
    6065            0 : 
    6066            0 :                 let second_range = desc.key_range.start..Key {
    6067            0 :                     field6: desc.key_range.start.field6 + 4,
    6068            0 :                     ..desc.key_range.start
    6069            0 :                 };
    6070            0 : 
    6071            0 :                 reads.push(KeySpace {
    6072            0 :                     ranges: vec![first_range, second_range],
    6073            0 :                 });
    6074            2 :             };
    6075            2 : 
    6076            2 :             prev = Some(desc.clone());
    6077           12 :         });
    6078            2 : 
    6079            2 :         drop(guard);
    6080            2 : 
    6081            2 :         // Pick a big LSN such that we query over all the changes.
    6082            2 :         let reads_lsn = Lsn(u64::MAX - 1);
    6083            2 : 
    6084           12 :         for read in reads {
    6085           10 :             info!("Doing vectored read on {:?}", read);
    6086            2 : 
    6087           10 :             let vectored_res = tline
    6088           10 :                 .get_vectored_impl(
    6089           10 :                     read.clone(),
    6090           10 :                     reads_lsn,
    6091           10 :                     &mut ValuesReconstructState::new(),
    6092           10 :                     &ctx,
    6093           10 :                 )
    6094           25 :                 .await;
    6095            2 : 
    6096           10 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6097           10 :             let mut expect_missing = false;
    6098           10 :             let mut key = read.start().unwrap();
    6099          330 :             while key != read.end().unwrap() {
    6100          320 :                 if let Some(lsns) = inserted.get(&key) {
    6101          320 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6102          320 :                     match expected_lsn {
    6103          320 :                         Some(lsn) => {
    6104          320 :                             expected_lsns.insert(key, *lsn);
    6105          320 :                         }
    6106            2 :                         None => {
    6107            2 :                             expect_missing = true;
    6108            0 :                             break;
    6109            2 :                         }
    6110            2 :                     }
    6111            2 :                 } else {
    6112            2 :                     expect_missing = true;
    6113            0 :                     break;
    6114            2 :                 }
    6115            2 : 
    6116          320 :                 key = key.next();
    6117            2 :             }
    6118            2 : 
    6119           10 :             if expect_missing {
    6120            2 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6121            2 :             } else {
    6122          320 :                 for (key, image) in vectored_res? {
    6123          320 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6124          320 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6125          320 :                     assert_eq!(image?, expected_image);
    6126            2 :                 }
    6127            2 :             }
    6128            2 :         }
    6129            2 : 
    6130            2 :         Ok(())
    6131            2 :     }
    6132              : 
    6133              :     #[tokio::test]
    6134            2 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6135            2 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6136            2 : 
    6137           20 :         let (tenant, ctx) = harness.load().await;
    6138            2 :         let tline = tenant
    6139            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6140            2 :             .await?;
    6141            2 :         let tline = tline.raw_timeline().unwrap();
    6142            2 : 
    6143            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6144            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6145            2 :         modification.set_lsn(Lsn(0x1008))?;
    6146            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6147            2 :         modification.commit(&ctx).await?;
    6148            2 : 
    6149            2 :         let child_timeline_id = TimelineId::generate();
    6150            2 :         tenant
    6151            2 :             .branch_timeline_test(
    6152            2 :                 tline,
    6153            2 :                 child_timeline_id,
    6154            2 :                 Some(tline.get_last_record_lsn()),
    6155            2 :                 &ctx,
    6156            2 :             )
    6157            2 :             .await?;
    6158            2 : 
    6159            2 :         let child_timeline = tenant
    6160            2 :             .get_timeline(child_timeline_id, true)
    6161            2 :             .expect("Should have the branched timeline");
    6162            2 : 
    6163            2 :         let aux_keyspace = KeySpace {
    6164            2 :             ranges: vec![NON_INHERITED_RANGE],
    6165            2 :         };
    6166            2 :         let read_lsn = child_timeline.get_last_record_lsn();
    6167            2 : 
    6168            2 :         let vectored_res = child_timeline
    6169            2 :             .get_vectored_impl(
    6170            2 :                 aux_keyspace.clone(),
    6171            2 :                 read_lsn,
    6172            2 :                 &mut ValuesReconstructState::new(),
    6173            2 :                 &ctx,
    6174            2 :             )
    6175            2 :             .await;
    6176            2 : 
    6177            2 :         let images = vectored_res?;
    6178            2 :         assert!(images.is_empty());
    6179            2 :         Ok(())
    6180            2 :     }
    6181              : 
    6182              :     // Test that vectored get handles layer gaps correctly
    6183              :     // by advancing into the next ancestor timeline if required.
    6184              :     //
    6185              :     // The test generates timelines that look like the diagram below.
    6186              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6187              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6188              :     //
    6189              :     // ```
    6190              :     //-------------------------------+
    6191              :     //                          ...  |
    6192              :     //               [   L1   ]      |
    6193              :     //     [ / L1   ]                | Child Timeline
    6194              :     // ...                           |
    6195              :     // ------------------------------+
    6196              :     //     [ X L1   ]                | Parent Timeline
    6197              :     // ------------------------------+
    6198              :     // ```
    6199              :     #[tokio::test]
    6200            2 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6201            2 :         let tenant_conf = TenantConf {
    6202            2 :             // Make compaction deterministic
    6203            2 :             gc_period: Duration::ZERO,
    6204            2 :             compaction_period: Duration::ZERO,
    6205            2 :             // Encourage creation of L1 layers
    6206            2 :             checkpoint_distance: 16 * 1024,
    6207            2 :             compaction_target_size: 8 * 1024,
    6208            2 :             ..TenantConf::default()
    6209            2 :         };
    6210            2 : 
    6211            2 :         let harness = TenantHarness::create_custom(
    6212            2 :             "test_get_vectored_key_gap",
    6213            2 :             tenant_conf,
    6214            2 :             TenantId::generate(),
    6215            2 :             ShardIdentity::unsharded(),
    6216            2 :             Generation::new(0xdeadbeef),
    6217            2 :         )
    6218            2 :         .await?;
    6219           20 :         let (tenant, ctx) = harness.load().await;
    6220            2 : 
    6221            2 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6222            2 :         let gap_at_key = current_key.add(100);
    6223            2 :         let mut current_lsn = Lsn(0x10);
    6224            2 : 
    6225            2 :         const KEY_COUNT: usize = 10_000;
    6226            2 : 
    6227            2 :         let timeline_id = TimelineId::generate();
    6228            2 :         let current_timeline = tenant
    6229            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6230            5 :             .await?;
    6231            2 : 
    6232            2 :         current_lsn += 0x100;
    6233            2 : 
    6234            2 :         let mut writer = current_timeline.writer().await;
    6235            2 :         writer
    6236            2 :             .put(
    6237            2 :                 gap_at_key,
    6238            2 :                 current_lsn,
    6239            2 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6240            2 :                 &ctx,
    6241            2 :             )
    6242            2 :             .await?;
    6243            2 :         writer.finish_write(current_lsn);
    6244            2 :         drop(writer);
    6245            2 : 
    6246            2 :         let mut latest_lsns = HashMap::new();
    6247            2 :         latest_lsns.insert(gap_at_key, current_lsn);
    6248            2 : 
    6249            2 :         current_timeline.freeze_and_flush().await?;
    6250            2 : 
    6251            2 :         let child_timeline_id = TimelineId::generate();
    6252            2 : 
    6253            2 :         tenant
    6254            2 :             .branch_timeline_test(
    6255            2 :                 &current_timeline,
    6256            2 :                 child_timeline_id,
    6257            2 :                 Some(current_lsn),
    6258            2 :                 &ctx,
    6259            2 :             )
    6260            2 :             .await?;
    6261            2 :         let child_timeline = tenant
    6262            2 :             .get_timeline(child_timeline_id, true)
    6263            2 :             .expect("Should have the branched timeline");
    6264            2 : 
    6265        20002 :         for i in 0..KEY_COUNT {
    6266        20000 :             if current_key == gap_at_key {
    6267            2 :                 current_key = current_key.next();
    6268            2 :                 continue;
    6269        19998 :             }
    6270        19998 : 
    6271        19998 :             current_lsn += 0x10;
    6272            2 : 
    6273        19998 :             let mut writer = child_timeline.writer().await;
    6274        19998 :             writer
    6275        19998 :                 .put(
    6276        19998 :                     current_key,
    6277        19998 :                     current_lsn,
    6278        19998 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6279        19998 :                     &ctx,
    6280        19998 :                 )
    6281           67 :                 .await?;
    6282        19998 :             writer.finish_write(current_lsn);
    6283        19998 :             drop(writer);
    6284        19998 : 
    6285        19998 :             latest_lsns.insert(current_key, current_lsn);
    6286        19998 :             current_key = current_key.next();
    6287        19998 : 
    6288        19998 :             // Flush every now and then to encourage layer file creation.
    6289        19998 :             if i % 500 == 0 {
    6290           42 :                 child_timeline.freeze_and_flush().await?;
    6291        19958 :             }
    6292            2 :         }
    6293            2 : 
    6294            2 :         child_timeline.freeze_and_flush().await?;
    6295            2 :         let mut flags = EnumSet::new();
    6296            2 :         flags.insert(CompactFlags::ForceRepartition);
    6297            2 :         child_timeline
    6298            2 :             .compact(&CancellationToken::new(), flags, &ctx)
    6299         1757 :             .await?;
    6300            2 : 
    6301            2 :         let key_near_end = {
    6302            2 :             let mut tmp = current_key;
    6303            2 :             tmp.field6 -= 10;
    6304            2 :             tmp
    6305            2 :         };
    6306            2 : 
    6307            2 :         let key_near_gap = {
    6308            2 :             let mut tmp = gap_at_key;
    6309            2 :             tmp.field6 -= 10;
    6310            2 :             tmp
    6311            2 :         };
    6312            2 : 
    6313            2 :         let read = KeySpace {
    6314            2 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6315            2 :         };
    6316            2 :         let results = child_timeline
    6317            2 :             .get_vectored_impl(
    6318            2 :                 read.clone(),
    6319            2 :                 current_lsn,
    6320            2 :                 &mut ValuesReconstructState::new(),
    6321            2 :                 &ctx,
    6322            2 :             )
    6323           16 :             .await?;
    6324            2 : 
    6325           44 :         for (key, img_res) in results {
    6326           42 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6327           42 :             assert_eq!(img_res?, expected);
    6328            2 :         }
    6329            2 : 
    6330            2 :         Ok(())
    6331            2 :     }
    6332              : 
    6333              :     // Test that vectored get descends into ancestor timelines correctly and
    6334              :     // does not return an image that's newer than requested.
    6335              :     //
    6336              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6337              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6338              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6339              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6340              :     // order to avoid returning an image that's too new. The test below constructs such
    6341              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6342              :     // ```
    6343              :     //    LSN
    6344              :     //     ^
    6345              :     //     |
    6346              :     //     |
    6347              :     // 500 | --------------------------------------> branch point
    6348              :     // 400 |        X
    6349              :     // 300 |        X
    6350              :     // 200 | --------------------------------------> requested lsn
    6351              :     // 100 |        X
    6352              :     //     |---------------------------------------> Key
    6353              :     //              |
    6354              :     //              ------> requested key
    6355              :     //
    6356              :     // Legend:
    6357              :     // * X - page images
    6358              :     // ```
    6359              :     #[tokio::test]
    6360            2 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6361            2 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6362           20 :         let (tenant, ctx) = harness.load().await;
    6363            2 : 
    6364            2 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6365            2 :         let end_key = start_key.add(1000);
    6366            2 :         let child_gap_at_key = start_key.add(500);
    6367            2 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6368            2 : 
    6369            2 :         let mut current_lsn = Lsn(0x10);
    6370            2 : 
    6371            2 :         let timeline_id = TimelineId::generate();
    6372            2 :         let parent_timeline = tenant
    6373            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6374            6 :             .await?;
    6375            2 : 
    6376            2 :         current_lsn += 0x100;
    6377            2 : 
    6378            8 :         for _ in 0..3 {
    6379            6 :             let mut key = start_key;
    6380         6006 :             while key < end_key {
    6381         6000 :                 current_lsn += 0x10;
    6382         6000 : 
    6383         6000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6384            2 : 
    6385         6000 :                 let mut writer = parent_timeline.writer().await;
    6386         6000 :                 writer
    6387         6000 :                     .put(
    6388         6000 :                         key,
    6389         6000 :                         current_lsn,
    6390         6000 :                         &Value::Image(test_img(&image_value)),
    6391         6000 :                         &ctx,
    6392         6000 :                     )
    6393            6 :                     .await?;
    6394         6000 :                 writer.finish_write(current_lsn);
    6395         6000 : 
    6396         6000 :                 if key == child_gap_at_key {
    6397            6 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6398         5994 :                 }
    6399            2 : 
    6400         6000 :                 key = key.next();
    6401            2 :             }
    6402            2 : 
    6403            6 :             parent_timeline.freeze_and_flush().await?;
    6404            2 :         }
    6405            2 : 
    6406            2 :         let child_timeline_id = TimelineId::generate();
    6407            2 : 
    6408            2 :         let child_timeline = tenant
    6409            2 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6410            2 :             .await?;
    6411            2 : 
    6412            2 :         let mut key = start_key;
    6413         2002 :         while key < end_key {
    6414         2000 :             if key == child_gap_at_key {
    6415            2 :                 key = key.next();
    6416            2 :                 continue;
    6417         1998 :             }
    6418         1998 : 
    6419         1998 :             current_lsn += 0x10;
    6420            2 : 
    6421         1998 :             let mut writer = child_timeline.writer().await;
    6422         1998 :             writer
    6423         1998 :                 .put(
    6424         1998 :                     key,
    6425         1998 :                     current_lsn,
    6426         1998 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6427         1998 :                     &ctx,
    6428         1998 :                 )
    6429           17 :                 .await?;
    6430         1998 :             writer.finish_write(current_lsn);
    6431         1998 : 
    6432         1998 :             key = key.next();
    6433            2 :         }
    6434            2 : 
    6435            2 :         child_timeline.freeze_and_flush().await?;
    6436            2 : 
    6437            2 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6438            2 :         let mut query_lsns = Vec::new();
    6439            6 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6440           36 :             for offset in lsn_offsets {
    6441           30 :                 query_lsns.push(Lsn(image_lsn
    6442           30 :                     .0
    6443           30 :                     .checked_add_signed(offset)
    6444           30 :                     .expect("Shouldn't overflow")));
    6445           30 :             }
    6446            2 :         }
    6447            2 : 
    6448           32 :         for query_lsn in query_lsns {
    6449           30 :             let results = child_timeline
    6450           30 :                 .get_vectored_impl(
    6451           30 :                     KeySpace {
    6452           30 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6453           30 :                     },
    6454           30 :                     query_lsn,
    6455           30 :                     &mut ValuesReconstructState::new(),
    6456           30 :                     &ctx,
    6457           30 :                 )
    6458           29 :                 .await;
    6459            2 : 
    6460           30 :             let expected_item = parent_gap_lsns
    6461           30 :                 .iter()
    6462           30 :                 .rev()
    6463           68 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6464           30 : 
    6465           30 :             info!(
    6466            2 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6467            2 :                 query_lsn, expected_item
    6468            2 :             );
    6469            2 : 
    6470           30 :             match expected_item {
    6471           26 :                 Some((_, img_value)) => {
    6472           26 :                     let key_results = results.expect("No vectored get error expected");
    6473           26 :                     let key_result = &key_results[&child_gap_at_key];
    6474           26 :                     let returned_img = key_result
    6475           26 :                         .as_ref()
    6476           26 :                         .expect("No page reconstruct error expected");
    6477           26 : 
    6478           26 :                     info!(
    6479            2 :                         "Vectored read at LSN {} returned image {}",
    6480            0 :                         query_lsn,
    6481            0 :                         std::str::from_utf8(returned_img)?
    6482            2 :                     );
    6483           26 :                     assert_eq!(*returned_img, test_img(img_value));
    6484            2 :                 }
    6485            2 :                 None => {
    6486            4 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6487            2 :                 }
    6488            2 :             }
    6489            2 :         }
    6490            2 : 
    6491            2 :         Ok(())
    6492            2 :     }
    6493              : 
    6494              :     #[tokio::test]
    6495            2 :     async fn test_random_updates() -> anyhow::Result<()> {
    6496            2 :         let names_algorithms = [
    6497            2 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    6498            2 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    6499            2 :         ];
    6500            6 :         for (name, algorithm) in names_algorithms {
    6501        96217 :             test_random_updates_algorithm(name, algorithm).await?;
    6502            2 :         }
    6503            2 :         Ok(())
    6504            2 :     }
    6505              : 
    6506            4 :     async fn test_random_updates_algorithm(
    6507            4 :         name: &'static str,
    6508            4 :         compaction_algorithm: CompactionAlgorithm,
    6509            4 :     ) -> anyhow::Result<()> {
    6510            4 :         let mut harness = TenantHarness::create(name).await?;
    6511            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6512            4 :             kind: compaction_algorithm,
    6513            4 :         };
    6514           40 :         let (tenant, ctx) = harness.load().await;
    6515            4 :         let tline = tenant
    6516            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6517            9 :             .await?;
    6518              : 
    6519              :         const NUM_KEYS: usize = 1000;
    6520            4 :         let cancel = CancellationToken::new();
    6521            4 : 
    6522            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6523            4 :         let mut test_key_end = test_key;
    6524            4 :         test_key_end.field6 = NUM_KEYS as u32;
    6525            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    6526            4 : 
    6527            4 :         let mut keyspace = KeySpaceAccum::new();
    6528            4 : 
    6529            4 :         // Track when each page was last modified. Used to assert that
    6530            4 :         // a read sees the latest page version.
    6531            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    6532            4 : 
    6533            4 :         let mut lsn = Lsn(0x10);
    6534              :         #[allow(clippy::needless_range_loop)]
    6535         4004 :         for blknum in 0..NUM_KEYS {
    6536         4000 :             lsn = Lsn(lsn.0 + 0x10);
    6537         4000 :             test_key.field6 = blknum as u32;
    6538         4000 :             let mut writer = tline.writer().await;
    6539         4000 :             writer
    6540         4000 :                 .put(
    6541         4000 :                     test_key,
    6542         4000 :                     lsn,
    6543         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6544         4000 :                     &ctx,
    6545         4000 :                 )
    6546            4 :                 .await?;
    6547         4000 :             writer.finish_write(lsn);
    6548         4000 :             updated[blknum] = lsn;
    6549         4000 :             drop(writer);
    6550         4000 : 
    6551         4000 :             keyspace.add_key(test_key);
    6552              :         }
    6553              : 
    6554          204 :         for _ in 0..50 {
    6555       200200 :             for _ in 0..NUM_KEYS {
    6556       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    6557       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6558       200000 :                 test_key.field6 = blknum as u32;
    6559       200000 :                 let mut writer = tline.writer().await;
    6560       200000 :                 writer
    6561       200000 :                     .put(
    6562       200000 :                         test_key,
    6563       200000 :                         lsn,
    6564       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6565       200000 :                         &ctx,
    6566       200000 :                     )
    6567          198 :                     .await?;
    6568       200000 :                 writer.finish_write(lsn);
    6569       200000 :                 drop(writer);
    6570       200000 :                 updated[blknum] = lsn;
    6571              :             }
    6572              : 
    6573              :             // Read all the blocks
    6574       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6575       200000 :                 test_key.field6 = blknum as u32;
    6576       200000 :                 assert_eq!(
    6577       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    6578       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6579              :                 );
    6580              :             }
    6581              : 
    6582              :             // Perform a cycle of flush, and GC
    6583          201 :             tline.freeze_and_flush().await?;
    6584          200 :             tenant
    6585          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    6586            0 :                 .await?;
    6587              :         }
    6588              : 
    6589            4 :         Ok(())
    6590            4 :     }
    6591              : 
    6592              :     #[tokio::test]
    6593            2 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    6594            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    6595            2 :             .await?
    6596            2 :             .load()
    6597           20 :             .await;
    6598            2 :         let mut tline = tenant
    6599            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6600            6 :             .await?;
    6601            2 : 
    6602            2 :         const NUM_KEYS: usize = 1000;
    6603            2 : 
    6604            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6605            2 : 
    6606            2 :         let mut keyspace = KeySpaceAccum::new();
    6607            2 : 
    6608            2 :         let cancel = CancellationToken::new();
    6609            2 : 
    6610            2 :         // Track when each page was last modified. Used to assert that
    6611            2 :         // a read sees the latest page version.
    6612            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    6613            2 : 
    6614            2 :         let mut lsn = Lsn(0x10);
    6615            2 :         #[allow(clippy::needless_range_loop)]
    6616         2002 :         for blknum in 0..NUM_KEYS {
    6617         2000 :             lsn = Lsn(lsn.0 + 0x10);
    6618         2000 :             test_key.field6 = blknum as u32;
    6619         2000 :             let mut writer = tline.writer().await;
    6620         2000 :             writer
    6621         2000 :                 .put(
    6622         2000 :                     test_key,
    6623         2000 :                     lsn,
    6624         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6625         2000 :                     &ctx,
    6626         2000 :                 )
    6627            2 :                 .await?;
    6628         2000 :             writer.finish_write(lsn);
    6629         2000 :             updated[blknum] = lsn;
    6630         2000 :             drop(writer);
    6631         2000 : 
    6632         2000 :             keyspace.add_key(test_key);
    6633            2 :         }
    6634            2 : 
    6635          102 :         for _ in 0..50 {
    6636          100 :             let new_tline_id = TimelineId::generate();
    6637          100 :             tenant
    6638          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    6639           91 :                 .await?;
    6640          100 :             tline = tenant
    6641          100 :                 .get_timeline(new_tline_id, true)
    6642          100 :                 .expect("Should have the branched timeline");
    6643            2 : 
    6644       100100 :             for _ in 0..NUM_KEYS {
    6645       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    6646       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6647       100000 :                 test_key.field6 = blknum as u32;
    6648       100000 :                 let mut writer = tline.writer().await;
    6649       100000 :                 writer
    6650       100000 :                     .put(
    6651       100000 :                         test_key,
    6652       100000 :                         lsn,
    6653       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6654       100000 :                         &ctx,
    6655       100000 :                     )
    6656          792 :                     .await?;
    6657       100000 :                 println!("updating {} at {}", blknum, lsn);
    6658       100000 :                 writer.finish_write(lsn);
    6659       100000 :                 drop(writer);
    6660       100000 :                 updated[blknum] = lsn;
    6661            2 :             }
    6662            2 : 
    6663            2 :             // Read all the blocks
    6664       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6665       100000 :                 test_key.field6 = blknum as u32;
    6666       100000 :                 assert_eq!(
    6667       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    6668       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6669            2 :                 );
    6670            2 :             }
    6671            2 : 
    6672            2 :             // Perform a cycle of flush, compact, and GC
    6673          102 :             tline.freeze_and_flush().await?;
    6674        15044 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    6675          100 :             tenant
    6676          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    6677            2 :                 .await?;
    6678            2 :         }
    6679            2 : 
    6680            2 :         Ok(())
    6681            2 :     }
    6682              : 
    6683              :     #[tokio::test]
    6684            2 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    6685            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    6686            2 :             .await?
    6687            2 :             .load()
    6688           20 :             .await;
    6689            2 :         let mut tline = tenant
    6690            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6691            6 :             .await?;
    6692            2 : 
    6693            2 :         const NUM_KEYS: usize = 100;
    6694            2 :         const NUM_TLINES: usize = 50;
    6695            2 : 
    6696            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6697            2 :         // Track page mutation lsns across different timelines.
    6698            2 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    6699            2 : 
    6700            2 :         let mut lsn = Lsn(0x10);
    6701            2 : 
    6702            2 :         #[allow(clippy::needless_range_loop)]
    6703          102 :         for idx in 0..NUM_TLINES {
    6704          100 :             let new_tline_id = TimelineId::generate();
    6705          100 :             tenant
    6706          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    6707           64 :                 .await?;
    6708          100 :             tline = tenant
    6709          100 :                 .get_timeline(new_tline_id, true)
    6710          100 :                 .expect("Should have the branched timeline");
    6711            2 : 
    6712        10100 :             for _ in 0..NUM_KEYS {
    6713        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    6714        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6715        10000 :                 test_key.field6 = blknum as u32;
    6716        10000 :                 let mut writer = tline.writer().await;
    6717        10000 :                 writer
    6718        10000 :                     .put(
    6719        10000 :                         test_key,
    6720        10000 :                         lsn,
    6721        10000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    6722        10000 :                         &ctx,
    6723        10000 :                     )
    6724          108 :                     .await?;
    6725        10000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    6726        10000 :                 writer.finish_write(lsn);
    6727        10000 :                 drop(writer);
    6728        10000 :                 updated[idx][blknum] = lsn;
    6729            2 :             }
    6730            2 :         }
    6731            2 : 
    6732            2 :         // Read pages from leaf timeline across all ancestors.
    6733          100 :         for (idx, lsns) in updated.iter().enumerate() {
    6734        10000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    6735            2 :                 // Skip empty mutations.
    6736        10000 :                 if lsn.0 == 0 {
    6737         3694 :                     continue;
    6738         6306 :                 }
    6739         6306 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    6740         6306 :                 test_key.field6 = blknum as u32;
    6741         6306 :                 assert_eq!(
    6742         6306 :                     tline.get(test_key, *lsn, &ctx).await?,
    6743         6306 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    6744            2 :                 );
    6745            2 :             }
    6746            2 :         }
    6747            2 :         Ok(())
    6748            2 :     }
    6749              : 
    6750              :     #[tokio::test]
    6751            2 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    6752            2 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    6753            2 :             .await?
    6754            2 :             .load()
    6755           20 :             .await;
    6756            2 : 
    6757            2 :         let initdb_lsn = Lsn(0x20);
    6758            2 :         let utline = tenant
    6759            2 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    6760            2 :             .await?;
    6761            2 :         let tline = utline.raw_timeline().unwrap();
    6762            2 : 
    6763            2 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    6764            2 :         tline.maybe_spawn_flush_loop();
    6765            2 : 
    6766            2 :         // Make sure the timeline has the minimum set of required keys for operation.
    6767            2 :         // The only operation you can always do on an empty timeline is to `put` new data.
    6768            2 :         // Except if you `put` at `initdb_lsn`.
    6769            2 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    6770            2 :         // It uses `repartition()`, which assumes some keys to be present.
    6771            2 :         // Let's make sure the test timeline can handle that case.
    6772            2 :         {
    6773            2 :             let mut state = tline.flush_loop_state.lock().unwrap();
    6774            2 :             assert_eq!(
    6775            2 :                 timeline::FlushLoopState::Running {
    6776            2 :                     expect_initdb_optimization: false,
    6777            2 :                     initdb_optimization_count: 0,
    6778            2 :                 },
    6779            2 :                 *state
    6780            2 :             );
    6781            2 :             *state = timeline::FlushLoopState::Running {
    6782            2 :                 expect_initdb_optimization: true,
    6783            2 :                 initdb_optimization_count: 0,
    6784            2 :             };
    6785            2 :         }
    6786            2 : 
    6787            2 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    6788            2 :         // As explained above, the optimization requires some keys to be present.
    6789            2 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    6790            2 :         // This is what `create_test_timeline` does, by the way.
    6791            2 :         let mut modification = tline.begin_modification(initdb_lsn);
    6792            2 :         modification
    6793            2 :             .init_empty_test_timeline()
    6794            2 :             .context("init_empty_test_timeline")?;
    6795            2 :         modification
    6796            2 :             .commit(&ctx)
    6797            2 :             .await
    6798            2 :             .context("commit init_empty_test_timeline modification")?;
    6799            2 : 
    6800            2 :         // Do the flush. The flush code will check the expectations that we set above.
    6801            2 :         tline.freeze_and_flush().await?;
    6802            2 : 
    6803            2 :         // assert freeze_and_flush exercised the initdb optimization
    6804            2 :         {
    6805            2 :             let state = tline.flush_loop_state.lock().unwrap();
    6806            2 :             let timeline::FlushLoopState::Running {
    6807            2 :                 expect_initdb_optimization,
    6808            2 :                 initdb_optimization_count,
    6809            2 :             } = *state
    6810            2 :             else {
    6811            2 :                 panic!("unexpected state: {:?}", *state);
    6812            2 :             };
    6813            2 :             assert!(expect_initdb_optimization);
    6814            2 :             assert!(initdb_optimization_count > 0);
    6815            2 :         }
    6816            2 :         Ok(())
    6817            2 :     }
    6818              : 
    6819              :     #[tokio::test]
    6820            2 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    6821            2 :         let name = "test_create_guard_crash";
    6822            2 :         let harness = TenantHarness::create(name).await?;
    6823            2 :         {
    6824           20 :             let (tenant, ctx) = harness.load().await;
    6825            2 :             let tline = tenant
    6826            2 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6827            2 :                 .await?;
    6828            2 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    6829            2 :             let raw_tline = tline.raw_timeline().unwrap();
    6830            2 :             raw_tline
    6831            2 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    6832            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))
    6833            2 :                 .await;
    6834            2 :             std::mem::forget(tline);
    6835            2 :         }
    6836            2 : 
    6837           20 :         let (tenant, _) = harness.load().await;
    6838            2 :         match tenant.get_timeline(TIMELINE_ID, false) {
    6839            2 :             Ok(_) => panic!("timeline should've been removed during load"),
    6840            2 :             Err(e) => {
    6841            2 :                 assert_eq!(
    6842            2 :                     e,
    6843            2 :                     GetTimelineError::NotFound {
    6844            2 :                         tenant_id: tenant.tenant_shard_id,
    6845            2 :                         timeline_id: TIMELINE_ID,
    6846            2 :                     }
    6847            2 :                 )
    6848            2 :             }
    6849            2 :         }
    6850            2 : 
    6851            2 :         assert!(!harness
    6852            2 :             .conf
    6853            2 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    6854            2 :             .exists());
    6855            2 : 
    6856            2 :         Ok(())
    6857            2 :     }
    6858              : 
    6859              :     #[tokio::test]
    6860            2 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    6861            2 :         let names_algorithms = [
    6862            2 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    6863            2 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    6864            2 :         ];
    6865            6 :         for (name, algorithm) in names_algorithms {
    6866        32561 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    6867            2 :         }
    6868            2 :         Ok(())
    6869            2 :     }
    6870              : 
    6871            4 :     async fn test_read_at_max_lsn_algorithm(
    6872            4 :         name: &'static str,
    6873            4 :         compaction_algorithm: CompactionAlgorithm,
    6874            4 :     ) -> anyhow::Result<()> {
    6875            4 :         let mut harness = TenantHarness::create(name).await?;
    6876            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6877            4 :             kind: compaction_algorithm,
    6878            4 :         };
    6879           40 :         let (tenant, ctx) = harness.load().await;
    6880            4 :         let tline = tenant
    6881            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6882           11 :             .await?;
    6883              : 
    6884            4 :         let lsn = Lsn(0x10);
    6885            4 :         let compact = false;
    6886        32100 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    6887              : 
    6888            4 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6889            4 :         let read_lsn = Lsn(u64::MAX - 1);
    6890              : 
    6891          410 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    6892            4 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    6893              : 
    6894            4 :         Ok(())
    6895            4 :     }
    6896              : 
    6897              :     #[tokio::test]
    6898            2 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    6899            2 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    6900           20 :         let (tenant, ctx) = harness.load().await;
    6901            2 :         let tline = tenant
    6902            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6903            6 :             .await?;
    6904            2 : 
    6905            2 :         const NUM_KEYS: usize = 1000;
    6906            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    6907            2 : 
    6908            2 :         let cancel = CancellationToken::new();
    6909            2 : 
    6910            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    6911            2 :         base_key.field1 = AUX_KEY_PREFIX;
    6912            2 :         let mut test_key = base_key;
    6913            2 : 
    6914            2 :         // Track when each page was last modified. Used to assert that
    6915            2 :         // a read sees the latest page version.
    6916            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    6917            2 : 
    6918            2 :         let mut lsn = Lsn(0x10);
    6919            2 :         #[allow(clippy::needless_range_loop)]
    6920         2002 :         for blknum in 0..NUM_KEYS {
    6921         2000 :             lsn = Lsn(lsn.0 + 0x10);
    6922         2000 :             test_key.field6 = (blknum * STEP) as u32;
    6923         2000 :             let mut writer = tline.writer().await;
    6924         2000 :             writer
    6925         2000 :                 .put(
    6926         2000 :                     test_key,
    6927         2000 :                     lsn,
    6928         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6929         2000 :                     &ctx,
    6930         2000 :                 )
    6931            2 :                 .await?;
    6932         2000 :             writer.finish_write(lsn);
    6933         2000 :             updated[blknum] = lsn;
    6934         2000 :             drop(writer);
    6935            2 :         }
    6936            2 : 
    6937            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    6938            2 : 
    6939           24 :         for iter in 0..=10 {
    6940            2 :             // Read all the blocks
    6941        22000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    6942        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    6943        22000 :                 assert_eq!(
    6944        22000 :                     tline.get(test_key, lsn, &ctx).await?,
    6945        22000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    6946            2 :                 );
    6947            2 :             }
    6948            2 : 
    6949           22 :             let mut cnt = 0;
    6950        22000 :             for (key, value) in tline
    6951           22 :                 .get_vectored_impl(
    6952           22 :                     keyspace.clone(),
    6953           22 :                     lsn,
    6954           22 :                     &mut ValuesReconstructState::default(),
    6955           22 :                     &ctx,
    6956           22 :                 )
    6957          736 :                 .await?
    6958            2 :             {
    6959        22000 :                 let blknum = key.field6 as usize;
    6960        22000 :                 let value = value?;
    6961        22000 :                 assert!(blknum % STEP == 0);
    6962        22000 :                 let blknum = blknum / STEP;
    6963        22000 :                 assert_eq!(
    6964        22000 :                     value,
    6965        22000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    6966        22000 :                 );
    6967        22000 :                 cnt += 1;
    6968            2 :             }
    6969            2 : 
    6970           22 :             assert_eq!(cnt, NUM_KEYS);
    6971            2 : 
    6972        22022 :             for _ in 0..NUM_KEYS {
    6973        22000 :                 lsn = Lsn(lsn.0 + 0x10);
    6974        22000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    6975        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    6976        22000 :                 let mut writer = tline.writer().await;
    6977        22000 :                 writer
    6978        22000 :                     .put(
    6979        22000 :                         test_key,
    6980        22000 :                         lsn,
    6981        22000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6982        22000 :                         &ctx,
    6983        22000 :                     )
    6984          111 :                     .await?;
    6985        22000 :                 writer.finish_write(lsn);
    6986        22000 :                 drop(writer);
    6987        22000 :                 updated[blknum] = lsn;
    6988            2 :             }
    6989            2 : 
    6990            2 :             // Perform two cycles of flush, compact, and GC
    6991           66 :             for round in 0..2 {
    6992           44 :                 tline.freeze_and_flush().await?;
    6993           44 :                 tline
    6994           44 :                     .compact(
    6995           44 :                         &cancel,
    6996           44 :                         if iter % 5 == 0 && round == 0 {
    6997            6 :                             let mut flags = EnumSet::new();
    6998            6 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    6999            6 :                             flags.insert(CompactFlags::ForceRepartition);
    7000            6 :                             flags
    7001            2 :                         } else {
    7002           38 :                             EnumSet::empty()
    7003            2 :                         },
    7004           44 :                         &ctx,
    7005            2 :                     )
    7006         6672 :                     .await?;
    7007           44 :                 tenant
    7008           44 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7009            2 :                     .await?;
    7010            2 :             }
    7011            2 :         }
    7012            2 : 
    7013            2 :         Ok(())
    7014            2 :     }
    7015              : 
    7016              :     #[tokio::test]
    7017            2 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7018            2 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7019           19 :         let (tenant, ctx) = harness.load().await;
    7020            2 :         let tline = tenant
    7021            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7022            6 :             .await?;
    7023            2 : 
    7024            2 :         let cancel = CancellationToken::new();
    7025            2 : 
    7026            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7027            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7028            2 :         let test_key = base_key;
    7029            2 :         let mut lsn = Lsn(0x10);
    7030            2 : 
    7031           42 :         for _ in 0..20 {
    7032           40 :             lsn = Lsn(lsn.0 + 0x10);
    7033           40 :             let mut writer = tline.writer().await;
    7034           40 :             writer
    7035           40 :                 .put(
    7036           40 :                     test_key,
    7037           40 :                     lsn,
    7038           40 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7039           40 :                     &ctx,
    7040           40 :                 )
    7041           20 :                 .await?;
    7042           40 :             writer.finish_write(lsn);
    7043           40 :             drop(writer);
    7044           40 :             tline.freeze_and_flush().await?; // force create a delta layer
    7045            2 :         }
    7046            2 : 
    7047            2 :         let before_num_l0_delta_files =
    7048            2 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7049            2 : 
    7050          110 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7051            2 : 
    7052            2 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7053            2 : 
    7054            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}");
    7055            2 : 
    7056            2 :         assert_eq!(
    7057            4 :             tline.get(test_key, lsn, &ctx).await?,
    7058            2 :             test_img(&format!("{} at {}", 0, lsn))
    7059            2 :         );
    7060            2 : 
    7061            2 :         Ok(())
    7062            2 :     }
    7063              : 
    7064              :     #[tokio::test]
    7065            2 :     async fn test_aux_file_e2e() {
    7066            2 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7067            2 : 
    7068           20 :         let (tenant, ctx) = harness.load().await;
    7069            2 : 
    7070            2 :         let mut lsn = Lsn(0x08);
    7071            2 : 
    7072            2 :         let tline: Arc<Timeline> = tenant
    7073            2 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7074            6 :             .await
    7075            2 :             .unwrap();
    7076            2 : 
    7077            2 :         {
    7078            2 :             lsn += 8;
    7079            2 :             let mut modification = tline.begin_modification(lsn);
    7080            2 :             modification
    7081            2 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7082            2 :                 .await
    7083            2 :                 .unwrap();
    7084            2 :             modification.commit(&ctx).await.unwrap();
    7085            2 :         }
    7086            2 : 
    7087            2 :         // we can read everything from the storage
    7088            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7089            2 :         assert_eq!(
    7090            2 :             files.get("pg_logical/mappings/test1"),
    7091            2 :             Some(&bytes::Bytes::from_static(b"first"))
    7092            2 :         );
    7093            2 : 
    7094            2 :         {
    7095            2 :             lsn += 8;
    7096            2 :             let mut modification = tline.begin_modification(lsn);
    7097            2 :             modification
    7098            2 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7099            2 :                 .await
    7100            2 :                 .unwrap();
    7101            2 :             modification.commit(&ctx).await.unwrap();
    7102            2 :         }
    7103            2 : 
    7104            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7105            2 :         assert_eq!(
    7106            2 :             files.get("pg_logical/mappings/test2"),
    7107            2 :             Some(&bytes::Bytes::from_static(b"second"))
    7108            2 :         );
    7109            2 : 
    7110            2 :         let child = tenant
    7111            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7112            2 :             .await
    7113            2 :             .unwrap();
    7114            2 : 
    7115            2 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    7116            2 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7117            2 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7118            2 :     }
    7119              : 
    7120              :     #[tokio::test]
    7121            2 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7122            2 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7123           20 :         let (tenant, ctx) = harness.load().await;
    7124            2 :         let tline = tenant
    7125            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7126            6 :             .await?;
    7127            2 : 
    7128            2 :         const NUM_KEYS: usize = 1000;
    7129            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7130            2 : 
    7131            2 :         let cancel = CancellationToken::new();
    7132            2 : 
    7133            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7134            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7135            2 :         let mut test_key = base_key;
    7136            2 :         let mut lsn = Lsn(0x10);
    7137            2 : 
    7138            8 :         async fn scan_with_statistics(
    7139            8 :             tline: &Timeline,
    7140            8 :             keyspace: &KeySpace,
    7141            8 :             lsn: Lsn,
    7142            8 :             ctx: &RequestContext,
    7143            8 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7144            8 :             let mut reconstruct_state = ValuesReconstructState::default();
    7145            8 :             let res = tline
    7146            8 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7147          250 :                 .await?;
    7148            8 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7149            8 :         }
    7150            2 : 
    7151            2 :         #[allow(clippy::needless_range_loop)]
    7152         2002 :         for blknum in 0..NUM_KEYS {
    7153         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7154         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7155         2000 :             let mut writer = tline.writer().await;
    7156         2000 :             writer
    7157         2000 :                 .put(
    7158         2000 :                     test_key,
    7159         2000 :                     lsn,
    7160         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7161         2000 :                     &ctx,
    7162         2000 :                 )
    7163            2 :                 .await?;
    7164         2000 :             writer.finish_write(lsn);
    7165         2000 :             drop(writer);
    7166            2 :         }
    7167            2 : 
    7168            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7169            2 : 
    7170           22 :         for iter in 1..=10 {
    7171        20020 :             for _ in 0..NUM_KEYS {
    7172        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7173        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7174        20000 :                 test_key.field6 = (blknum * STEP) as u32;
    7175        20000 :                 let mut writer = tline.writer().await;
    7176        20000 :                 writer
    7177        20000 :                     .put(
    7178        20000 :                         test_key,
    7179        20000 :                         lsn,
    7180        20000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7181        20000 :                         &ctx,
    7182        20000 :                     )
    7183           35 :                     .await?;
    7184        20000 :                 writer.finish_write(lsn);
    7185        20000 :                 drop(writer);
    7186            2 :             }
    7187            2 : 
    7188           20 :             tline.freeze_and_flush().await?;
    7189            2 : 
    7190           20 :             if iter % 5 == 0 {
    7191            4 :                 let (_, before_delta_file_accessed) =
    7192          242 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7193            4 :                 tline
    7194            4 :                     .compact(
    7195            4 :                         &cancel,
    7196            4 :                         {
    7197            4 :                             let mut flags = EnumSet::new();
    7198            4 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7199            4 :                             flags.insert(CompactFlags::ForceRepartition);
    7200            4 :                             flags
    7201            4 :                         },
    7202            4 :                         &ctx,
    7203            4 :                     )
    7204         4818 :                     .await?;
    7205            4 :                 let (_, after_delta_file_accessed) =
    7206            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7207            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}");
    7208            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.
    7209            4 :                 assert!(
    7210            4 :                     after_delta_file_accessed <= 2,
    7211            2 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7212            2 :                 );
    7213           16 :             }
    7214            2 :         }
    7215            2 : 
    7216            2 :         Ok(())
    7217            2 :     }
    7218              : 
    7219              :     #[tokio::test]
    7220            2 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7221            2 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7222           17 :         let (tenant, ctx) = harness.load().await;
    7223            2 : 
    7224            2 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7225            2 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7226            2 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7227            2 : 
    7228            2 :         let tline = tenant
    7229            2 :             .create_test_timeline_with_layers(
    7230            2 :                 TIMELINE_ID,
    7231            2 :                 Lsn(0x10),
    7232            2 :                 DEFAULT_PG_VERSION,
    7233            2 :                 &ctx,
    7234            2 :                 Vec::new(), // delta layers
    7235            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7236            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
    7237            2 :             )
    7238           12 :             .await?;
    7239            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7240            2 : 
    7241            2 :         let child = tenant
    7242            2 :             .branch_timeline_test_with_layers(
    7243            2 :                 &tline,
    7244            2 :                 NEW_TIMELINE_ID,
    7245            2 :                 Some(Lsn(0x20)),
    7246            2 :                 &ctx,
    7247            2 :                 Vec::new(), // delta layers
    7248            2 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7249            2 :                 Lsn(0x30),
    7250            2 :             )
    7251            9 :             .await
    7252            2 :             .unwrap();
    7253            2 : 
    7254            2 :         let lsn = Lsn(0x30);
    7255            2 : 
    7256            2 :         // test vectored get on parent timeline
    7257            2 :         assert_eq!(
    7258            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7259            2 :             Some(test_img("data key 1"))
    7260            2 :         );
    7261            2 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7262            3 :             .await
    7263            2 :             .unwrap_err()
    7264            2 :             .is_missing_key_error());
    7265            2 :         assert!(
    7266            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7267            2 :                 .await
    7268            2 :                 .unwrap_err()
    7269            2 :                 .is_missing_key_error()
    7270            2 :         );
    7271            2 : 
    7272            2 :         // test vectored get on child timeline
    7273            2 :         assert_eq!(
    7274            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7275            2 :             Some(test_img("data key 1"))
    7276            2 :         );
    7277            2 :         assert_eq!(
    7278            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7279            2 :             Some(test_img("data key 2"))
    7280            2 :         );
    7281            2 :         assert!(
    7282            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7283            2 :                 .await
    7284            2 :                 .unwrap_err()
    7285            2 :                 .is_missing_key_error()
    7286            2 :         );
    7287            2 : 
    7288            2 :         Ok(())
    7289            2 :     }
    7290              : 
    7291              :     #[tokio::test]
    7292            2 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7293            2 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7294           20 :         let (tenant, ctx) = harness.load().await;
    7295            2 : 
    7296            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7297            2 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7298            2 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7299            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7300            2 : 
    7301            2 :         let tline = tenant
    7302            2 :             .create_test_timeline_with_layers(
    7303            2 :                 TIMELINE_ID,
    7304            2 :                 Lsn(0x10),
    7305            2 :                 DEFAULT_PG_VERSION,
    7306            2 :                 &ctx,
    7307            2 :                 Vec::new(), // delta layers
    7308            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
    7309            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
    7310            2 :             )
    7311           13 :             .await?;
    7312            2 : 
    7313            2 :         let child = tenant
    7314            2 :             .branch_timeline_test_with_layers(
    7315            2 :                 &tline,
    7316            2 :                 NEW_TIMELINE_ID,
    7317            2 :                 Some(Lsn(0x20)),
    7318            2 :                 &ctx,
    7319            2 :                 Vec::new(), // delta layers
    7320            2 :                 vec![(
    7321            2 :                     Lsn(0x30),
    7322            2 :                     vec![(base_key_child, test_img("metadata key 2"))],
    7323            2 :                 )], // image layers
    7324            2 :                 Lsn(0x30),
    7325            2 :             )
    7326            9 :             .await
    7327            2 :             .unwrap();
    7328            2 : 
    7329            2 :         let lsn = Lsn(0x30);
    7330            2 : 
    7331            2 :         // test vectored get on parent timeline
    7332            2 :         assert_eq!(
    7333            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7334            2 :             Some(test_img("metadata key 1"))
    7335            2 :         );
    7336            2 :         assert_eq!(
    7337            2 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7338            2 :             None
    7339            2 :         );
    7340            2 :         assert_eq!(
    7341            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7342            2 :             None
    7343            2 :         );
    7344            2 : 
    7345            2 :         // test vectored get on child timeline
    7346            2 :         assert_eq!(
    7347            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7348            2 :             None
    7349            2 :         );
    7350            2 :         assert_eq!(
    7351            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7352            2 :             Some(test_img("metadata key 2"))
    7353            2 :         );
    7354            2 :         assert_eq!(
    7355            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7356            2 :             None
    7357            2 :         );
    7358            2 : 
    7359            2 :         Ok(())
    7360            2 :     }
    7361              : 
    7362           36 :     async fn get_vectored_impl_wrapper(
    7363           36 :         tline: &Arc<Timeline>,
    7364           36 :         key: Key,
    7365           36 :         lsn: Lsn,
    7366           36 :         ctx: &RequestContext,
    7367           36 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7368           36 :         let mut reconstruct_state = ValuesReconstructState::new();
    7369           36 :         let mut res = tline
    7370           36 :             .get_vectored_impl(
    7371           36 :                 KeySpace::single(key..key.next()),
    7372           36 :                 lsn,
    7373           36 :                 &mut reconstruct_state,
    7374           36 :                 ctx,
    7375           36 :             )
    7376           40 :             .await?;
    7377           30 :         Ok(res.pop_last().map(|(k, v)| {
    7378           18 :             assert_eq!(k, key);
    7379           18 :             v.unwrap()
    7380           30 :         }))
    7381           36 :     }
    7382              : 
    7383              :     #[tokio::test]
    7384            2 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    7385            2 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    7386           20 :         let (tenant, ctx) = harness.load().await;
    7387            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7388            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7389            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7390            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7391            2 : 
    7392            2 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    7393            2 :         // Lsn 0x30 key0, key3, no key1+key2
    7394            2 :         // Lsn 0x20 key1+key2 tomestones
    7395            2 :         // Lsn 0x10 key1 in image, key2 in delta
    7396            2 :         let tline = tenant
    7397            2 :             .create_test_timeline_with_layers(
    7398            2 :                 TIMELINE_ID,
    7399            2 :                 Lsn(0x10),
    7400            2 :                 DEFAULT_PG_VERSION,
    7401            2 :                 &ctx,
    7402            2 :                 // delta layers
    7403            2 :                 vec![
    7404            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7405            2 :                         Lsn(0x10)..Lsn(0x20),
    7406            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7407            2 :                     ),
    7408            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7409            2 :                         Lsn(0x20)..Lsn(0x30),
    7410            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7411            2 :                     ),
    7412            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7413            2 :                         Lsn(0x20)..Lsn(0x30),
    7414            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7415            2 :                     ),
    7416            2 :                 ],
    7417            2 :                 // image layers
    7418            2 :                 vec![
    7419            2 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    7420            2 :                     (
    7421            2 :                         Lsn(0x30),
    7422            2 :                         vec![
    7423            2 :                             (key0, test_img("metadata key 0")),
    7424            2 :                             (key3, test_img("metadata key 3")),
    7425            2 :                         ],
    7426            2 :                     ),
    7427            2 :                 ],
    7428            2 :                 Lsn(0x30),
    7429            2 :             )
    7430           40 :             .await?;
    7431            2 : 
    7432            2 :         let lsn = Lsn(0x30);
    7433            2 :         let old_lsn = Lsn(0x20);
    7434            2 : 
    7435            2 :         assert_eq!(
    7436            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    7437            2 :             Some(test_img("metadata key 0"))
    7438            2 :         );
    7439            2 :         assert_eq!(
    7440            2 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    7441            2 :             None,
    7442            2 :         );
    7443            2 :         assert_eq!(
    7444            2 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    7445            2 :             None,
    7446            2 :         );
    7447            2 :         assert_eq!(
    7448            8 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    7449            2 :             Some(Bytes::new()),
    7450            2 :         );
    7451            2 :         assert_eq!(
    7452            7 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    7453            2 :             Some(Bytes::new()),
    7454            2 :         );
    7455            2 :         assert_eq!(
    7456            2 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    7457            2 :             Some(test_img("metadata key 3"))
    7458            2 :         );
    7459            2 : 
    7460            2 :         Ok(())
    7461            2 :     }
    7462              : 
    7463              :     #[tokio::test]
    7464            2 :     async fn test_metadata_tombstone_image_creation() {
    7465            2 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    7466            2 :             .await
    7467            2 :             .unwrap();
    7468           20 :         let (tenant, ctx) = harness.load().await;
    7469            2 : 
    7470            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7471            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7472            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7473            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7474            2 : 
    7475            2 :         let tline = tenant
    7476            2 :             .create_test_timeline_with_layers(
    7477            2 :                 TIMELINE_ID,
    7478            2 :                 Lsn(0x10),
    7479            2 :                 DEFAULT_PG_VERSION,
    7480            2 :                 &ctx,
    7481            2 :                 // delta layers
    7482            2 :                 vec![
    7483            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7484            2 :                         Lsn(0x10)..Lsn(0x20),
    7485            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7486            2 :                     ),
    7487            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7488            2 :                         Lsn(0x20)..Lsn(0x30),
    7489            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7490            2 :                     ),
    7491            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7492            2 :                         Lsn(0x20)..Lsn(0x30),
    7493            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7494            2 :                     ),
    7495            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7496            2 :                         Lsn(0x30)..Lsn(0x40),
    7497            2 :                         vec![
    7498            2 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    7499            2 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    7500            2 :                         ],
    7501            2 :                     ),
    7502            2 :                 ],
    7503            2 :                 // image layers
    7504            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7505            2 :                 Lsn(0x40),
    7506            2 :             )
    7507           37 :             .await
    7508            2 :             .unwrap();
    7509            2 : 
    7510            2 :         let cancel = CancellationToken::new();
    7511            2 : 
    7512            2 :         tline
    7513            2 :             .compact(
    7514            2 :                 &cancel,
    7515            2 :                 {
    7516            2 :                     let mut flags = EnumSet::new();
    7517            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7518            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7519            2 :                     flags
    7520            2 :                 },
    7521            2 :                 &ctx,
    7522            2 :             )
    7523           62 :             .await
    7524            2 :             .unwrap();
    7525            2 : 
    7526            2 :         // Image layers are created at last_record_lsn
    7527            2 :         let images = tline
    7528            2 :             .inspect_image_layers(Lsn(0x40), &ctx)
    7529            8 :             .await
    7530            2 :             .unwrap()
    7531            2 :             .into_iter()
    7532           18 :             .filter(|(k, _)| k.is_metadata_key())
    7533            2 :             .collect::<Vec<_>>();
    7534            2 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    7535            2 :     }
    7536              : 
    7537              :     #[tokio::test]
    7538            2 :     async fn test_metadata_tombstone_empty_image_creation() {
    7539            2 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    7540            2 :             .await
    7541            2 :             .unwrap();
    7542           20 :         let (tenant, ctx) = harness.load().await;
    7543            2 : 
    7544            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7545            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7546            2 : 
    7547            2 :         let tline = tenant
    7548            2 :             .create_test_timeline_with_layers(
    7549            2 :                 TIMELINE_ID,
    7550            2 :                 Lsn(0x10),
    7551            2 :                 DEFAULT_PG_VERSION,
    7552            2 :                 &ctx,
    7553            2 :                 // delta layers
    7554            2 :                 vec![
    7555            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7556            2 :                         Lsn(0x10)..Lsn(0x20),
    7557            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7558            2 :                     ),
    7559            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7560            2 :                         Lsn(0x20)..Lsn(0x30),
    7561            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7562            2 :                     ),
    7563            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7564            2 :                         Lsn(0x20)..Lsn(0x30),
    7565            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7566            2 :                     ),
    7567            2 :                 ],
    7568            2 :                 // image layers
    7569            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7570            2 :                 Lsn(0x30),
    7571            2 :             )
    7572           31 :             .await
    7573            2 :             .unwrap();
    7574            2 : 
    7575            2 :         let cancel = CancellationToken::new();
    7576            2 : 
    7577            2 :         tline
    7578            2 :             .compact(
    7579            2 :                 &cancel,
    7580            2 :                 {
    7581            2 :                     let mut flags = EnumSet::new();
    7582            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7583            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7584            2 :                     flags
    7585            2 :                 },
    7586            2 :                 &ctx,
    7587            2 :             )
    7588           50 :             .await
    7589            2 :             .unwrap();
    7590            2 : 
    7591            2 :         // Image layers are created at last_record_lsn
    7592            2 :         let images = tline
    7593            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    7594            4 :             .await
    7595            2 :             .unwrap()
    7596            2 :             .into_iter()
    7597           14 :             .filter(|(k, _)| k.is_metadata_key())
    7598            2 :             .collect::<Vec<_>>();
    7599            2 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    7600            2 :     }
    7601              : 
    7602              :     #[tokio::test]
    7603            2 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    7604            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    7605           20 :         let (tenant, ctx) = harness.load().await;
    7606            2 : 
    7607          102 :         fn get_key(id: u32) -> Key {
    7608          102 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7609          102 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7610          102 :             key.field6 = id;
    7611          102 :             key
    7612          102 :         }
    7613            2 : 
    7614            2 :         // We create
    7615            2 :         // - one bottom-most image layer,
    7616            2 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    7617            2 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    7618            2 :         // - a delta layer D3 above the horizon.
    7619            2 :         //
    7620            2 :         //                             | D3 |
    7621            2 :         //  | D1 |
    7622            2 :         // -|    |-- gc horizon -----------------
    7623            2 :         //  |    |                | D2 |
    7624            2 :         // --------- img layer ------------------
    7625            2 :         //
    7626            2 :         // What we should expact from this compaction is:
    7627            2 :         //                             | D3 |
    7628            2 :         //  | Part of D1 |
    7629            2 :         // --------- img layer with D1+D2 at GC horizon------------------
    7630            2 : 
    7631            2 :         // img layer at 0x10
    7632            2 :         let img_layer = (0..10)
    7633           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    7634            2 :             .collect_vec();
    7635            2 : 
    7636            2 :         let delta1 = vec![
    7637            2 :             (
    7638            2 :                 get_key(1),
    7639            2 :                 Lsn(0x20),
    7640            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    7641            2 :             ),
    7642            2 :             (
    7643            2 :                 get_key(2),
    7644            2 :                 Lsn(0x30),
    7645            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    7646            2 :             ),
    7647            2 :             (
    7648            2 :                 get_key(3),
    7649            2 :                 Lsn(0x40),
    7650            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    7651            2 :             ),
    7652            2 :         ];
    7653            2 :         let delta2 = vec![
    7654            2 :             (
    7655            2 :                 get_key(5),
    7656            2 :                 Lsn(0x20),
    7657            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    7658            2 :             ),
    7659            2 :             (
    7660            2 :                 get_key(6),
    7661            2 :                 Lsn(0x20),
    7662            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    7663            2 :             ),
    7664            2 :         ];
    7665            2 :         let delta3 = vec![
    7666            2 :             (
    7667            2 :                 get_key(8),
    7668            2 :                 Lsn(0x48),
    7669            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    7670            2 :             ),
    7671            2 :             (
    7672            2 :                 get_key(9),
    7673            2 :                 Lsn(0x48),
    7674            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    7675            2 :             ),
    7676            2 :         ];
    7677            2 : 
    7678            2 :         let tline = tenant
    7679            2 :             .create_test_timeline_with_layers(
    7680            2 :                 TIMELINE_ID,
    7681            2 :                 Lsn(0x10),
    7682            2 :                 DEFAULT_PG_VERSION,
    7683            2 :                 &ctx,
    7684            2 :                 vec![
    7685            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    7686            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    7687            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    7688            2 :                 ], // delta layers
    7689            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    7690            2 :                 Lsn(0x50),
    7691            2 :             )
    7692           49 :             .await?;
    7693            2 :         {
    7694            2 :             // Update GC info
    7695            2 :             let mut guard = tline.gc_info.write().unwrap();
    7696            2 :             guard.cutoffs.time = Lsn(0x30);
    7697            2 :             guard.cutoffs.space = Lsn(0x30);
    7698            2 :         }
    7699            2 : 
    7700            2 :         let expected_result = [
    7701            2 :             Bytes::from_static(b"value 0@0x10"),
    7702            2 :             Bytes::from_static(b"value 1@0x20"),
    7703            2 :             Bytes::from_static(b"value 2@0x30"),
    7704            2 :             Bytes::from_static(b"value 3@0x40"),
    7705            2 :             Bytes::from_static(b"value 4@0x10"),
    7706            2 :             Bytes::from_static(b"value 5@0x20"),
    7707            2 :             Bytes::from_static(b"value 6@0x20"),
    7708            2 :             Bytes::from_static(b"value 7@0x10"),
    7709            2 :             Bytes::from_static(b"value 8@0x48"),
    7710            2 :             Bytes::from_static(b"value 9@0x48"),
    7711            2 :         ];
    7712            2 : 
    7713           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    7714           20 :             assert_eq!(
    7715           20 :                 tline
    7716           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7717           30 :                     .await
    7718           20 :                     .unwrap(),
    7719            2 :                 expected
    7720            2 :             );
    7721            2 :         }
    7722            2 : 
    7723            2 :         let cancel = CancellationToken::new();
    7724            2 :         tline
    7725            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7726           56 :             .await
    7727            2 :             .unwrap();
    7728            2 : 
    7729           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    7730           20 :             assert_eq!(
    7731           20 :                 tline
    7732           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    7733           20 :                     .await
    7734           20 :                     .unwrap(),
    7735            2 :                 expected
    7736            2 :             );
    7737            2 :         }
    7738            2 : 
    7739            2 :         // Check if the image layer at the GC horizon contains exactly what we want
    7740            2 :         let image_at_gc_horizon = tline
    7741            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    7742            2 :             .await
    7743            2 :             .unwrap()
    7744            2 :             .into_iter()
    7745           34 :             .filter(|(k, _)| k.is_metadata_key())
    7746            2 :             .collect::<Vec<_>>();
    7747            2 : 
    7748            2 :         assert_eq!(image_at_gc_horizon.len(), 10);
    7749            2 :         let expected_result = [
    7750            2 :             Bytes::from_static(b"value 0@0x10"),
    7751            2 :             Bytes::from_static(b"value 1@0x20"),
    7752            2 :             Bytes::from_static(b"value 2@0x30"),
    7753            2 :             Bytes::from_static(b"value 3@0x10"),
    7754            2 :             Bytes::from_static(b"value 4@0x10"),
    7755            2 :             Bytes::from_static(b"value 5@0x20"),
    7756            2 :             Bytes::from_static(b"value 6@0x20"),
    7757            2 :             Bytes::from_static(b"value 7@0x10"),
    7758            2 :             Bytes::from_static(b"value 8@0x10"),
    7759            2 :             Bytes::from_static(b"value 9@0x10"),
    7760            2 :         ];
    7761           22 :         for idx in 0..10 {
    7762           20 :             assert_eq!(
    7763           20 :                 image_at_gc_horizon[idx],
    7764           20 :                 (get_key(idx as u32), expected_result[idx].clone())
    7765           20 :             );
    7766            2 :         }
    7767            2 : 
    7768            2 :         // Check if old layers are removed / new layers have the expected LSN
    7769            2 :         let all_layers = inspect_and_sort(&tline, None).await;
    7770            2 :         assert_eq!(
    7771            2 :             all_layers,
    7772            2 :             vec![
    7773            2 :                 // Image layer at GC horizon
    7774            2 :                 PersistentLayerKey {
    7775            2 :                     key_range: Key::MIN..Key::MAX,
    7776            2 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    7777            2 :                     is_delta: false
    7778            2 :                 },
    7779            2 :                 // The delta layer below the horizon
    7780            2 :                 PersistentLayerKey {
    7781            2 :                     key_range: get_key(3)..get_key(4),
    7782            2 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    7783            2 :                     is_delta: true
    7784            2 :                 },
    7785            2 :                 // The delta3 layer that should not be picked for the compaction
    7786            2 :                 PersistentLayerKey {
    7787            2 :                     key_range: get_key(8)..get_key(10),
    7788            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    7789            2 :                     is_delta: true
    7790            2 :                 }
    7791            2 :             ]
    7792            2 :         );
    7793            2 : 
    7794            2 :         // increase GC horizon and compact again
    7795            2 :         {
    7796            2 :             // Update GC info
    7797            2 :             let mut guard = tline.gc_info.write().unwrap();
    7798            2 :             guard.cutoffs.time = Lsn(0x40);
    7799            2 :             guard.cutoffs.space = Lsn(0x40);
    7800            2 :         }
    7801            2 :         tline
    7802            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    7803           43 :             .await
    7804            2 :             .unwrap();
    7805            2 : 
    7806            2 :         Ok(())
    7807            2 :     }
    7808              : 
    7809              :     #[cfg(feature = "testing")]
    7810              :     #[tokio::test]
    7811            2 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    7812            2 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    7813           20 :         let (tenant, ctx) = harness.load().await;
    7814            2 : 
    7815           24 :         fn get_key(id: u32) -> Key {
    7816           24 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    7817           24 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7818           24 :             key.field6 = id;
    7819           24 :             key
    7820           24 :         }
    7821            2 : 
    7822            2 :         let delta1 = vec![
    7823            2 :             (
    7824            2 :                 get_key(1),
    7825            2 :                 Lsn(0x20),
    7826            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    7827            2 :             ),
    7828            2 :             (
    7829            2 :                 get_key(1),
    7830            2 :                 Lsn(0x30),
    7831            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    7832            2 :             ),
    7833            2 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    7834            2 :             (
    7835            2 :                 get_key(2),
    7836            2 :                 Lsn(0x20),
    7837            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    7838            2 :             ),
    7839            2 :             (
    7840            2 :                 get_key(2),
    7841            2 :                 Lsn(0x30),
    7842            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    7843            2 :             ),
    7844            2 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    7845            2 :             (
    7846            2 :                 get_key(3),
    7847            2 :                 Lsn(0x20),
    7848            2 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    7849            2 :             ),
    7850            2 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    7851            2 :             (
    7852            2 :                 get_key(4),
    7853            2 :                 Lsn(0x20),
    7854            2 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    7855            2 :             ),
    7856            2 :         ];
    7857            2 :         let image1 = vec![(get_key(1), "0x10".into())];
    7858            2 : 
    7859            2 :         let tline = tenant
    7860            2 :             .create_test_timeline_with_layers(
    7861            2 :                 TIMELINE_ID,
    7862            2 :                 Lsn(0x10),
    7863            2 :                 DEFAULT_PG_VERSION,
    7864            2 :                 &ctx,
    7865            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    7866            2 :                     Lsn(0x10)..Lsn(0x40),
    7867            2 :                     delta1,
    7868            2 :                 )], // delta layers
    7869            2 :                 vec![(Lsn(0x10), image1)], // image layers
    7870            2 :                 Lsn(0x50),
    7871            2 :             )
    7872           19 :             .await?;
    7873            2 : 
    7874            2 :         assert_eq!(
    7875            8 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    7876            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    7877            2 :         );
    7878            2 :         assert_eq!(
    7879            2 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    7880            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    7881            2 :         );
    7882            2 : 
    7883            2 :         // Need to remove the limit of "Neon WAL redo requires base image".
    7884            2 : 
    7885            2 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    7886            2 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    7887            2 : 
    7888            2 :         Ok(())
    7889            2 :     }
    7890              : 
    7891              :     #[tokio::test(start_paused = true)]
    7892            2 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    7893            2 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    7894            2 :             .await
    7895            2 :             .unwrap()
    7896            2 :             .load()
    7897           20 :             .await;
    7898            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    7899            2 :         // initial transition into AttachedSingle.
    7900            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    7901            2 :         tokio::time::resume();
    7902            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7903            2 : 
    7904            2 :         let end_lsn = Lsn(0x100);
    7905            2 :         let image_layers = (0x20..=0x90)
    7906            2 :             .step_by(0x10)
    7907           16 :             .map(|n| {
    7908           16 :                 (
    7909           16 :                     Lsn(n),
    7910           16 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    7911           16 :                 )
    7912           16 :             })
    7913            2 :             .collect();
    7914            2 : 
    7915            2 :         let timeline = tenant
    7916            2 :             .create_test_timeline_with_layers(
    7917            2 :                 TIMELINE_ID,
    7918            2 :                 Lsn(0x10),
    7919            2 :                 DEFAULT_PG_VERSION,
    7920            2 :                 &ctx,
    7921            2 :                 Vec::new(),
    7922            2 :                 image_layers,
    7923            2 :                 end_lsn,
    7924            2 :             )
    7925           62 :             .await?;
    7926            2 : 
    7927            2 :         let leased_lsns = [0x30, 0x50, 0x70];
    7928            2 :         let mut leases = Vec::new();
    7929            6 :         leased_lsns.iter().for_each(|n| {
    7930            6 :             leases.push(
    7931            6 :                 timeline
    7932            6 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    7933            6 :                     .expect("lease request should succeed"),
    7934            6 :             );
    7935            6 :         });
    7936            2 : 
    7937            2 :         let updated_lease_0 = timeline
    7938            2 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    7939            2 :             .expect("lease renewal should succeed");
    7940            2 :         assert_eq!(
    7941            2 :             updated_lease_0.valid_until, leases[0].valid_until,
    7942            2 :             " Renewing with shorter lease should not change the lease."
    7943            2 :         );
    7944            2 : 
    7945            2 :         let updated_lease_1 = timeline
    7946            2 :             .renew_lsn_lease(
    7947            2 :                 Lsn(leased_lsns[1]),
    7948            2 :                 timeline.get_lsn_lease_length() * 2,
    7949            2 :                 &ctx,
    7950            2 :             )
    7951            2 :             .expect("lease renewal should succeed");
    7952            2 :         assert!(
    7953            2 :             updated_lease_1.valid_until > leases[1].valid_until,
    7954            2 :             "Renewing with a long lease should renew lease with later expiration time."
    7955            2 :         );
    7956            2 : 
    7957            2 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    7958            2 :         info!(
    7959            2 :             "latest_gc_cutoff_lsn: {}",
    7960            0 :             *timeline.get_latest_gc_cutoff_lsn()
    7961            2 :         );
    7962            2 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    7963            2 : 
    7964            2 :         let res = tenant
    7965            2 :             .gc_iteration(
    7966            2 :                 Some(TIMELINE_ID),
    7967            2 :                 0,
    7968            2 :                 Duration::ZERO,
    7969            2 :                 &CancellationToken::new(),
    7970            2 :                 &ctx,
    7971            2 :             )
    7972            2 :             .await
    7973            2 :             .unwrap();
    7974            2 : 
    7975            2 :         // Keeping everything <= Lsn(0x80) b/c leases:
    7976            2 :         // 0/10: initdb layer
    7977            2 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    7978            2 :         assert_eq!(res.layers_needed_by_leases, 7);
    7979            2 :         // Keeping 0/90 b/c it is the latest layer.
    7980            2 :         assert_eq!(res.layers_not_updated, 1);
    7981            2 :         // Removed 0/80.
    7982            2 :         assert_eq!(res.layers_removed, 1);
    7983            2 : 
    7984            2 :         // Make lease on a already GC-ed LSN.
    7985            2 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    7986            2 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    7987            2 :         timeline
    7988            2 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    7989            2 :             .expect_err("lease request on GC-ed LSN should fail");
    7990            2 : 
    7991            2 :         // Should still be able to renew a currently valid lease
    7992            2 :         // Assumption: original lease to is still valid for 0/50.
    7993            2 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    7994            2 :         timeline
    7995            2 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    7996            2 :             .expect("lease renewal with validation should succeed");
    7997            2 : 
    7998            2 :         Ok(())
    7999            2 :     }
    8000              : 
    8001              :     #[cfg(feature = "testing")]
    8002              :     #[tokio::test]
    8003            2 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8004            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8005            2 :             "test_simple_bottom_most_compaction_deltas_1",
    8006            2 :             false,
    8007            2 :         )
    8008          240 :         .await
    8009            2 :     }
    8010              : 
    8011              :     #[cfg(feature = "testing")]
    8012              :     #[tokio::test]
    8013            2 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8014            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8015            2 :             "test_simple_bottom_most_compaction_deltas_2",
    8016            2 :             true,
    8017            2 :         )
    8018          225 :         .await
    8019            2 :     }
    8020              : 
    8021              :     #[cfg(feature = "testing")]
    8022            4 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8023            4 :         test_name: &'static str,
    8024            4 :         use_delta_bottom_layer: bool,
    8025            4 :     ) -> anyhow::Result<()> {
    8026            4 :         let harness = TenantHarness::create(test_name).await?;
    8027           40 :         let (tenant, ctx) = harness.load().await;
    8028              : 
    8029          276 :         fn get_key(id: u32) -> Key {
    8030          276 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8031          276 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8032          276 :             key.field6 = id;
    8033          276 :             key
    8034          276 :         }
    8035              : 
    8036              :         // We create
    8037              :         // - one bottom-most image layer,
    8038              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8039              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8040              :         // - a delta layer D3 above the horizon.
    8041              :         //
    8042              :         //                             | D3 |
    8043              :         //  | D1 |
    8044              :         // -|    |-- gc horizon -----------------
    8045              :         //  |    |                | D2 |
    8046              :         // --------- img layer ------------------
    8047              :         //
    8048              :         // What we should expact from this compaction is:
    8049              :         //                             | D3 |
    8050              :         //  | Part of D1 |
    8051              :         // --------- img layer with D1+D2 at GC horizon------------------
    8052              : 
    8053              :         // img layer at 0x10
    8054            4 :         let img_layer = (0..10)
    8055           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8056            4 :             .collect_vec();
    8057            4 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8058            4 :         let delta4 = (0..10)
    8059           40 :             .map(|id| {
    8060           40 :                 (
    8061           40 :                     get_key(id),
    8062           40 :                     Lsn(0x08),
    8063           40 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8064           40 :                 )
    8065           40 :             })
    8066            4 :             .collect_vec();
    8067            4 : 
    8068            4 :         let delta1 = vec![
    8069            4 :             (
    8070            4 :                 get_key(1),
    8071            4 :                 Lsn(0x20),
    8072            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8073            4 :             ),
    8074            4 :             (
    8075            4 :                 get_key(2),
    8076            4 :                 Lsn(0x30),
    8077            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8078            4 :             ),
    8079            4 :             (
    8080            4 :                 get_key(3),
    8081            4 :                 Lsn(0x28),
    8082            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8083            4 :             ),
    8084            4 :             (
    8085            4 :                 get_key(3),
    8086            4 :                 Lsn(0x30),
    8087            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8088            4 :             ),
    8089            4 :             (
    8090            4 :                 get_key(3),
    8091            4 :                 Lsn(0x40),
    8092            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8093            4 :             ),
    8094            4 :         ];
    8095            4 :         let delta2 = vec![
    8096            4 :             (
    8097            4 :                 get_key(5),
    8098            4 :                 Lsn(0x20),
    8099            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8100            4 :             ),
    8101            4 :             (
    8102            4 :                 get_key(6),
    8103            4 :                 Lsn(0x20),
    8104            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8105            4 :             ),
    8106            4 :         ];
    8107            4 :         let delta3 = vec![
    8108            4 :             (
    8109            4 :                 get_key(8),
    8110            4 :                 Lsn(0x48),
    8111            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8112            4 :             ),
    8113            4 :             (
    8114            4 :                 get_key(9),
    8115            4 :                 Lsn(0x48),
    8116            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8117            4 :             ),
    8118            4 :         ];
    8119              : 
    8120            4 :         let tline = if use_delta_bottom_layer {
    8121            2 :             tenant
    8122            2 :                 .create_test_timeline_with_layers(
    8123            2 :                     TIMELINE_ID,
    8124            2 :                     Lsn(0x08),
    8125            2 :                     DEFAULT_PG_VERSION,
    8126            2 :                     &ctx,
    8127            2 :                     vec![
    8128            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8129            2 :                             Lsn(0x08)..Lsn(0x10),
    8130            2 :                             delta4,
    8131            2 :                         ),
    8132            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8133            2 :                             Lsn(0x20)..Lsn(0x48),
    8134            2 :                             delta1,
    8135            2 :                         ),
    8136            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8137            2 :                             Lsn(0x20)..Lsn(0x48),
    8138            2 :                             delta2,
    8139            2 :                         ),
    8140            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8141            2 :                             Lsn(0x48)..Lsn(0x50),
    8142            2 :                             delta3,
    8143            2 :                         ),
    8144            2 :                     ], // delta layers
    8145            2 :                     vec![], // image layers
    8146            2 :                     Lsn(0x50),
    8147            2 :                 )
    8148           30 :                 .await?
    8149              :         } else {
    8150            2 :             tenant
    8151            2 :                 .create_test_timeline_with_layers(
    8152            2 :                     TIMELINE_ID,
    8153            2 :                     Lsn(0x10),
    8154            2 :                     DEFAULT_PG_VERSION,
    8155            2 :                     &ctx,
    8156            2 :                     vec![
    8157            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8158            2 :                             Lsn(0x10)..Lsn(0x48),
    8159            2 :                             delta1,
    8160            2 :                         ),
    8161            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8162            2 :                             Lsn(0x10)..Lsn(0x48),
    8163            2 :                             delta2,
    8164            2 :                         ),
    8165            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8166            2 :                             Lsn(0x48)..Lsn(0x50),
    8167            2 :                             delta3,
    8168            2 :                         ),
    8169            2 :                     ], // delta layers
    8170            2 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8171            2 :                     Lsn(0x50),
    8172            2 :                 )
    8173           49 :                 .await?
    8174              :         };
    8175            4 :         {
    8176            4 :             // Update GC info
    8177            4 :             let mut guard = tline.gc_info.write().unwrap();
    8178            4 :             *guard = GcInfo {
    8179            4 :                 retain_lsns: vec![],
    8180            4 :                 cutoffs: GcCutoffs {
    8181            4 :                     time: Lsn(0x30),
    8182            4 :                     space: Lsn(0x30),
    8183            4 :                 },
    8184            4 :                 leases: Default::default(),
    8185            4 :                 within_ancestor_pitr: false,
    8186            4 :             };
    8187            4 :         }
    8188            4 : 
    8189            4 :         let expected_result = [
    8190            4 :             Bytes::from_static(b"value 0@0x10"),
    8191            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8192            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8193            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8194            4 :             Bytes::from_static(b"value 4@0x10"),
    8195            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8196            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8197            4 :             Bytes::from_static(b"value 7@0x10"),
    8198            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8199            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8200            4 :         ];
    8201            4 : 
    8202            4 :         let expected_result_at_gc_horizon = [
    8203            4 :             Bytes::from_static(b"value 0@0x10"),
    8204            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8205            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8206            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8207            4 :             Bytes::from_static(b"value 4@0x10"),
    8208            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8209            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8210            4 :             Bytes::from_static(b"value 7@0x10"),
    8211            4 :             Bytes::from_static(b"value 8@0x10"),
    8212            4 :             Bytes::from_static(b"value 9@0x10"),
    8213            4 :         ];
    8214              : 
    8215           44 :         for idx in 0..10 {
    8216           40 :             assert_eq!(
    8217           40 :                 tline
    8218           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8219           60 :                     .await
    8220           40 :                     .unwrap(),
    8221           40 :                 &expected_result[idx]
    8222              :             );
    8223           40 :             assert_eq!(
    8224           40 :                 tline
    8225           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8226           31 :                     .await
    8227           40 :                     .unwrap(),
    8228           40 :                 &expected_result_at_gc_horizon[idx]
    8229              :             );
    8230              :         }
    8231              : 
    8232            4 :         let cancel = CancellationToken::new();
    8233            4 :         tline
    8234            4 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8235          108 :             .await
    8236            4 :             .unwrap();
    8237              : 
    8238           44 :         for idx in 0..10 {
    8239           40 :             assert_eq!(
    8240           40 :                 tline
    8241           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8242           40 :                     .await
    8243           40 :                     .unwrap(),
    8244           40 :                 &expected_result[idx]
    8245              :             );
    8246           40 :             assert_eq!(
    8247           40 :                 tline
    8248           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8249           20 :                     .await
    8250           40 :                     .unwrap(),
    8251           40 :                 &expected_result_at_gc_horizon[idx]
    8252              :             );
    8253              :         }
    8254              : 
    8255              :         // increase GC horizon and compact again
    8256            4 :         {
    8257            4 :             // Update GC info
    8258            4 :             let mut guard = tline.gc_info.write().unwrap();
    8259            4 :             guard.cutoffs.time = Lsn(0x40);
    8260            4 :             guard.cutoffs.space = Lsn(0x40);
    8261            4 :         }
    8262            4 :         tline
    8263            4 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8264           87 :             .await
    8265            4 :             .unwrap();
    8266            4 : 
    8267            4 :         Ok(())
    8268            4 :     }
    8269              : 
    8270              :     #[cfg(feature = "testing")]
    8271              :     #[tokio::test]
    8272            2 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8273            2 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8274           20 :         let (tenant, ctx) = harness.load().await;
    8275            2 :         let tline = tenant
    8276            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8277            6 :             .await?;
    8278            2 :         tline.force_advance_lsn(Lsn(0x70));
    8279            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8280            2 :         let history = vec![
    8281            2 :             (
    8282            2 :                 key,
    8283            2 :                 Lsn(0x10),
    8284            2 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8285            2 :             ),
    8286            2 :             (
    8287            2 :                 key,
    8288            2 :                 Lsn(0x20),
    8289            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8290            2 :             ),
    8291            2 :             (
    8292            2 :                 key,
    8293            2 :                 Lsn(0x30),
    8294            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8295            2 :             ),
    8296            2 :             (
    8297            2 :                 key,
    8298            2 :                 Lsn(0x40),
    8299            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8300            2 :             ),
    8301            2 :             (
    8302            2 :                 key,
    8303            2 :                 Lsn(0x50),
    8304            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8305            2 :             ),
    8306            2 :             (
    8307            2 :                 key,
    8308            2 :                 Lsn(0x60),
    8309            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8310            2 :             ),
    8311            2 :             (
    8312            2 :                 key,
    8313            2 :                 Lsn(0x70),
    8314            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8315            2 :             ),
    8316            2 :             (
    8317            2 :                 key,
    8318            2 :                 Lsn(0x80),
    8319            2 :                 Value::Image(Bytes::copy_from_slice(
    8320            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8321            2 :                 )),
    8322            2 :             ),
    8323            2 :             (
    8324            2 :                 key,
    8325            2 :                 Lsn(0x90),
    8326            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8327            2 :             ),
    8328            2 :         ];
    8329            2 :         let res = tline
    8330            2 :             .generate_key_retention(
    8331            2 :                 key,
    8332            2 :                 &history,
    8333            2 :                 Lsn(0x60),
    8334            2 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8335            2 :                 3,
    8336            2 :                 None,
    8337            2 :             )
    8338            2 :             .await
    8339            2 :             .unwrap();
    8340            2 :         let expected_res = KeyHistoryRetention {
    8341            2 :             below_horizon: vec![
    8342            2 :                 (
    8343            2 :                     Lsn(0x20),
    8344            2 :                     KeyLogAtLsn(vec![(
    8345            2 :                         Lsn(0x20),
    8346            2 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8347            2 :                     )]),
    8348            2 :                 ),
    8349            2 :                 (
    8350            2 :                     Lsn(0x40),
    8351            2 :                     KeyLogAtLsn(vec![
    8352            2 :                         (
    8353            2 :                             Lsn(0x30),
    8354            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8355            2 :                         ),
    8356            2 :                         (
    8357            2 :                             Lsn(0x40),
    8358            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8359            2 :                         ),
    8360            2 :                     ]),
    8361            2 :                 ),
    8362            2 :                 (
    8363            2 :                     Lsn(0x50),
    8364            2 :                     KeyLogAtLsn(vec![(
    8365            2 :                         Lsn(0x50),
    8366            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    8367            2 :                     )]),
    8368            2 :                 ),
    8369            2 :                 (
    8370            2 :                     Lsn(0x60),
    8371            2 :                     KeyLogAtLsn(vec![(
    8372            2 :                         Lsn(0x60),
    8373            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8374            2 :                     )]),
    8375            2 :                 ),
    8376            2 :             ],
    8377            2 :             above_horizon: KeyLogAtLsn(vec![
    8378            2 :                 (
    8379            2 :                     Lsn(0x70),
    8380            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8381            2 :                 ),
    8382            2 :                 (
    8383            2 :                     Lsn(0x80),
    8384            2 :                     Value::Image(Bytes::copy_from_slice(
    8385            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8386            2 :                     )),
    8387            2 :                 ),
    8388            2 :                 (
    8389            2 :                     Lsn(0x90),
    8390            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8391            2 :                 ),
    8392            2 :             ]),
    8393            2 :         };
    8394            2 :         assert_eq!(res, expected_res);
    8395            2 : 
    8396            2 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    8397            2 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    8398            2 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    8399            2 :         // For example, we have
    8400            2 :         // ```plain
    8401            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    8402            2 :         // ```
    8403            2 :         // Now the GC horizon moves up, and we have
    8404            2 :         // ```plain
    8405            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    8406            2 :         // ```
    8407            2 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    8408            2 :         // We will end up with
    8409            2 :         // ```plain
    8410            2 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    8411            2 :         // ```
    8412            2 :         // Now we run the GC-compaction, and this key does not have a full history.
    8413            2 :         // We should be able to handle this partial history and drop everything before the
    8414            2 :         // gc_horizon image.
    8415            2 : 
    8416            2 :         let history = vec![
    8417            2 :             (
    8418            2 :                 key,
    8419            2 :                 Lsn(0x20),
    8420            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8421            2 :             ),
    8422            2 :             (
    8423            2 :                 key,
    8424            2 :                 Lsn(0x30),
    8425            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8426            2 :             ),
    8427            2 :             (
    8428            2 :                 key,
    8429            2 :                 Lsn(0x40),
    8430            2 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8431            2 :             ),
    8432            2 :             (
    8433            2 :                 key,
    8434            2 :                 Lsn(0x50),
    8435            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8436            2 :             ),
    8437            2 :             (
    8438            2 :                 key,
    8439            2 :                 Lsn(0x60),
    8440            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8441            2 :             ),
    8442            2 :             (
    8443            2 :                 key,
    8444            2 :                 Lsn(0x70),
    8445            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8446            2 :             ),
    8447            2 :             (
    8448            2 :                 key,
    8449            2 :                 Lsn(0x80),
    8450            2 :                 Value::Image(Bytes::copy_from_slice(
    8451            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8452            2 :                 )),
    8453            2 :             ),
    8454            2 :             (
    8455            2 :                 key,
    8456            2 :                 Lsn(0x90),
    8457            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8458            2 :             ),
    8459            2 :         ];
    8460            2 :         let res = tline
    8461            2 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    8462            2 :             .await
    8463            2 :             .unwrap();
    8464            2 :         let expected_res = KeyHistoryRetention {
    8465            2 :             below_horizon: vec![
    8466            2 :                 (
    8467            2 :                     Lsn(0x40),
    8468            2 :                     KeyLogAtLsn(vec![(
    8469            2 :                         Lsn(0x40),
    8470            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8471            2 :                     )]),
    8472            2 :                 ),
    8473            2 :                 (
    8474            2 :                     Lsn(0x50),
    8475            2 :                     KeyLogAtLsn(vec![(
    8476            2 :                         Lsn(0x50),
    8477            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8478            2 :                     )]),
    8479            2 :                 ),
    8480            2 :                 (
    8481            2 :                     Lsn(0x60),
    8482            2 :                     KeyLogAtLsn(vec![(
    8483            2 :                         Lsn(0x60),
    8484            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8485            2 :                     )]),
    8486            2 :                 ),
    8487            2 :             ],
    8488            2 :             above_horizon: KeyLogAtLsn(vec![
    8489            2 :                 (
    8490            2 :                     Lsn(0x70),
    8491            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8492            2 :                 ),
    8493            2 :                 (
    8494            2 :                     Lsn(0x80),
    8495            2 :                     Value::Image(Bytes::copy_from_slice(
    8496            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8497            2 :                     )),
    8498            2 :                 ),
    8499            2 :                 (
    8500            2 :                     Lsn(0x90),
    8501            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8502            2 :                 ),
    8503            2 :             ]),
    8504            2 :         };
    8505            2 :         assert_eq!(res, expected_res);
    8506            2 : 
    8507            2 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    8508            2 :         // the ancestor image in the test case.
    8509            2 : 
    8510            2 :         let history = vec![
    8511            2 :             (
    8512            2 :                 key,
    8513            2 :                 Lsn(0x20),
    8514            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8515            2 :             ),
    8516            2 :             (
    8517            2 :                 key,
    8518            2 :                 Lsn(0x30),
    8519            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8520            2 :             ),
    8521            2 :             (
    8522            2 :                 key,
    8523            2 :                 Lsn(0x40),
    8524            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8525            2 :             ),
    8526            2 :             (
    8527            2 :                 key,
    8528            2 :                 Lsn(0x70),
    8529            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8530            2 :             ),
    8531            2 :         ];
    8532            2 :         let res = tline
    8533            2 :             .generate_key_retention(
    8534            2 :                 key,
    8535            2 :                 &history,
    8536            2 :                 Lsn(0x60),
    8537            2 :                 &[],
    8538            2 :                 3,
    8539            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    8540            2 :             )
    8541            2 :             .await
    8542            2 :             .unwrap();
    8543            2 :         let expected_res = KeyHistoryRetention {
    8544            2 :             below_horizon: vec![(
    8545            2 :                 Lsn(0x60),
    8546            2 :                 KeyLogAtLsn(vec![(
    8547            2 :                     Lsn(0x60),
    8548            2 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    8549            2 :                 )]),
    8550            2 :             )],
    8551            2 :             above_horizon: KeyLogAtLsn(vec![(
    8552            2 :                 Lsn(0x70),
    8553            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8554            2 :             )]),
    8555            2 :         };
    8556            2 :         assert_eq!(res, expected_res);
    8557            2 : 
    8558            2 :         let history = vec![
    8559            2 :             (
    8560            2 :                 key,
    8561            2 :                 Lsn(0x20),
    8562            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8563            2 :             ),
    8564            2 :             (
    8565            2 :                 key,
    8566            2 :                 Lsn(0x40),
    8567            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8568            2 :             ),
    8569            2 :             (
    8570            2 :                 key,
    8571            2 :                 Lsn(0x60),
    8572            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8573            2 :             ),
    8574            2 :             (
    8575            2 :                 key,
    8576            2 :                 Lsn(0x70),
    8577            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8578            2 :             ),
    8579            2 :         ];
    8580            2 :         let res = tline
    8581            2 :             .generate_key_retention(
    8582            2 :                 key,
    8583            2 :                 &history,
    8584            2 :                 Lsn(0x60),
    8585            2 :                 &[Lsn(0x30)],
    8586            2 :                 3,
    8587            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    8588            2 :             )
    8589            2 :             .await
    8590            2 :             .unwrap();
    8591            2 :         let expected_res = KeyHistoryRetention {
    8592            2 :             below_horizon: vec![
    8593            2 :                 (
    8594            2 :                     Lsn(0x30),
    8595            2 :                     KeyLogAtLsn(vec![(
    8596            2 :                         Lsn(0x20),
    8597            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8598            2 :                     )]),
    8599            2 :                 ),
    8600            2 :                 (
    8601            2 :                     Lsn(0x60),
    8602            2 :                     KeyLogAtLsn(vec![(
    8603            2 :                         Lsn(0x60),
    8604            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    8605            2 :                     )]),
    8606            2 :                 ),
    8607            2 :             ],
    8608            2 :             above_horizon: KeyLogAtLsn(vec![(
    8609            2 :                 Lsn(0x70),
    8610            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8611            2 :             )]),
    8612            2 :         };
    8613            2 :         assert_eq!(res, expected_res);
    8614            2 : 
    8615            2 :         Ok(())
    8616            2 :     }
    8617              : 
    8618              :     #[cfg(feature = "testing")]
    8619              :     #[tokio::test]
    8620            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    8621            2 :         let harness =
    8622            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    8623           19 :         let (tenant, ctx) = harness.load().await;
    8624            2 : 
    8625          518 :         fn get_key(id: u32) -> Key {
    8626          518 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8627          518 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8628          518 :             key.field6 = id;
    8629          518 :             key
    8630          518 :         }
    8631            2 : 
    8632            2 :         let img_layer = (0..10)
    8633           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8634            2 :             .collect_vec();
    8635            2 : 
    8636            2 :         let delta1 = vec![
    8637            2 :             (
    8638            2 :                 get_key(1),
    8639            2 :                 Lsn(0x20),
    8640            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8641            2 :             ),
    8642            2 :             (
    8643            2 :                 get_key(2),
    8644            2 :                 Lsn(0x30),
    8645            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8646            2 :             ),
    8647            2 :             (
    8648            2 :                 get_key(3),
    8649            2 :                 Lsn(0x28),
    8650            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8651            2 :             ),
    8652            2 :             (
    8653            2 :                 get_key(3),
    8654            2 :                 Lsn(0x30),
    8655            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8656            2 :             ),
    8657            2 :             (
    8658            2 :                 get_key(3),
    8659            2 :                 Lsn(0x40),
    8660            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8661            2 :             ),
    8662            2 :         ];
    8663            2 :         let delta2 = vec![
    8664            2 :             (
    8665            2 :                 get_key(5),
    8666            2 :                 Lsn(0x20),
    8667            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8668            2 :             ),
    8669            2 :             (
    8670            2 :                 get_key(6),
    8671            2 :                 Lsn(0x20),
    8672            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8673            2 :             ),
    8674            2 :         ];
    8675            2 :         let delta3 = vec![
    8676            2 :             (
    8677            2 :                 get_key(8),
    8678            2 :                 Lsn(0x48),
    8679            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8680            2 :             ),
    8681            2 :             (
    8682            2 :                 get_key(9),
    8683            2 :                 Lsn(0x48),
    8684            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8685            2 :             ),
    8686            2 :         ];
    8687            2 : 
    8688            2 :         let tline = tenant
    8689            2 :             .create_test_timeline_with_layers(
    8690            2 :                 TIMELINE_ID,
    8691            2 :                 Lsn(0x10),
    8692            2 :                 DEFAULT_PG_VERSION,
    8693            2 :                 &ctx,
    8694            2 :                 vec![
    8695            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    8696            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    8697            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8698            2 :                 ], // delta layers
    8699            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8700            2 :                 Lsn(0x50),
    8701            2 :             )
    8702           49 :             .await?;
    8703            2 :         {
    8704            2 :             // Update GC info
    8705            2 :             let mut guard = tline.gc_info.write().unwrap();
    8706            2 :             *guard = GcInfo {
    8707            2 :                 retain_lsns: vec![
    8708            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    8709            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    8710            2 :                 ],
    8711            2 :                 cutoffs: GcCutoffs {
    8712            2 :                     time: Lsn(0x30),
    8713            2 :                     space: Lsn(0x30),
    8714            2 :                 },
    8715            2 :                 leases: Default::default(),
    8716            2 :                 within_ancestor_pitr: false,
    8717            2 :             };
    8718            2 :         }
    8719            2 : 
    8720            2 :         let expected_result = [
    8721            2 :             Bytes::from_static(b"value 0@0x10"),
    8722            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8723            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8724            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8725            2 :             Bytes::from_static(b"value 4@0x10"),
    8726            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8727            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8728            2 :             Bytes::from_static(b"value 7@0x10"),
    8729            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8730            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8731            2 :         ];
    8732            2 : 
    8733            2 :         let expected_result_at_gc_horizon = [
    8734            2 :             Bytes::from_static(b"value 0@0x10"),
    8735            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8736            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8737            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8738            2 :             Bytes::from_static(b"value 4@0x10"),
    8739            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8740            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8741            2 :             Bytes::from_static(b"value 7@0x10"),
    8742            2 :             Bytes::from_static(b"value 8@0x10"),
    8743            2 :             Bytes::from_static(b"value 9@0x10"),
    8744            2 :         ];
    8745            2 : 
    8746            2 :         let expected_result_at_lsn_20 = [
    8747            2 :             Bytes::from_static(b"value 0@0x10"),
    8748            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8749            2 :             Bytes::from_static(b"value 2@0x10"),
    8750            2 :             Bytes::from_static(b"value 3@0x10"),
    8751            2 :             Bytes::from_static(b"value 4@0x10"),
    8752            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8753            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8754            2 :             Bytes::from_static(b"value 7@0x10"),
    8755            2 :             Bytes::from_static(b"value 8@0x10"),
    8756            2 :             Bytes::from_static(b"value 9@0x10"),
    8757            2 :         ];
    8758            2 : 
    8759            2 :         let expected_result_at_lsn_10 = [
    8760            2 :             Bytes::from_static(b"value 0@0x10"),
    8761            2 :             Bytes::from_static(b"value 1@0x10"),
    8762            2 :             Bytes::from_static(b"value 2@0x10"),
    8763            2 :             Bytes::from_static(b"value 3@0x10"),
    8764            2 :             Bytes::from_static(b"value 4@0x10"),
    8765            2 :             Bytes::from_static(b"value 5@0x10"),
    8766            2 :             Bytes::from_static(b"value 6@0x10"),
    8767            2 :             Bytes::from_static(b"value 7@0x10"),
    8768            2 :             Bytes::from_static(b"value 8@0x10"),
    8769            2 :             Bytes::from_static(b"value 9@0x10"),
    8770            2 :         ];
    8771            2 : 
    8772           12 :         let verify_result = || async {
    8773           12 :             let gc_horizon = {
    8774           12 :                 let gc_info = tline.gc_info.read().unwrap();
    8775           12 :                 gc_info.cutoffs.time
    8776            2 :             };
    8777          132 :             for idx in 0..10 {
    8778          120 :                 assert_eq!(
    8779          120 :                     tline
    8780          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8781          121 :                         .await
    8782          120 :                         .unwrap(),
    8783          120 :                     &expected_result[idx]
    8784            2 :                 );
    8785          120 :                 assert_eq!(
    8786          120 :                     tline
    8787          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    8788           93 :                         .await
    8789          120 :                         .unwrap(),
    8790          120 :                     &expected_result_at_gc_horizon[idx]
    8791            2 :                 );
    8792          120 :                 assert_eq!(
    8793          120 :                     tline
    8794          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    8795           86 :                         .await
    8796          120 :                         .unwrap(),
    8797          120 :                     &expected_result_at_lsn_20[idx]
    8798            2 :                 );
    8799          120 :                 assert_eq!(
    8800          120 :                     tline
    8801          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    8802           61 :                         .await
    8803          120 :                         .unwrap(),
    8804          120 :                     &expected_result_at_lsn_10[idx]
    8805            2 :                 );
    8806            2 :             }
    8807           24 :         };
    8808            2 : 
    8809           69 :         verify_result().await;
    8810            2 : 
    8811            2 :         let cancel = CancellationToken::new();
    8812            2 :         let mut dryrun_flags = EnumSet::new();
    8813            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    8814            2 : 
    8815            2 :         tline
    8816            2 :             .compact_with_gc(&cancel, dryrun_flags, &ctx)
    8817           45 :             .await
    8818            2 :             .unwrap();
    8819            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
    8820            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    8821           57 :         verify_result().await;
    8822            2 : 
    8823            2 :         tline
    8824            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8825           50 :             .await
    8826            2 :             .unwrap();
    8827           64 :         verify_result().await;
    8828            2 : 
    8829            2 :         // compact again
    8830            2 :         tline
    8831            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8832           40 :             .await
    8833            2 :             .unwrap();
    8834           57 :         verify_result().await;
    8835            2 : 
    8836            2 :         // increase GC horizon and compact again
    8837            2 :         {
    8838            2 :             // Update GC info
    8839            2 :             let mut guard = tline.gc_info.write().unwrap();
    8840            2 :             guard.cutoffs.time = Lsn(0x38);
    8841            2 :             guard.cutoffs.space = Lsn(0x38);
    8842            2 :         }
    8843            2 :         tline
    8844            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8845           39 :             .await
    8846            2 :             .unwrap();
    8847           57 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    8848            2 : 
    8849            2 :         // not increasing the GC horizon and compact again
    8850            2 :         tline
    8851            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    8852           40 :             .await
    8853            2 :             .unwrap();
    8854           57 :         verify_result().await;
    8855            2 : 
    8856            2 :         Ok(())
    8857            2 :     }
    8858              : 
    8859              :     #[cfg(feature = "testing")]
    8860              :     #[tokio::test]
    8861            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    8862            2 :     {
    8863            2 :         let harness =
    8864            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    8865            2 :                 .await?;
    8866           20 :         let (tenant, ctx) = harness.load().await;
    8867            2 : 
    8868          352 :         fn get_key(id: u32) -> Key {
    8869          352 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8870          352 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8871          352 :             key.field6 = id;
    8872          352 :             key
    8873          352 :         }
    8874            2 : 
    8875            2 :         let img_layer = (0..10)
    8876           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8877            2 :             .collect_vec();
    8878            2 : 
    8879            2 :         let delta1 = vec![
    8880            2 :             (
    8881            2 :                 get_key(1),
    8882            2 :                 Lsn(0x20),
    8883            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8884            2 :             ),
    8885            2 :             (
    8886            2 :                 get_key(1),
    8887            2 :                 Lsn(0x28),
    8888            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8889            2 :             ),
    8890            2 :         ];
    8891            2 :         let delta2 = vec![
    8892            2 :             (
    8893            2 :                 get_key(1),
    8894            2 :                 Lsn(0x30),
    8895            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8896            2 :             ),
    8897            2 :             (
    8898            2 :                 get_key(1),
    8899            2 :                 Lsn(0x38),
    8900            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    8901            2 :             ),
    8902            2 :         ];
    8903            2 :         let delta3 = vec![
    8904            2 :             (
    8905            2 :                 get_key(8),
    8906            2 :                 Lsn(0x48),
    8907            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8908            2 :             ),
    8909            2 :             (
    8910            2 :                 get_key(9),
    8911            2 :                 Lsn(0x48),
    8912            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8913            2 :             ),
    8914            2 :         ];
    8915            2 : 
    8916            2 :         let tline = tenant
    8917            2 :             .create_test_timeline_with_layers(
    8918            2 :                 TIMELINE_ID,
    8919            2 :                 Lsn(0x10),
    8920            2 :                 DEFAULT_PG_VERSION,
    8921            2 :                 &ctx,
    8922            2 :                 vec![
    8923            2 :                     // delta1 and delta 2 only contain a single key but multiple updates
    8924            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    8925            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    8926            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    8927            2 :                 ], // delta layers
    8928            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8929            2 :                 Lsn(0x50),
    8930            2 :             )
    8931           49 :             .await?;
    8932            2 :         {
    8933            2 :             // Update GC info
    8934            2 :             let mut guard = tline.gc_info.write().unwrap();
    8935            2 :             *guard = GcInfo {
    8936            2 :                 retain_lsns: vec![
    8937            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    8938            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    8939            2 :                 ],
    8940            2 :                 cutoffs: GcCutoffs {
    8941            2 :                     time: Lsn(0x30),
    8942            2 :                     space: Lsn(0x30),
    8943            2 :                 },
    8944            2 :                 leases: Default::default(),
    8945            2 :                 within_ancestor_pitr: false,
    8946            2 :             };
    8947            2 :         }
    8948            2 : 
    8949            2 :         let expected_result = [
    8950            2 :             Bytes::from_static(b"value 0@0x10"),
    8951            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    8952            2 :             Bytes::from_static(b"value 2@0x10"),
    8953            2 :             Bytes::from_static(b"value 3@0x10"),
    8954            2 :             Bytes::from_static(b"value 4@0x10"),
    8955            2 :             Bytes::from_static(b"value 5@0x10"),
    8956            2 :             Bytes::from_static(b"value 6@0x10"),
    8957            2 :             Bytes::from_static(b"value 7@0x10"),
    8958            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8959            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8960            2 :         ];
    8961            2 : 
    8962            2 :         let expected_result_at_gc_horizon = [
    8963            2 :             Bytes::from_static(b"value 0@0x10"),
    8964            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    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"),
    8972            2 :             Bytes::from_static(b"value 9@0x10"),
    8973            2 :         ];
    8974            2 : 
    8975            2 :         let expected_result_at_lsn_20 = [
    8976            2 :             Bytes::from_static(b"value 0@0x10"),
    8977            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    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_10 = [
    8989            2 :             Bytes::from_static(b"value 0@0x10"),
    8990            2 :             Bytes::from_static(b"value 1@0x10"),
    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            8 :         let verify_result = || async {
    9002            8 :             let gc_horizon = {
    9003            8 :                 let gc_info = tline.gc_info.read().unwrap();
    9004            8 :                 gc_info.cutoffs.time
    9005            2 :             };
    9006           88 :             for idx in 0..10 {
    9007           80 :                 assert_eq!(
    9008           80 :                     tline
    9009           80 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9010           76 :                         .await
    9011           80 :                         .unwrap(),
    9012           80 :                     &expected_result[idx]
    9013            2 :                 );
    9014           80 :                 assert_eq!(
    9015           80 :                     tline
    9016           80 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9017           46 :                         .await
    9018           80 :                         .unwrap(),
    9019           80 :                     &expected_result_at_gc_horizon[idx]
    9020            2 :                 );
    9021           80 :                 assert_eq!(
    9022           80 :                     tline
    9023           80 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9024           47 :                         .await
    9025           80 :                         .unwrap(),
    9026           80 :                     &expected_result_at_lsn_20[idx]
    9027            2 :                 );
    9028           80 :                 assert_eq!(
    9029           80 :                     tline
    9030           80 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9031           41 :                         .await
    9032           80 :                         .unwrap(),
    9033           80 :                     &expected_result_at_lsn_10[idx]
    9034            2 :                 );
    9035            2 :             }
    9036           16 :         };
    9037            2 : 
    9038           61 :         verify_result().await;
    9039            2 : 
    9040            2 :         let cancel = CancellationToken::new();
    9041            2 :         let mut dryrun_flags = EnumSet::new();
    9042            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9043            2 : 
    9044            2 :         tline
    9045            2 :             .compact_with_gc(&cancel, dryrun_flags, &ctx)
    9046           45 :             .await
    9047            2 :             .unwrap();
    9048            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
    9049            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9050           49 :         verify_result().await;
    9051            2 : 
    9052            2 :         tline
    9053            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    9054           51 :             .await
    9055            2 :             .unwrap();
    9056           53 :         verify_result().await;
    9057            2 : 
    9058            2 :         // compact again
    9059            2 :         tline
    9060            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    9061           40 :             .await
    9062            2 :             .unwrap();
    9063           47 :         verify_result().await;
    9064            2 : 
    9065            2 :         Ok(())
    9066            2 :     }
    9067              : 
    9068              :     #[cfg(feature = "testing")]
    9069              :     #[tokio::test]
    9070            2 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9071            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9072           20 :         let (tenant, ctx) = harness.load().await;
    9073            2 : 
    9074          126 :         fn get_key(id: u32) -> Key {
    9075          126 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9076          126 :             key.field6 = id;
    9077          126 :             key
    9078          126 :         }
    9079            2 : 
    9080            2 :         let img_layer = (0..10)
    9081           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9082            2 :             .collect_vec();
    9083            2 : 
    9084            2 :         let delta1 = vec![
    9085            2 :             (
    9086            2 :                 get_key(1),
    9087            2 :                 Lsn(0x20),
    9088            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9089            2 :             ),
    9090            2 :             (
    9091            2 :                 get_key(2),
    9092            2 :                 Lsn(0x30),
    9093            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9094            2 :             ),
    9095            2 :             (
    9096            2 :                 get_key(3),
    9097            2 :                 Lsn(0x28),
    9098            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9099            2 :             ),
    9100            2 :             (
    9101            2 :                 get_key(3),
    9102            2 :                 Lsn(0x30),
    9103            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9104            2 :             ),
    9105            2 :             (
    9106            2 :                 get_key(3),
    9107            2 :                 Lsn(0x40),
    9108            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9109            2 :             ),
    9110            2 :         ];
    9111            2 :         let delta2 = vec![
    9112            2 :             (
    9113            2 :                 get_key(5),
    9114            2 :                 Lsn(0x20),
    9115            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9116            2 :             ),
    9117            2 :             (
    9118            2 :                 get_key(6),
    9119            2 :                 Lsn(0x20),
    9120            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9121            2 :             ),
    9122            2 :         ];
    9123            2 :         let delta3 = vec![
    9124            2 :             (
    9125            2 :                 get_key(8),
    9126            2 :                 Lsn(0x48),
    9127            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9128            2 :             ),
    9129            2 :             (
    9130            2 :                 get_key(9),
    9131            2 :                 Lsn(0x48),
    9132            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9133            2 :             ),
    9134            2 :         ];
    9135            2 : 
    9136            2 :         let parent_tline = tenant
    9137            2 :             .create_test_timeline_with_layers(
    9138            2 :                 TIMELINE_ID,
    9139            2 :                 Lsn(0x10),
    9140            2 :                 DEFAULT_PG_VERSION,
    9141            2 :                 &ctx,
    9142            2 :                 vec![],                       // delta layers
    9143            2 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9144            2 :                 Lsn(0x18),
    9145            2 :             )
    9146           31 :             .await?;
    9147            2 : 
    9148            2 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9149            2 : 
    9150            2 :         let branch_tline = tenant
    9151            2 :             .branch_timeline_test_with_layers(
    9152            2 :                 &parent_tline,
    9153            2 :                 NEW_TIMELINE_ID,
    9154            2 :                 Some(Lsn(0x18)),
    9155            2 :                 &ctx,
    9156            2 :                 vec![
    9157            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9158            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9159            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9160            2 :                 ], // delta layers
    9161            2 :                 vec![], // image layers
    9162            2 :                 Lsn(0x50),
    9163            2 :             )
    9164           19 :             .await?;
    9165            2 : 
    9166            2 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9167            2 : 
    9168            2 :         {
    9169            2 :             // Update GC info
    9170            2 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9171            2 :             *guard = GcInfo {
    9172            2 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9173            2 :                 cutoffs: GcCutoffs {
    9174            2 :                     time: Lsn(0x10),
    9175            2 :                     space: Lsn(0x10),
    9176            2 :                 },
    9177            2 :                 leases: Default::default(),
    9178            2 :                 within_ancestor_pitr: false,
    9179            2 :             };
    9180            2 :         }
    9181            2 : 
    9182            2 :         {
    9183            2 :             // Update GC info
    9184            2 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9185            2 :             *guard = GcInfo {
    9186            2 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9187            2 :                 cutoffs: GcCutoffs {
    9188            2 :                     time: Lsn(0x50),
    9189            2 :                     space: Lsn(0x50),
    9190            2 :                 },
    9191            2 :                 leases: Default::default(),
    9192            2 :                 within_ancestor_pitr: false,
    9193            2 :             };
    9194            2 :         }
    9195            2 : 
    9196            2 :         let expected_result_at_gc_horizon = [
    9197            2 :             Bytes::from_static(b"value 0@0x10"),
    9198            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9199            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9200            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9201            2 :             Bytes::from_static(b"value 4@0x10"),
    9202            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9203            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9204            2 :             Bytes::from_static(b"value 7@0x10"),
    9205            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9206            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9207            2 :         ];
    9208            2 : 
    9209            2 :         let expected_result_at_lsn_40 = [
    9210            2 :             Bytes::from_static(b"value 0@0x10"),
    9211            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9212            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9213            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9214            2 :             Bytes::from_static(b"value 4@0x10"),
    9215            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9216            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9217            2 :             Bytes::from_static(b"value 7@0x10"),
    9218            2 :             Bytes::from_static(b"value 8@0x10"),
    9219            2 :             Bytes::from_static(b"value 9@0x10"),
    9220            2 :         ];
    9221            2 : 
    9222            4 :         let verify_result = || async {
    9223           44 :             for idx in 0..10 {
    9224           40 :                 assert_eq!(
    9225           40 :                     branch_tline
    9226           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9227           52 :                         .await
    9228           40 :                         .unwrap(),
    9229           40 :                     &expected_result_at_gc_horizon[idx]
    9230            2 :                 );
    9231           40 :                 assert_eq!(
    9232           40 :                     branch_tline
    9233           40 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9234           31 :                         .await
    9235           40 :                         .unwrap(),
    9236           40 :                     &expected_result_at_lsn_40[idx]
    9237            2 :                 );
    9238            2 :             }
    9239            8 :         };
    9240            2 : 
    9241           46 :         verify_result().await;
    9242            2 : 
    9243            2 :         let cancel = CancellationToken::new();
    9244            2 :         branch_tline
    9245            2 :             .compact_with_gc(&cancel, EnumSet::new(), &ctx)
    9246           19 :             .await
    9247            2 :             .unwrap();
    9248            2 : 
    9249           37 :         verify_result().await;
    9250            2 : 
    9251            2 :         Ok(())
    9252            2 :     }
    9253              : 
    9254              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9255              :     // Create an image arrangement where we have to read at different LSN ranges
    9256              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9257              :     // a delta layer. Like so:
    9258              :     //
    9259              :     //     A      B
    9260              :     // +----------------+ -> delta_layer
    9261              :     // |                |                           ^ lsn
    9262              :     // |       =========|-> nested_image_layer      |
    9263              :     // |       C        |                           |
    9264              :     // +----------------+                           |
    9265              :     // ======== -> baseline_image_layer             +-------> key
    9266              :     //
    9267              :     //
    9268              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9269              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9270              :     #[cfg(feature = "testing")]
    9271              :     #[tokio::test]
    9272            2 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9273            2 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9274           20 :         let (tenant, ctx) = harness.load().await;
    9275            2 : 
    9276            2 :         let will_init_keys = [2, 6];
    9277           44 :         fn get_key(id: u32) -> Key {
    9278           44 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9279           44 :             key.field6 = id;
    9280           44 :             key
    9281           44 :         }
    9282            2 : 
    9283            2 :         let mut expected_key_values = HashMap::new();
    9284            2 : 
    9285            2 :         let baseline_image_layer_lsn = Lsn(0x10);
    9286            2 :         let mut baseline_img_layer = Vec::new();
    9287           12 :         for i in 0..5 {
    9288           10 :             let key = get_key(i);
    9289           10 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
    9290           10 : 
    9291           10 :             let removed = expected_key_values.insert(key, value.clone());
    9292           10 :             assert!(removed.is_none());
    9293            2 : 
    9294           10 :             baseline_img_layer.push((key, Bytes::from(value)));
    9295            2 :         }
    9296            2 : 
    9297            2 :         let nested_image_layer_lsn = Lsn(0x50);
    9298            2 :         let mut nested_img_layer = Vec::new();
    9299           12 :         for i in 5..10 {
    9300           10 :             let key = get_key(i);
    9301           10 :             let value = format!("value {i}@{nested_image_layer_lsn}");
    9302           10 : 
    9303           10 :             let removed = expected_key_values.insert(key, value.clone());
    9304           10 :             assert!(removed.is_none());
    9305            2 : 
    9306           10 :             nested_img_layer.push((key, Bytes::from(value)));
    9307            2 :         }
    9308            2 : 
    9309            2 :         let mut delta_layer_spec = Vec::default();
    9310            2 :         let delta_layer_start_lsn = Lsn(0x20);
    9311            2 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
    9312            2 : 
    9313           22 :         for i in 0..10 {
    9314           20 :             let key = get_key(i);
    9315           20 :             let key_in_nested = nested_img_layer
    9316           20 :                 .iter()
    9317           80 :                 .any(|(key_with_img, _)| *key_with_img == key);
    9318           20 :             let lsn = {
    9319           20 :                 if key_in_nested {
    9320           10 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
    9321            2 :                 } else {
    9322           10 :                     delta_layer_start_lsn
    9323            2 :                 }
    9324            2 :             };
    9325            2 : 
    9326           20 :             let will_init = will_init_keys.contains(&i);
    9327           20 :             if will_init {
    9328            4 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
    9329            4 : 
    9330            4 :                 expected_key_values.insert(key, "".to_string());
    9331           16 :             } else {
    9332           16 :                 let delta = format!("@{lsn}");
    9333           16 :                 delta_layer_spec.push((
    9334           16 :                     key,
    9335           16 :                     lsn,
    9336           16 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
    9337           16 :                 ));
    9338           16 : 
    9339           16 :                 expected_key_values
    9340           16 :                     .get_mut(&key)
    9341           16 :                     .expect("An image exists for each key")
    9342           16 :                     .push_str(delta.as_str());
    9343           16 :             }
    9344           20 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
    9345            2 :         }
    9346            2 : 
    9347            2 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
    9348            2 : 
    9349            2 :         assert!(
    9350            2 :             nested_image_layer_lsn > delta_layer_start_lsn
    9351            2 :                 && nested_image_layer_lsn < delta_layer_end_lsn
    9352            2 :         );
    9353            2 : 
    9354            2 :         let tline = tenant
    9355            2 :             .create_test_timeline_with_layers(
    9356            2 :                 TIMELINE_ID,
    9357            2 :                 baseline_image_layer_lsn,
    9358            2 :                 DEFAULT_PG_VERSION,
    9359            2 :                 &ctx,
    9360            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9361            2 :                     delta_layer_start_lsn..delta_layer_end_lsn,
    9362            2 :                     delta_layer_spec,
    9363            2 :                 )], // delta layers
    9364            2 :                 vec![
    9365            2 :                     (baseline_image_layer_lsn, baseline_img_layer),
    9366            2 :                     (nested_image_layer_lsn, nested_img_layer),
    9367            2 :                 ], // image layers
    9368            2 :                 delta_layer_end_lsn,
    9369            2 :             )
    9370           42 :             .await?;
    9371            2 : 
    9372            2 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
    9373            2 :         let results = tline
    9374            2 :             .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
    9375           13 :             .await
    9376            2 :             .expect("No vectored errors");
    9377           22 :         for (key, res) in results {
    9378           20 :             let value = res.expect("No key errors");
    9379           20 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
    9380           20 :             assert_eq!(value, Bytes::from(expected_value));
    9381            2 :         }
    9382            2 : 
    9383            2 :         Ok(())
    9384            2 :     }
    9385              : 
    9386          142 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
    9387          142 :         (
    9388          142 :             k1.is_delta,
    9389          142 :             k1.key_range.start,
    9390          142 :             k1.key_range.end,
    9391          142 :             k1.lsn_range.start,
    9392          142 :             k1.lsn_range.end,
    9393          142 :         )
    9394          142 :             .cmp(&(
    9395          142 :                 k2.is_delta,
    9396          142 :                 k2.key_range.start,
    9397          142 :                 k2.key_range.end,
    9398          142 :                 k2.lsn_range.start,
    9399          142 :                 k2.lsn_range.end,
    9400          142 :             ))
    9401          142 :     }
    9402              : 
    9403           12 :     async fn inspect_and_sort(
    9404           12 :         tline: &Arc<Timeline>,
    9405           12 :         filter: Option<std::ops::Range<Key>>,
    9406           12 :     ) -> Vec<PersistentLayerKey> {
    9407           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
    9408           12 :         if let Some(filter) = filter {
    9409           64 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
    9410           10 :         }
    9411           12 :         all_layers.sort_by(sort_layer_key);
    9412           12 :         all_layers
    9413           12 :     }
    9414              : 
    9415              :     #[cfg(feature = "testing")]
    9416           10 :     fn check_layer_map_key_eq(
    9417           10 :         mut left: Vec<PersistentLayerKey>,
    9418           10 :         mut right: Vec<PersistentLayerKey>,
    9419           10 :     ) {
    9420           10 :         left.sort_by(sort_layer_key);
    9421           10 :         right.sort_by(sort_layer_key);
    9422           10 :         if left != right {
    9423            0 :             eprintln!("---LEFT---");
    9424            0 :             for left in left.iter() {
    9425            0 :                 eprintln!("{}", left);
    9426            0 :             }
    9427            0 :             eprintln!("---RIGHT---");
    9428            0 :             for right in right.iter() {
    9429            0 :                 eprintln!("{}", right);
    9430            0 :             }
    9431            0 :             assert_eq!(left, right);
    9432           10 :         }
    9433           10 :     }
    9434              : 
    9435              :     #[cfg(feature = "testing")]
    9436              :     #[tokio::test]
    9437            2 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
    9438            2 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
    9439           20 :         let (tenant, ctx) = harness.load().await;
    9440            2 : 
    9441          182 :         fn get_key(id: u32) -> Key {
    9442          182 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9443          182 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9444          182 :             key.field6 = id;
    9445          182 :             key
    9446          182 :         }
    9447            2 : 
    9448            2 :         // img layer at 0x10
    9449            2 :         let img_layer = (0..10)
    9450           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9451            2 :             .collect_vec();
    9452            2 : 
    9453            2 :         let delta1 = vec![
    9454            2 :             (
    9455            2 :                 get_key(1),
    9456            2 :                 Lsn(0x20),
    9457            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    9458            2 :             ),
    9459            2 :             (
    9460            2 :                 get_key(2),
    9461            2 :                 Lsn(0x30),
    9462            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    9463            2 :             ),
    9464            2 :             (
    9465            2 :                 get_key(3),
    9466            2 :                 Lsn(0x40),
    9467            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    9468            2 :             ),
    9469            2 :         ];
    9470            2 :         let delta2 = vec![
    9471            2 :             (
    9472            2 :                 get_key(5),
    9473            2 :                 Lsn(0x20),
    9474            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    9475            2 :             ),
    9476            2 :             (
    9477            2 :                 get_key(6),
    9478            2 :                 Lsn(0x20),
    9479            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    9480            2 :             ),
    9481            2 :         ];
    9482            2 :         let delta3 = vec![
    9483            2 :             (
    9484            2 :                 get_key(8),
    9485            2 :                 Lsn(0x48),
    9486            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    9487            2 :             ),
    9488            2 :             (
    9489            2 :                 get_key(9),
    9490            2 :                 Lsn(0x48),
    9491            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    9492            2 :             ),
    9493            2 :         ];
    9494            2 : 
    9495            2 :         let tline = tenant
    9496            2 :             .create_test_timeline_with_layers(
    9497            2 :                 TIMELINE_ID,
    9498            2 :                 Lsn(0x10),
    9499            2 :                 DEFAULT_PG_VERSION,
    9500            2 :                 &ctx,
    9501            2 :                 vec![
    9502            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9503            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9504            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9505            2 :                 ], // delta layers
    9506            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9507            2 :                 Lsn(0x50),
    9508            2 :             )
    9509           49 :             .await?;
    9510            2 : 
    9511            2 :         {
    9512            2 :             // Update GC info
    9513            2 :             let mut guard = tline.gc_info.write().unwrap();
    9514            2 :             *guard = GcInfo {
    9515            2 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
    9516            2 :                 cutoffs: GcCutoffs {
    9517            2 :                     time: Lsn(0x30),
    9518            2 :                     space: Lsn(0x30),
    9519            2 :                 },
    9520            2 :                 leases: Default::default(),
    9521            2 :                 within_ancestor_pitr: false,
    9522            2 :             };
    9523            2 :         }
    9524            2 : 
    9525            2 :         let cancel = CancellationToken::new();
    9526            2 : 
    9527            2 :         // Do a partial compaction on key range 0..2
    9528            2 :         tline
    9529            2 :             .partial_compact_with_gc(get_key(0)..get_key(2), &cancel, EnumSet::new(), &ctx)
    9530           27 :             .await
    9531            2 :             .unwrap();
    9532            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9533            2 :         check_layer_map_key_eq(
    9534            2 :             all_layers,
    9535            2 :             vec![
    9536            2 :                 // newly-generated image layer for the partial compaction range 0-2
    9537            2 :                 PersistentLayerKey {
    9538            2 :                     key_range: get_key(0)..get_key(2),
    9539            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9540            2 :                     is_delta: false,
    9541            2 :                 },
    9542            2 :                 PersistentLayerKey {
    9543            2 :                     key_range: get_key(0)..get_key(10),
    9544            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9545            2 :                     is_delta: false,
    9546            2 :                 },
    9547            2 :                 // delta1 is split and the second part is rewritten
    9548            2 :                 PersistentLayerKey {
    9549            2 :                     key_range: get_key(2)..get_key(4),
    9550            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9551            2 :                     is_delta: true,
    9552            2 :                 },
    9553            2 :                 PersistentLayerKey {
    9554            2 :                     key_range: get_key(5)..get_key(7),
    9555            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9556            2 :                     is_delta: true,
    9557            2 :                 },
    9558            2 :                 PersistentLayerKey {
    9559            2 :                     key_range: get_key(8)..get_key(10),
    9560            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9561            2 :                     is_delta: true,
    9562            2 :                 },
    9563            2 :             ],
    9564            2 :         );
    9565            2 : 
    9566            2 :         // Do a partial compaction on key range 2..4
    9567            2 :         tline
    9568            2 :             .partial_compact_with_gc(get_key(2)..get_key(4), &cancel, EnumSet::new(), &ctx)
    9569           19 :             .await
    9570            2 :             .unwrap();
    9571            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9572            2 :         check_layer_map_key_eq(
    9573            2 :             all_layers,
    9574            2 :             vec![
    9575            2 :                 PersistentLayerKey {
    9576            2 :                     key_range: get_key(0)..get_key(2),
    9577            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9578            2 :                     is_delta: false,
    9579            2 :                 },
    9580            2 :                 PersistentLayerKey {
    9581            2 :                     key_range: get_key(0)..get_key(10),
    9582            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9583            2 :                     is_delta: false,
    9584            2 :                 },
    9585            2 :                 // image layer generated for the compaction range 2-4
    9586            2 :                 PersistentLayerKey {
    9587            2 :                     key_range: get_key(2)..get_key(4),
    9588            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9589            2 :                     is_delta: false,
    9590            2 :                 },
    9591            2 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
    9592            2 :                 PersistentLayerKey {
    9593            2 :                     key_range: get_key(2)..get_key(4),
    9594            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9595            2 :                     is_delta: true,
    9596            2 :                 },
    9597            2 :                 PersistentLayerKey {
    9598            2 :                     key_range: get_key(5)..get_key(7),
    9599            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9600            2 :                     is_delta: true,
    9601            2 :                 },
    9602            2 :                 PersistentLayerKey {
    9603            2 :                     key_range: get_key(8)..get_key(10),
    9604            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9605            2 :                     is_delta: true,
    9606            2 :                 },
    9607            2 :             ],
    9608            2 :         );
    9609            2 : 
    9610            2 :         // Do a partial compaction on key range 4..9
    9611            2 :         tline
    9612            2 :             .partial_compact_with_gc(get_key(4)..get_key(9), &cancel, EnumSet::new(), &ctx)
    9613           24 :             .await
    9614            2 :             .unwrap();
    9615            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9616            2 :         check_layer_map_key_eq(
    9617            2 :             all_layers,
    9618            2 :             vec![
    9619            2 :                 PersistentLayerKey {
    9620            2 :                     key_range: get_key(0)..get_key(2),
    9621            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9622            2 :                     is_delta: false,
    9623            2 :                 },
    9624            2 :                 PersistentLayerKey {
    9625            2 :                     key_range: get_key(0)..get_key(10),
    9626            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9627            2 :                     is_delta: false,
    9628            2 :                 },
    9629            2 :                 PersistentLayerKey {
    9630            2 :                     key_range: get_key(2)..get_key(4),
    9631            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9632            2 :                     is_delta: false,
    9633            2 :                 },
    9634            2 :                 PersistentLayerKey {
    9635            2 :                     key_range: get_key(2)..get_key(4),
    9636            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9637            2 :                     is_delta: true,
    9638            2 :                 },
    9639            2 :                 // image layer generated for this compaction range
    9640            2 :                 PersistentLayerKey {
    9641            2 :                     key_range: get_key(4)..get_key(9),
    9642            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9643            2 :                     is_delta: false,
    9644            2 :                 },
    9645            2 :                 PersistentLayerKey {
    9646            2 :                     key_range: get_key(8)..get_key(10),
    9647            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9648            2 :                     is_delta: true,
    9649            2 :                 },
    9650            2 :             ],
    9651            2 :         );
    9652            2 : 
    9653            2 :         // Do a partial compaction on key range 9..10
    9654            2 :         tline
    9655            2 :             .partial_compact_with_gc(get_key(9)..get_key(10), &cancel, EnumSet::new(), &ctx)
    9656           10 :             .await
    9657            2 :             .unwrap();
    9658            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9659            2 :         check_layer_map_key_eq(
    9660            2 :             all_layers,
    9661            2 :             vec![
    9662            2 :                 PersistentLayerKey {
    9663            2 :                     key_range: get_key(0)..get_key(2),
    9664            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9665            2 :                     is_delta: false,
    9666            2 :                 },
    9667            2 :                 PersistentLayerKey {
    9668            2 :                     key_range: get_key(0)..get_key(10),
    9669            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
    9670            2 :                     is_delta: false,
    9671            2 :                 },
    9672            2 :                 PersistentLayerKey {
    9673            2 :                     key_range: get_key(2)..get_key(4),
    9674            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9675            2 :                     is_delta: false,
    9676            2 :                 },
    9677            2 :                 PersistentLayerKey {
    9678            2 :                     key_range: get_key(2)..get_key(4),
    9679            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9680            2 :                     is_delta: true,
    9681            2 :                 },
    9682            2 :                 PersistentLayerKey {
    9683            2 :                     key_range: get_key(4)..get_key(9),
    9684            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9685            2 :                     is_delta: false,
    9686            2 :                 },
    9687            2 :                 // image layer generated for the compaction range
    9688            2 :                 PersistentLayerKey {
    9689            2 :                     key_range: get_key(9)..get_key(10),
    9690            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9691            2 :                     is_delta: false,
    9692            2 :                 },
    9693            2 :                 PersistentLayerKey {
    9694            2 :                     key_range: get_key(8)..get_key(10),
    9695            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9696            2 :                     is_delta: true,
    9697            2 :                 },
    9698            2 :             ],
    9699            2 :         );
    9700            2 : 
    9701            2 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
    9702            2 :         tline
    9703            2 :             .partial_compact_with_gc(get_key(0)..get_key(10), &cancel, EnumSet::new(), &ctx)
    9704           54 :             .await
    9705            2 :             .unwrap();
    9706            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
    9707            2 :         check_layer_map_key_eq(
    9708            2 :             all_layers,
    9709            2 :             vec![
    9710            2 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
    9711            2 :                 PersistentLayerKey {
    9712            2 :                     key_range: get_key(0)..get_key(10),
    9713            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
    9714            2 :                     is_delta: false,
    9715            2 :                 },
    9716            2 :                 PersistentLayerKey {
    9717            2 :                     key_range: get_key(2)..get_key(4),
    9718            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
    9719            2 :                     is_delta: true,
    9720            2 :                 },
    9721            2 :                 PersistentLayerKey {
    9722            2 :                     key_range: get_key(8)..get_key(10),
    9723            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9724            2 :                     is_delta: true,
    9725            2 :                 },
    9726            2 :             ],
    9727            2 :         );
    9728            2 : 
    9729            2 :         Ok(())
    9730            2 :     }
    9731              : 
    9732              :     #[cfg(feature = "testing")]
    9733              :     #[tokio::test]
    9734            2 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
    9735            2 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
    9736            2 :             .await
    9737            2 :             .unwrap();
    9738           19 :         let (tenant, ctx) = harness.load().await;
    9739            2 :         let tline_parent = tenant
    9740            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9741            6 :             .await
    9742            2 :             .unwrap();
    9743            2 :         let tline_child = tenant
    9744            2 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
    9745            2 :             .await
    9746            2 :             .unwrap();
    9747            2 :         {
    9748            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
    9749            2 :             assert_eq!(
    9750            2 :                 gc_info_parent.retain_lsns,
    9751            2 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
    9752            2 :             );
    9753            2 :         }
    9754            2 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
    9755            2 :         tline_child
    9756            2 :             .remote_client
    9757            2 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
    9758            2 :             .unwrap();
    9759            2 :         tline_child.remote_client.wait_completion().await.unwrap();
    9760            2 :         offload_timeline(&tenant, &tline_child)
    9761            2 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
    9762           14 :             .await.unwrap();
    9763            2 :         let child_timeline_id = tline_child.timeline_id;
    9764            2 :         Arc::try_unwrap(tline_child).unwrap();
    9765            2 : 
    9766            2 :         {
    9767            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
    9768            2 :             assert_eq!(
    9769            2 :                 gc_info_parent.retain_lsns,
    9770            2 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
    9771            2 :             );
    9772            2 :         }
    9773            2 : 
    9774            2 :         tenant
    9775            2 :             .get_offloaded_timeline(child_timeline_id)
    9776            2 :             .unwrap()
    9777            2 :             .defuse_for_tenant_drop();
    9778            2 : 
    9779            2 :         Ok(())
    9780            2 :     }
    9781              : }
        

Generated by: LCOV version 2.1-beta