LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: bb45db3982713bfd5bec075773079136e362195e.info Lines: 74.1 % 7701 5707
Test Date: 2024-12-11 15:53:32 Functions: 59.6 % 421 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::collections::VecDeque;
      41              : use std::fmt;
      42              : use std::future::Future;
      43              : use std::sync::atomic::AtomicBool;
      44              : use std::sync::Weak;
      45              : use std::time::SystemTime;
      46              : use storage_broker::BrokerClientChannel;
      47              : use timeline::compaction::ScheduledCompactionTask;
      48              : use timeline::import_pgdata;
      49              : use timeline::offload::offload_timeline;
      50              : use timeline::CompactFlags;
      51              : use timeline::CompactOptions;
      52              : use timeline::CompactionError;
      53              : use timeline::ShutdownMode;
      54              : use tokio::io::BufReader;
      55              : use tokio::sync::watch;
      56              : use tokio::task::JoinSet;
      57              : use tokio_util::sync::CancellationToken;
      58              : use tracing::*;
      59              : use upload_queue::NotInitialized;
      60              : use utils::backoff;
      61              : use utils::circuit_breaker::CircuitBreaker;
      62              : use utils::completion;
      63              : use utils::crashsafe::path_with_suffix_extension;
      64              : use utils::failpoint_support;
      65              : use utils::fs_ext;
      66              : use utils::pausable_failpoint;
      67              : use utils::sync::gate::Gate;
      68              : use utils::sync::gate::GateGuard;
      69              : use utils::timeout::timeout_cancellable;
      70              : use utils::timeout::TimeoutCancellableError;
      71              : use utils::zstd::create_zst_tarball;
      72              : use utils::zstd::extract_zst_tarball;
      73              : 
      74              : use self::config::AttachedLocationConfig;
      75              : use self::config::AttachmentMode;
      76              : use self::config::LocationConf;
      77              : use self::config::TenantConf;
      78              : use self::metadata::TimelineMetadata;
      79              : use self::mgr::GetActiveTenantError;
      80              : use self::mgr::GetTenantError;
      81              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      82              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      83              : use self::timeline::uninit::TimelineCreateGuard;
      84              : use self::timeline::uninit::TimelineExclusionError;
      85              : use self::timeline::uninit::UninitializedTimeline;
      86              : use self::timeline::EvictionTaskTenantState;
      87              : use self::timeline::GcCutoffs;
      88              : use self::timeline::TimelineDeleteProgress;
      89              : use self::timeline::TimelineResources;
      90              : use self::timeline::WaitLsnError;
      91              : use crate::config::PageServerConf;
      92              : use crate::context::{DownloadBehavior, RequestContext};
      93              : use crate::deletion_queue::DeletionQueueClient;
      94              : use crate::deletion_queue::DeletionQueueError;
      95              : use crate::import_datadir;
      96              : use crate::is_uninit_mark;
      97              : use crate::l0_flush::L0FlushGlobalState;
      98              : use crate::metrics::TENANT;
      99              : use crate::metrics::{
     100              :     remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
     101              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
     102              : };
     103              : use crate::task_mgr;
     104              : use crate::task_mgr::TaskKind;
     105              : use crate::tenant::config::LocationMode;
     106              : use crate::tenant::config::TenantConfOpt;
     107              : use crate::tenant::gc_result::GcResult;
     108              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     109              : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
     110              : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
     111              : use crate::tenant::remote_timeline_client::INITDB_PATH;
     112              : use crate::tenant::storage_layer::DeltaLayer;
     113              : use crate::tenant::storage_layer::ImageLayer;
     114              : use crate::walingest::WalLagCooldown;
     115              : use crate::walredo;
     116              : use crate::InitializationOrder;
     117              : use std::collections::hash_map::Entry;
     118              : use std::collections::HashMap;
     119              : use std::collections::HashSet;
     120              : use std::fmt::Debug;
     121              : use std::fmt::Display;
     122              : use std::fs;
     123              : use std::fs::File;
     124              : use std::sync::atomic::{AtomicU64, Ordering};
     125              : use std::sync::Arc;
     126              : use std::sync::Mutex;
     127              : use std::time::{Duration, Instant};
     128              : 
     129              : use crate::span;
     130              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     131              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     132              : use crate::virtual_file::VirtualFile;
     133              : use crate::walredo::PostgresRedoManager;
     134              : use crate::TEMP_FILE_SUFFIX;
     135              : use once_cell::sync::Lazy;
     136              : pub use pageserver_api::models::TenantState;
     137              : use tokio::sync::Semaphore;
     138              : 
     139            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     140              : use utils::{
     141              :     crashsafe,
     142              :     generation::Generation,
     143              :     id::TimelineId,
     144              :     lsn::{Lsn, RecordLsn},
     145              : };
     146              : 
     147              : pub mod blob_io;
     148              : pub mod block_io;
     149              : pub mod vectored_blob_io;
     150              : 
     151              : pub mod disk_btree;
     152              : pub(crate) mod ephemeral_file;
     153              : pub mod layer_map;
     154              : 
     155              : pub mod metadata;
     156              : pub mod remote_timeline_client;
     157              : pub mod storage_layer;
     158              : 
     159              : pub mod checks;
     160              : pub mod config;
     161              : pub mod mgr;
     162              : pub mod secondary;
     163              : pub mod tasks;
     164              : pub mod upload_queue;
     165              : 
     166              : pub(crate) mod timeline;
     167              : 
     168              : pub mod size;
     169              : 
     170              : mod gc_block;
     171              : mod gc_result;
     172              : pub(crate) mod throttle;
     173              : 
     174              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     175              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     176              : 
     177              : // re-export for use in walreceiver
     178              : pub use crate::tenant::timeline::WalReceiverInfo;
     179              : 
     180              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     181              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     182              : 
     183              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     184              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     185              : 
     186              : /// References to shared objects that are passed into each tenant, such
     187              : /// as the shared remote storage client and process initialization state.
     188              : #[derive(Clone)]
     189              : pub struct TenantSharedResources {
     190              :     pub broker_client: storage_broker::BrokerClientChannel,
     191              :     pub remote_storage: GenericRemoteStorage,
     192              :     pub deletion_queue_client: DeletionQueueClient,
     193              :     pub l0_flush_global_state: L0FlushGlobalState,
     194              : }
     195              : 
     196              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     197              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     198              : /// in this struct.
     199              : #[derive(Clone)]
     200              : pub(super) struct AttachedTenantConf {
     201              :     tenant_conf: TenantConfOpt,
     202              :     location: AttachedLocationConfig,
     203              :     /// The deadline before which we are blocked from GC so that
     204              :     /// leases have a chance to be renewed.
     205              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     206              : }
     207              : 
     208              : impl AttachedTenantConf {
     209          192 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     210              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     211              :         //
     212              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     213              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     214              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     215          192 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     216          192 :             Some(
     217          192 :                 tokio::time::Instant::now()
     218          192 :                     + tenant_conf
     219          192 :                         .lsn_lease_length
     220          192 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     221          192 :             )
     222              :         } else {
     223              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     224              :             // because we don't do GC in these modes.
     225            0 :             None
     226              :         };
     227              : 
     228          192 :         Self {
     229          192 :             tenant_conf,
     230          192 :             location,
     231          192 :             lsn_lease_deadline,
     232          192 :         }
     233          192 :     }
     234              : 
     235          192 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     236          192 :         match &location_conf.mode {
     237          192 :             LocationMode::Attached(attach_conf) => {
     238          192 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     239              :             }
     240              :             LocationMode::Secondary(_) => {
     241            0 :                 anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
     242              :             }
     243              :         }
     244          192 :     }
     245              : 
     246          762 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     247          762 :         self.lsn_lease_deadline
     248          762 :             .map(|d| tokio::time::Instant::now() < d)
     249          762 :             .unwrap_or(false)
     250          762 :     }
     251              : }
     252              : struct TimelinePreload {
     253              :     timeline_id: TimelineId,
     254              :     client: RemoteTimelineClient,
     255              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     256              : }
     257              : 
     258              : pub(crate) struct TenantPreload {
     259              :     tenant_manifest: TenantManifest,
     260              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     261              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     262              : }
     263              : 
     264              : /// When we spawn a tenant, there is a special mode for tenant creation that
     265              : /// avoids trying to read anything from remote storage.
     266              : pub(crate) enum SpawnMode {
     267              :     /// Activate as soon as possible
     268              :     Eager,
     269              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     270              :     Lazy,
     271              : }
     272              : 
     273              : ///
     274              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     275              : ///
     276              : pub struct Tenant {
     277              :     // Global pageserver config parameters
     278              :     pub conf: &'static PageServerConf,
     279              : 
     280              :     /// The value creation timestamp, used to measure activation delay, see:
     281              :     /// <https://github.com/neondatabase/neon/issues/4025>
     282              :     constructed_at: Instant,
     283              : 
     284              :     state: watch::Sender<TenantState>,
     285              : 
     286              :     // Overridden tenant-specific config parameters.
     287              :     // We keep TenantConfOpt sturct here to preserve the information
     288              :     // about parameters that are not set.
     289              :     // This is necessary to allow global config updates.
     290              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     291              : 
     292              :     tenant_shard_id: TenantShardId,
     293              : 
     294              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     295              :     shard_identity: ShardIdentity,
     296              : 
     297              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     298              :     /// Does not change over the lifetime of the [`Tenant`] object.
     299              :     ///
     300              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     301              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     302              :     generation: Generation,
     303              : 
     304              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     305              : 
     306              :     /// During timeline creation, we first insert the TimelineId to the
     307              :     /// creating map, then `timelines`, then remove it from the creating map.
     308              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     309              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     310              : 
     311              :     /// Possibly offloaded and archived timelines
     312              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     313              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     314              : 
     315              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     316              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     317              :     /// each other (this could be optimized to coalesce writes if necessary).
     318              :     ///
     319              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     320              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     321              : 
     322              :     // This mutex prevents creation of new timelines during GC.
     323              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     324              :     // `timelines` mutex during all GC iteration
     325              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     326              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     327              :     // timeout...
     328              :     gc_cs: tokio::sync::Mutex<()>,
     329              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     330              : 
     331              :     // provides access to timeline data sitting in the remote storage
     332              :     pub(crate) remote_storage: GenericRemoteStorage,
     333              : 
     334              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     335              :     deletion_queue_client: DeletionQueueClient,
     336              : 
     337              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     338              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     339              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     340              : 
     341              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     342              : 
     343              :     /// Track repeated failures to compact, so that we can back off.
     344              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     345              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     346              : 
     347              :     /// Scheduled compaction tasks. Currently, this can only be populated by triggering
     348              :     /// a manual gc-compaction from the manual compaction API.
     349              :     scheduled_compaction_tasks:
     350              :         std::sync::Mutex<HashMap<TimelineId, VecDeque<ScheduledCompactionTask>>>,
     351              : 
     352              :     /// If the tenant is in Activating state, notify this to encourage it
     353              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     354              :     /// background warmup.
     355              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     356              : 
     357              :     /// Time it took for the tenant to activate. Zero if not active yet.
     358              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     359              : 
     360              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     361              :     // Timelines' cancellation token.
     362              :     pub(crate) cancel: CancellationToken,
     363              : 
     364              :     // Users of the Tenant such as the page service must take this Gate to avoid
     365              :     // trying to use a Tenant which is shutting down.
     366              :     pub(crate) gate: Gate,
     367              : 
     368              :     /// Throttle applied at the top of [`Timeline::get`].
     369              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     370              :     pub(crate) pagestream_throttle:
     371              :         Arc<throttle::Throttle<crate::metrics::tenant_throttling::Pagestream>>,
     372              : 
     373              :     /// An ongoing timeline detach concurrency limiter.
     374              :     ///
     375              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     376              :     /// to have two running at the same time. A different one can be started if an earlier one
     377              :     /// has failed for whatever reason.
     378              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     379              : 
     380              :     /// `index_part.json` based gc blocking reason tracking.
     381              :     ///
     382              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     383              :     /// proceeding.
     384              :     pub(crate) gc_block: gc_block::GcBlock,
     385              : 
     386              :     l0_flush_global_state: L0FlushGlobalState,
     387              : }
     388              : impl std::fmt::Debug for Tenant {
     389            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     390            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     391            0 :     }
     392              : }
     393              : 
     394              : pub(crate) enum WalRedoManager {
     395              :     Prod(WalredoManagerId, PostgresRedoManager),
     396              :     #[cfg(test)]
     397              :     Test(harness::TestRedoManager),
     398              : }
     399              : 
     400              : #[derive(thiserror::Error, Debug)]
     401              : #[error("pageserver is shutting down")]
     402              : pub(crate) struct GlobalShutDown;
     403              : 
     404              : impl WalRedoManager {
     405            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     406            0 :         let id = WalredoManagerId::next();
     407            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     408            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     409            0 :         match &mut *guard {
     410            0 :             Some(map) => {
     411            0 :                 map.insert(id, Arc::downgrade(&arc));
     412            0 :                 Ok(arc)
     413              :             }
     414            0 :             None => Err(GlobalShutDown),
     415              :         }
     416            0 :     }
     417              : }
     418              : 
     419              : impl Drop for WalRedoManager {
     420           10 :     fn drop(&mut self) {
     421           10 :         match self {
     422            0 :             Self::Prod(id, _) => {
     423            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     424            0 :                 if let Some(map) = &mut *guard {
     425            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     426            0 :                 }
     427              :             }
     428              :             #[cfg(test)]
     429           10 :             Self::Test(_) => {
     430           10 :                 // Not applicable to test redo manager
     431           10 :             }
     432              :         }
     433           10 :     }
     434              : }
     435              : 
     436              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     437              : /// the walredo processes outside of the regular order.
     438              : ///
     439              : /// This is necessary to work around a systemd bug where it freezes if there are
     440              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     441              : #[allow(clippy::type_complexity)]
     442              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     443              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     444            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     445              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     446              : pub(crate) struct WalredoManagerId(u64);
     447              : impl WalredoManagerId {
     448            0 :     pub fn next() -> Self {
     449              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     450            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     451            0 :         if id == 0 {
     452            0 :             panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
     453            0 :         }
     454            0 :         Self(id)
     455            0 :     }
     456              : }
     457              : 
     458              : #[cfg(test)]
     459              : impl From<harness::TestRedoManager> for WalRedoManager {
     460          192 :     fn from(mgr: harness::TestRedoManager) -> Self {
     461          192 :         Self::Test(mgr)
     462          192 :     }
     463              : }
     464              : 
     465              : impl WalRedoManager {
     466            6 :     pub(crate) async fn shutdown(&self) -> bool {
     467            6 :         match self {
     468            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     469              :             #[cfg(test)]
     470              :             Self::Test(_) => {
     471              :                 // Not applicable to test redo manager
     472            6 :                 true
     473              :             }
     474              :         }
     475            6 :     }
     476              : 
     477            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     478            0 :         match self {
     479            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     480            0 :             #[cfg(test)]
     481            0 :             Self::Test(_) => {
     482            0 :                 // Not applicable to test redo manager
     483            0 :             }
     484            0 :         }
     485            0 :     }
     486              : 
     487              :     /// # Cancel-Safety
     488              :     ///
     489              :     /// This method is cancellation-safe.
     490          410 :     pub async fn request_redo(
     491          410 :         &self,
     492          410 :         key: pageserver_api::key::Key,
     493          410 :         lsn: Lsn,
     494          410 :         base_img: Option<(Lsn, bytes::Bytes)>,
     495          410 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     496          410 :         pg_version: u32,
     497          410 :     ) -> Result<bytes::Bytes, walredo::Error> {
     498          410 :         match self {
     499            0 :             Self::Prod(_, mgr) => {
     500            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     501            0 :                     .await
     502              :             }
     503              :             #[cfg(test)]
     504          410 :             Self::Test(mgr) => {
     505          410 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     506          410 :                     .await
     507              :             }
     508              :         }
     509          410 :     }
     510              : 
     511            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     512            0 :         match self {
     513            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     514            0 :             #[cfg(test)]
     515            0 :             WalRedoManager::Test(_) => None,
     516            0 :         }
     517            0 :     }
     518              : }
     519              : 
     520              : /// A very lightweight memory representation of an offloaded timeline.
     521              : ///
     522              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     523              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     524              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     525              : /// more offloaded timelines than we can manage ones that aren't.
     526              : pub struct OffloadedTimeline {
     527              :     pub tenant_shard_id: TenantShardId,
     528              :     pub timeline_id: TimelineId,
     529              :     pub ancestor_timeline_id: Option<TimelineId>,
     530              :     /// Whether to retain the branch lsn at the ancestor or not
     531              :     pub ancestor_retain_lsn: Option<Lsn>,
     532              : 
     533              :     /// When the timeline was archived.
     534              :     ///
     535              :     /// Present for future flattening deliberations.
     536              :     pub archived_at: NaiveDateTime,
     537              : 
     538              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     539              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     540              :     pub delete_progress: TimelineDeleteProgress,
     541              : 
     542              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     543              :     pub deleted_from_ancestor: AtomicBool,
     544              : }
     545              : 
     546              : impl OffloadedTimeline {
     547              :     /// Obtains an offloaded timeline from a given timeline object.
     548              :     ///
     549              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     550              :     /// the timeline is not in a stopped state.
     551              :     /// Panics if the timeline is not archived.
     552            2 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     553            2 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     554            2 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     555            2 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     556            2 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     557            2 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     558            2 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     559            2 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     560              :             } else {
     561            0 :                 (None, None)
     562              :             };
     563            2 :         let archived_at = timeline
     564            2 :             .remote_client
     565            2 :             .archived_at_stopped_queue()?
     566            2 :             .expect("must be called on an archived timeline");
     567            2 :         Ok(Self {
     568            2 :             tenant_shard_id: timeline.tenant_shard_id,
     569            2 :             timeline_id: timeline.timeline_id,
     570            2 :             ancestor_timeline_id,
     571            2 :             ancestor_retain_lsn,
     572            2 :             archived_at,
     573            2 : 
     574            2 :             delete_progress: timeline.delete_progress.clone(),
     575            2 :             deleted_from_ancestor: AtomicBool::new(false),
     576            2 :         })
     577            2 :     }
     578            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     579            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     580            0 :         // by the `initialize_gc_info` function.
     581            0 :         let OffloadedTimelineManifest {
     582            0 :             timeline_id,
     583            0 :             ancestor_timeline_id,
     584            0 :             ancestor_retain_lsn,
     585            0 :             archived_at,
     586            0 :         } = *manifest;
     587            0 :         Self {
     588            0 :             tenant_shard_id,
     589            0 :             timeline_id,
     590            0 :             ancestor_timeline_id,
     591            0 :             ancestor_retain_lsn,
     592            0 :             archived_at,
     593            0 :             delete_progress: TimelineDeleteProgress::default(),
     594            0 :             deleted_from_ancestor: AtomicBool::new(false),
     595            0 :         }
     596            0 :     }
     597            2 :     fn manifest(&self) -> OffloadedTimelineManifest {
     598            2 :         let Self {
     599            2 :             timeline_id,
     600            2 :             ancestor_timeline_id,
     601            2 :             ancestor_retain_lsn,
     602            2 :             archived_at,
     603            2 :             ..
     604            2 :         } = self;
     605            2 :         OffloadedTimelineManifest {
     606            2 :             timeline_id: *timeline_id,
     607            2 :             ancestor_timeline_id: *ancestor_timeline_id,
     608            2 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     609            2 :             archived_at: *archived_at,
     610            2 :         }
     611            2 :     }
     612              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     613            0 :     fn delete_from_ancestor_with_timelines(
     614            0 :         &self,
     615            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     616            0 :     ) {
     617            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     618            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     619              :         {
     620            0 :             if let Some((_, ancestor_timeline)) = timelines
     621            0 :                 .iter()
     622            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     623              :             {
     624            0 :                 let removal_happened = ancestor_timeline
     625            0 :                     .gc_info
     626            0 :                     .write()
     627            0 :                     .unwrap()
     628            0 :                     .remove_child_offloaded(self.timeline_id);
     629            0 :                 if !removal_happened {
     630            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     631            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     632            0 :                 }
     633            0 :             }
     634            0 :         }
     635            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     636            0 :     }
     637              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     638              :     ///
     639              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     640            2 :     fn defuse_for_tenant_drop(&self) {
     641            2 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     642            2 :     }
     643              : }
     644              : 
     645              : impl fmt::Debug for OffloadedTimeline {
     646            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     647            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     648            0 :     }
     649              : }
     650              : 
     651              : impl Drop for OffloadedTimeline {
     652            2 :     fn drop(&mut self) {
     653            2 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     654            0 :             tracing::warn!(
     655            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     656              :                 self.timeline_id
     657              :             );
     658            2 :         }
     659            2 :     }
     660              : }
     661              : 
     662              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     663              : pub enum MaybeOffloaded {
     664              :     Yes,
     665              :     No,
     666              : }
     667              : 
     668              : #[derive(Clone, Debug)]
     669              : pub enum TimelineOrOffloaded {
     670              :     Timeline(Arc<Timeline>),
     671              :     Offloaded(Arc<OffloadedTimeline>),
     672              : }
     673              : 
     674              : impl TimelineOrOffloaded {
     675            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     676            0 :         match self {
     677            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     678            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     679              :             }
     680            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     681            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     682              :             }
     683              :         }
     684            0 :     }
     685            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     686            0 :         self.arc_ref().tenant_shard_id()
     687            0 :     }
     688            0 :     pub fn timeline_id(&self) -> TimelineId {
     689            0 :         self.arc_ref().timeline_id()
     690            0 :     }
     691            2 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     692            2 :         match self {
     693            2 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     694            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     695              :         }
     696            2 :     }
     697            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     698            0 :         match self {
     699            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     700            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     701              :         }
     702            0 :     }
     703              : }
     704              : 
     705              : pub enum TimelineOrOffloadedArcRef<'a> {
     706              :     Timeline(&'a Arc<Timeline>),
     707              :     Offloaded(&'a Arc<OffloadedTimeline>),
     708              : }
     709              : 
     710              : impl TimelineOrOffloadedArcRef<'_> {
     711            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     712            0 :         match self {
     713            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     714            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     715              :         }
     716            0 :     }
     717            0 :     pub fn timeline_id(&self) -> TimelineId {
     718            0 :         match self {
     719            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     720            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     721              :         }
     722            0 :     }
     723              : }
     724              : 
     725              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     726            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     727            0 :         Self::Timeline(timeline)
     728            0 :     }
     729              : }
     730              : 
     731              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     732            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     733            0 :         Self::Offloaded(timeline)
     734            0 :     }
     735              : }
     736              : 
     737              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     738              : pub enum GetTimelineError {
     739              :     #[error("Timeline is shutting down")]
     740              :     ShuttingDown,
     741              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     742              :     NotActive {
     743              :         tenant_id: TenantShardId,
     744              :         timeline_id: TimelineId,
     745              :         state: TimelineState,
     746              :     },
     747              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     748              :     NotFound {
     749              :         tenant_id: TenantShardId,
     750              :         timeline_id: TimelineId,
     751              :     },
     752              : }
     753              : 
     754              : #[derive(Debug, thiserror::Error)]
     755              : pub enum LoadLocalTimelineError {
     756              :     #[error("FailedToLoad")]
     757              :     Load(#[source] anyhow::Error),
     758              :     #[error("FailedToResumeDeletion")]
     759              :     ResumeDeletion(#[source] anyhow::Error),
     760              : }
     761              : 
     762              : #[derive(thiserror::Error)]
     763              : pub enum DeleteTimelineError {
     764              :     #[error("NotFound")]
     765              :     NotFound,
     766              : 
     767              :     #[error("HasChildren")]
     768              :     HasChildren(Vec<TimelineId>),
     769              : 
     770              :     #[error("Timeline deletion is already in progress")]
     771              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     772              : 
     773              :     #[error("Cancelled")]
     774              :     Cancelled,
     775              : 
     776              :     #[error(transparent)]
     777              :     Other(#[from] anyhow::Error),
     778              : }
     779              : 
     780              : impl Debug for DeleteTimelineError {
     781            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     782            0 :         match self {
     783            0 :             Self::NotFound => write!(f, "NotFound"),
     784            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     785            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     786            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     787            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     788              :         }
     789            0 :     }
     790              : }
     791              : 
     792              : #[derive(thiserror::Error)]
     793              : pub enum TimelineArchivalError {
     794              :     #[error("NotFound")]
     795              :     NotFound,
     796              : 
     797              :     #[error("Timeout")]
     798              :     Timeout,
     799              : 
     800              :     #[error("Cancelled")]
     801              :     Cancelled,
     802              : 
     803              :     #[error("ancestor is archived: {}", .0)]
     804              :     HasArchivedParent(TimelineId),
     805              : 
     806              :     #[error("HasUnarchivedChildren")]
     807              :     HasUnarchivedChildren(Vec<TimelineId>),
     808              : 
     809              :     #[error("Timeline archival is already in progress")]
     810              :     AlreadyInProgress,
     811              : 
     812              :     #[error(transparent)]
     813              :     Other(anyhow::Error),
     814              : }
     815              : 
     816              : #[derive(thiserror::Error, Debug)]
     817              : pub(crate) enum TenantManifestError {
     818              :     #[error("Remote storage error: {0}")]
     819              :     RemoteStorage(anyhow::Error),
     820              : 
     821              :     #[error("Cancelled")]
     822              :     Cancelled,
     823              : }
     824              : 
     825              : impl From<TenantManifestError> for TimelineArchivalError {
     826            0 :     fn from(e: TenantManifestError) -> Self {
     827            0 :         match e {
     828            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     829            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     830              :         }
     831            0 :     }
     832              : }
     833              : 
     834              : impl Debug for TimelineArchivalError {
     835            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     836            0 :         match self {
     837            0 :             Self::NotFound => write!(f, "NotFound"),
     838            0 :             Self::Timeout => write!(f, "Timeout"),
     839            0 :             Self::Cancelled => write!(f, "Cancelled"),
     840            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     841            0 :             Self::HasUnarchivedChildren(c) => {
     842            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     843              :             }
     844            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     845            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     846              :         }
     847            0 :     }
     848              : }
     849              : 
     850              : pub enum SetStoppingError {
     851              :     AlreadyStopping(completion::Barrier),
     852              :     Broken,
     853              : }
     854              : 
     855              : impl Debug for SetStoppingError {
     856            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     857            0 :         match self {
     858            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     859            0 :             Self::Broken => write!(f, "Broken"),
     860              :         }
     861            0 :     }
     862              : }
     863              : 
     864              : /// Arguments to [`Tenant::create_timeline`].
     865              : ///
     866              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     867              : /// is `None`, the result of the timeline create call is not deterministic.
     868              : ///
     869              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     870              : #[derive(Debug)]
     871              : pub(crate) enum CreateTimelineParams {
     872              :     Bootstrap(CreateTimelineParamsBootstrap),
     873              :     Branch(CreateTimelineParamsBranch),
     874              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     875              : }
     876              : 
     877              : #[derive(Debug)]
     878              : pub(crate) struct CreateTimelineParamsBootstrap {
     879              :     pub(crate) new_timeline_id: TimelineId,
     880              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     881              :     pub(crate) pg_version: u32,
     882              : }
     883              : 
     884              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     885              : #[derive(Debug)]
     886              : pub(crate) struct CreateTimelineParamsBranch {
     887              :     pub(crate) new_timeline_id: TimelineId,
     888              :     pub(crate) ancestor_timeline_id: TimelineId,
     889              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     890              : }
     891              : 
     892              : #[derive(Debug)]
     893              : pub(crate) struct CreateTimelineParamsImportPgdata {
     894              :     pub(crate) new_timeline_id: TimelineId,
     895              :     pub(crate) location: import_pgdata::index_part_format::Location,
     896              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     897              : }
     898              : 
     899              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     900              : ///
     901              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     902              : ///
     903              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     904              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     905              : ///
     906              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     907              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     908              : ///
     909              : /// Notes:
     910              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     911              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     912              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     913              : ///
     914              : #[derive(Debug, Clone, PartialEq, Eq)]
     915              : pub(crate) enum CreateTimelineIdempotency {
     916              :     /// NB: special treatment, see comment in [`Self`].
     917              :     FailWithConflict,
     918              :     Bootstrap {
     919              :         pg_version: u32,
     920              :     },
     921              :     /// NB: branches always have the same `pg_version` as their ancestor.
     922              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     923              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     924              :     /// determining the child branch pg_version.
     925              :     Branch {
     926              :         ancestor_timeline_id: TimelineId,
     927              :         ancestor_start_lsn: Lsn,
     928              :     },
     929              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     930              : }
     931              : 
     932              : #[derive(Debug, Clone, PartialEq, Eq)]
     933              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     934              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     935              : }
     936              : 
     937              : /// What is returned by [`Tenant::start_creating_timeline`].
     938              : #[must_use]
     939              : enum StartCreatingTimelineResult {
     940              :     CreateGuard(TimelineCreateGuard),
     941              :     Idempotent(Arc<Timeline>),
     942              : }
     943              : 
     944              : enum TimelineInitAndSyncResult {
     945              :     ReadyToActivate(Arc<Timeline>),
     946              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     947              : }
     948              : 
     949              : impl TimelineInitAndSyncResult {
     950            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     951            0 :         match self {
     952            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     953            0 :             _ => None,
     954              :         }
     955            0 :     }
     956              : }
     957              : 
     958              : #[must_use]
     959              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     960              :     timeline: Arc<Timeline>,
     961              :     import_pgdata: import_pgdata::index_part_format::Root,
     962              :     guard: TimelineCreateGuard,
     963              : }
     964              : 
     965              : /// What is returned by [`Tenant::create_timeline`].
     966              : enum CreateTimelineResult {
     967              :     Created(Arc<Timeline>),
     968              :     Idempotent(Arc<Timeline>),
     969              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     970              :     /// we return this result, nor will this concrete object ever be added there.
     971              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     972              :     ImportSpawned(Arc<Timeline>),
     973              : }
     974              : 
     975              : impl CreateTimelineResult {
     976            0 :     fn discriminant(&self) -> &'static str {
     977            0 :         match self {
     978            0 :             Self::Created(_) => "Created",
     979            0 :             Self::Idempotent(_) => "Idempotent",
     980            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     981              :         }
     982            0 :     }
     983            0 :     fn timeline(&self) -> &Arc<Timeline> {
     984            0 :         match self {
     985            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     986            0 :         }
     987            0 :     }
     988              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     989              :     #[cfg(test)]
     990          230 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     991          230 :         match self {
     992          230 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     993          230 :         }
     994          230 :     }
     995              : }
     996              : 
     997              : #[derive(thiserror::Error, Debug)]
     998              : pub enum CreateTimelineError {
     999              :     #[error("creation of timeline with the given ID is in progress")]
    1000              :     AlreadyCreating,
    1001              :     #[error("timeline already exists with different parameters")]
    1002              :     Conflict,
    1003              :     #[error(transparent)]
    1004              :     AncestorLsn(anyhow::Error),
    1005              :     #[error("ancestor timeline is not active")]
    1006              :     AncestorNotActive,
    1007              :     #[error("ancestor timeline is archived")]
    1008              :     AncestorArchived,
    1009              :     #[error("tenant shutting down")]
    1010              :     ShuttingDown,
    1011              :     #[error(transparent)]
    1012              :     Other(#[from] anyhow::Error),
    1013              : }
    1014              : 
    1015              : #[derive(thiserror::Error, Debug)]
    1016              : pub enum InitdbError {
    1017              :     #[error("Operation was cancelled")]
    1018              :     Cancelled,
    1019              :     #[error(transparent)]
    1020              :     Other(anyhow::Error),
    1021              :     #[error(transparent)]
    1022              :     Inner(postgres_initdb::Error),
    1023              : }
    1024              : 
    1025              : enum CreateTimelineCause {
    1026              :     Load,
    1027              :     Delete,
    1028              : }
    1029              : 
    1030              : enum LoadTimelineCause {
    1031              :     Attach,
    1032              :     Unoffload,
    1033              :     ImportPgdata {
    1034              :         create_guard: TimelineCreateGuard,
    1035              :         activate: ActivateTimelineArgs,
    1036              :     },
    1037              : }
    1038              : 
    1039              : #[derive(thiserror::Error, Debug)]
    1040              : pub(crate) enum GcError {
    1041              :     // The tenant is shutting down
    1042              :     #[error("tenant shutting down")]
    1043              :     TenantCancelled,
    1044              : 
    1045              :     // The tenant is shutting down
    1046              :     #[error("timeline shutting down")]
    1047              :     TimelineCancelled,
    1048              : 
    1049              :     // The tenant is in a state inelegible to run GC
    1050              :     #[error("not active")]
    1051              :     NotActive,
    1052              : 
    1053              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1054              :     #[error("not active")]
    1055              :     BadLsn { why: String },
    1056              : 
    1057              :     // A remote storage error while scheduling updates after compaction
    1058              :     #[error(transparent)]
    1059              :     Remote(anyhow::Error),
    1060              : 
    1061              :     // An error reading while calculating GC cutoffs
    1062              :     #[error(transparent)]
    1063              :     GcCutoffs(PageReconstructError),
    1064              : 
    1065              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1066              :     #[error("timeline not found")]
    1067              :     TimelineNotFound,
    1068              : }
    1069              : 
    1070              : impl From<PageReconstructError> for GcError {
    1071            0 :     fn from(value: PageReconstructError) -> Self {
    1072            0 :         match value {
    1073            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1074            0 :             other => Self::GcCutoffs(other),
    1075              :         }
    1076            0 :     }
    1077              : }
    1078              : 
    1079              : impl From<NotInitialized> for GcError {
    1080            0 :     fn from(value: NotInitialized) -> Self {
    1081            0 :         match value {
    1082            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1083            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1084              :         }
    1085            0 :     }
    1086              : }
    1087              : 
    1088              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1089            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1090            0 :         GcError::TimelineCancelled
    1091            0 :     }
    1092              : }
    1093              : 
    1094              : #[derive(thiserror::Error, Debug)]
    1095              : pub(crate) enum LoadConfigError {
    1096              :     #[error("TOML deserialization error: '{0}'")]
    1097              :     DeserializeToml(#[from] toml_edit::de::Error),
    1098              : 
    1099              :     #[error("Config not found at {0}")]
    1100              :     NotFound(Utf8PathBuf),
    1101              : }
    1102              : 
    1103              : impl Tenant {
    1104              :     /// Yet another helper for timeline initialization.
    1105              :     ///
    1106              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1107              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1108              :     /// - Downloads remote index file and adds remote files to the layer map
    1109              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1110              :     ///
    1111              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1112              :     /// it is marked as Active.
    1113              :     #[allow(clippy::too_many_arguments)]
    1114            6 :     async fn timeline_init_and_sync(
    1115            6 :         self: &Arc<Self>,
    1116            6 :         timeline_id: TimelineId,
    1117            6 :         resources: TimelineResources,
    1118            6 :         mut index_part: IndexPart,
    1119            6 :         metadata: TimelineMetadata,
    1120            6 :         ancestor: Option<Arc<Timeline>>,
    1121            6 :         cause: LoadTimelineCause,
    1122            6 :         ctx: &RequestContext,
    1123            6 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1124            6 :         let tenant_id = self.tenant_shard_id;
    1125            6 : 
    1126            6 :         let import_pgdata = index_part.import_pgdata.take();
    1127            6 :         let idempotency = match &import_pgdata {
    1128            0 :             Some(import_pgdata) => {
    1129            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1130            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1131            0 :                 })
    1132              :             }
    1133              :             None => {
    1134            6 :                 if metadata.ancestor_timeline().is_none() {
    1135            4 :                     CreateTimelineIdempotency::Bootstrap {
    1136            4 :                         pg_version: metadata.pg_version(),
    1137            4 :                     }
    1138              :                 } else {
    1139            2 :                     CreateTimelineIdempotency::Branch {
    1140            2 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1141            2 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1142            2 :                     }
    1143              :                 }
    1144              :             }
    1145              :         };
    1146              : 
    1147            6 :         let timeline = self.create_timeline_struct(
    1148            6 :             timeline_id,
    1149            6 :             &metadata,
    1150            6 :             ancestor.clone(),
    1151            6 :             resources,
    1152            6 :             CreateTimelineCause::Load,
    1153            6 :             idempotency.clone(),
    1154            6 :         )?;
    1155            6 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1156            6 :         anyhow::ensure!(
    1157            6 :             disk_consistent_lsn.is_valid(),
    1158            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1159              :         );
    1160            6 :         assert_eq!(
    1161            6 :             disk_consistent_lsn,
    1162            6 :             metadata.disk_consistent_lsn(),
    1163            0 :             "these are used interchangeably"
    1164              :         );
    1165              : 
    1166            6 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1167              : 
    1168            6 :         timeline
    1169            6 :             .load_layer_map(disk_consistent_lsn, index_part)
    1170            6 :             .await
    1171            6 :             .with_context(|| {
    1172            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1173            6 :             })?;
    1174              : 
    1175            0 :         match import_pgdata {
    1176            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1177            0 :                 match cause {
    1178            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1179              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1180            0 :                         unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
    1181              :                     }
    1182              :                 }
    1183            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1184            0 :                 if !guard.insert(timeline_id) {
    1185              :                     // We should never try and load the same timeline twice during startup
    1186            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1187            0 :                 }
    1188            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1189            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1190            0 :                     owning_tenant: self.clone(),
    1191            0 :                     timeline_id,
    1192            0 :                     idempotency,
    1193            0 :                     // The users of this specific return value don't need the timline_path in there.
    1194            0 :                     timeline_path: timeline
    1195            0 :                         .conf
    1196            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1197            0 :                 };
    1198            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1199            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1200            0 :                         timeline,
    1201            0 :                         import_pgdata,
    1202            0 :                         guard: timeline_create_guard,
    1203            0 :                     },
    1204            0 :                 ))
    1205              :             }
    1206              :             Some(_) | None => {
    1207              :                 {
    1208            6 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1209            6 :                     match timelines_accessor.entry(timeline_id) {
    1210              :                         // We should never try and load the same timeline twice during startup
    1211              :                         Entry::Occupied(_) => {
    1212            0 :                             unreachable!(
    1213            0 :                             "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1214            0 :                         );
    1215              :                         }
    1216            6 :                         Entry::Vacant(v) => {
    1217            6 :                             v.insert(Arc::clone(&timeline));
    1218            6 :                             timeline.maybe_spawn_flush_loop();
    1219            6 :                         }
    1220              :                     }
    1221              :                 }
    1222              : 
    1223              :                 // Sanity check: a timeline should have some content.
    1224            6 :                 anyhow::ensure!(
    1225            6 :                     ancestor.is_some()
    1226            4 :                         || timeline
    1227            4 :                             .layers
    1228            4 :                             .read()
    1229            4 :                             .await
    1230            4 :                             .layer_map()
    1231            4 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1232            4 :                             .iter_historic_layers()
    1233            4 :                             .next()
    1234            4 :                             .is_some(),
    1235            0 :                     "Timeline has no ancestor and no layer files"
    1236              :                 );
    1237              : 
    1238            6 :                 match cause {
    1239            6 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1240              :                     LoadTimelineCause::ImportPgdata {
    1241            0 :                         create_guard,
    1242            0 :                         activate,
    1243            0 :                     } => {
    1244            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1245            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1246            0 :                         match activate {
    1247            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1248            0 :                                 info!("activating timeline after reload from pgdata import task");
    1249            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1250              :                             }
    1251            0 :                             ActivateTimelineArgs::No => (),
    1252              :                         }
    1253            0 :                         drop(create_guard);
    1254              :                     }
    1255              :                 }
    1256              : 
    1257            6 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1258              :             }
    1259              :         }
    1260            6 :     }
    1261              : 
    1262              :     /// Attach a tenant that's available in cloud storage.
    1263              :     ///
    1264              :     /// This returns quickly, after just creating the in-memory object
    1265              :     /// Tenant struct and launching a background task to download
    1266              :     /// the remote index files.  On return, the tenant is most likely still in
    1267              :     /// Attaching state, and it will become Active once the background task
    1268              :     /// finishes. You can use wait_until_active() to wait for the task to
    1269              :     /// complete.
    1270              :     ///
    1271              :     #[allow(clippy::too_many_arguments)]
    1272            0 :     pub(crate) fn spawn(
    1273            0 :         conf: &'static PageServerConf,
    1274            0 :         tenant_shard_id: TenantShardId,
    1275            0 :         resources: TenantSharedResources,
    1276            0 :         attached_conf: AttachedTenantConf,
    1277            0 :         shard_identity: ShardIdentity,
    1278            0 :         init_order: Option<InitializationOrder>,
    1279            0 :         mode: SpawnMode,
    1280            0 :         ctx: &RequestContext,
    1281            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1282            0 :         let wal_redo_manager =
    1283            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1284              : 
    1285              :         let TenantSharedResources {
    1286            0 :             broker_client,
    1287            0 :             remote_storage,
    1288            0 :             deletion_queue_client,
    1289            0 :             l0_flush_global_state,
    1290            0 :         } = resources;
    1291            0 : 
    1292            0 :         let attach_mode = attached_conf.location.attach_mode;
    1293            0 :         let generation = attached_conf.location.generation;
    1294            0 : 
    1295            0 :         let tenant = Arc::new(Tenant::new(
    1296            0 :             TenantState::Attaching,
    1297            0 :             conf,
    1298            0 :             attached_conf,
    1299            0 :             shard_identity,
    1300            0 :             Some(wal_redo_manager),
    1301            0 :             tenant_shard_id,
    1302            0 :             remote_storage.clone(),
    1303            0 :             deletion_queue_client,
    1304            0 :             l0_flush_global_state,
    1305            0 :         ));
    1306            0 : 
    1307            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1308            0 :         // we shut down while attaching.
    1309            0 :         let attach_gate_guard = tenant
    1310            0 :             .gate
    1311            0 :             .enter()
    1312            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1313            0 : 
    1314            0 :         // Do all the hard work in the background
    1315            0 :         let tenant_clone = Arc::clone(&tenant);
    1316            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1317            0 :         task_mgr::spawn(
    1318            0 :             &tokio::runtime::Handle::current(),
    1319            0 :             TaskKind::Attach,
    1320            0 :             tenant_shard_id,
    1321            0 :             None,
    1322            0 :             "attach tenant",
    1323            0 :             async move {
    1324            0 : 
    1325            0 :                 info!(
    1326              :                     ?attach_mode,
    1327            0 :                     "Attaching tenant"
    1328              :                 );
    1329              : 
    1330            0 :                 let _gate_guard = attach_gate_guard;
    1331            0 : 
    1332            0 :                 // Is this tenant being spawned as part of process startup?
    1333            0 :                 let starting_up = init_order.is_some();
    1334            0 :                 scopeguard::defer! {
    1335            0 :                     if starting_up {
    1336            0 :                         TENANT.startup_complete.inc();
    1337            0 :                     }
    1338            0 :                 }
    1339              : 
    1340              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1341              :                 enum BrokenVerbosity {
    1342              :                     Error,
    1343              :                     Info
    1344              :                 }
    1345            0 :                 let make_broken =
    1346            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1347            0 :                         match verbosity {
    1348              :                             BrokenVerbosity::Info => {
    1349            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1350              :                             },
    1351              :                             BrokenVerbosity::Error => {
    1352            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1353              :                             }
    1354              :                         }
    1355            0 :                         t.state.send_modify(|state| {
    1356            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1357            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1358            0 :                             assert!(
    1359            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1360            0 :                                 "the attach task owns the tenant state until activation is complete"
    1361              :                             );
    1362              : 
    1363            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1364            0 :                         });
    1365            0 :                     };
    1366              : 
    1367              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1368            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1369            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1370            0 :                     return Ok(());
    1371            0 :                 }
    1372            0 : 
    1373            0 :                 let mut init_order = init_order;
    1374            0 :                 // take the completion because initial tenant loading will complete when all of
    1375            0 :                 // these tasks complete.
    1376            0 :                 let _completion = init_order
    1377            0 :                     .as_mut()
    1378            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1379            0 :                 let remote_load_completion = init_order
    1380            0 :                     .as_mut()
    1381            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1382              : 
    1383              :                 enum AttachType<'a> {
    1384              :                     /// We are attaching this tenant lazily in the background.
    1385              :                     Warmup {
    1386              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1387              :                         during_startup: bool
    1388              :                     },
    1389              :                     /// We are attaching this tenant as soon as we can, because for example an
    1390              :                     /// endpoint tried to access it.
    1391              :                     OnDemand,
    1392              :                     /// During normal operations after startup, we are attaching a tenant, and
    1393              :                     /// eager attach was requested.
    1394              :                     Normal,
    1395              :                 }
    1396              : 
    1397            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1398              :                     // Before doing any I/O, wait for at least one of:
    1399              :                     // - A client attempting to access to this tenant (on-demand loading)
    1400              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1401              : 
    1402            0 :                     tokio::select!(
    1403            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1404            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1405            0 :                             tracing::info!("Activating tenant (on-demand)");
    1406            0 :                             AttachType::OnDemand
    1407              :                         },
    1408            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1409            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1410            0 :                             tracing::info!("Activating tenant (warmup)");
    1411            0 :                             AttachType::Warmup {
    1412            0 :                                 _permit,
    1413            0 :                                 during_startup: init_order.is_some()
    1414            0 :                             }
    1415              :                         }
    1416            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1417              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1418              :                             // stayed in Activating for such a long time that shutdown found it in
    1419              :                             // that state.
    1420            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1421              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1422              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1423              :                             // just shutting down), but ensures progress.
    1424            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1425            0 :                             return Ok(());
    1426              :                         },
    1427              :                     )
    1428              :                 } else {
    1429              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1430              :                     // concurrent_tenant_warmup queue
    1431            0 :                     AttachType::Normal
    1432              :                 };
    1433              : 
    1434            0 :                 let preload = match &mode {
    1435              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1436            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1437            0 :                         let res = tenant_clone
    1438            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1439            0 :                             .await;
    1440            0 :                         match res {
    1441            0 :                             Ok(p) => Some(p),
    1442            0 :                             Err(e) => {
    1443            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1444            0 :                                 return Ok(());
    1445              :                             }
    1446              :                         }
    1447              :                     }
    1448              : 
    1449              :                 };
    1450              : 
    1451              :                 // Remote preload is complete.
    1452            0 :                 drop(remote_load_completion);
    1453            0 : 
    1454            0 : 
    1455            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1456            0 :                 let attach_start = std::time::Instant::now();
    1457            0 :                 let attached = {
    1458            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1459            0 :                     tenant_clone.attach(preload, &ctx).await
    1460              :                 };
    1461            0 :                 let attach_duration = attach_start.elapsed();
    1462            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1463            0 : 
    1464            0 :                 match attached {
    1465              :                     Ok(()) => {
    1466            0 :                         info!("attach finished, activating");
    1467            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1468              :                     }
    1469            0 :                     Err(e) => {
    1470            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1471            0 :                     }
    1472              :                 }
    1473              : 
    1474              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1475              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1476              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1477              :                 //
    1478              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1479              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1480              :                 // then warmup will wait for that before proceeding to the next tenant.
    1481            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1482            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1483            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1484            0 :                     while futs.next().await.is_some() {}
    1485            0 :                     tracing::info!("Warm-up complete");
    1486            0 :                 }
    1487              : 
    1488            0 :                 Ok(())
    1489            0 :             }
    1490            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1491              :         );
    1492            0 :         Ok(tenant)
    1493            0 :     }
    1494              : 
    1495          192 :     #[instrument(skip_all)]
    1496              :     pub(crate) async fn preload(
    1497              :         self: &Arc<Self>,
    1498              :         remote_storage: &GenericRemoteStorage,
    1499              :         cancel: CancellationToken,
    1500              :     ) -> anyhow::Result<TenantPreload> {
    1501              :         span::debug_assert_current_span_has_tenant_id();
    1502              :         // Get list of remote timelines
    1503              :         // download index files for every tenant timeline
    1504              :         info!("listing remote timelines");
    1505              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1506              :             remote_storage,
    1507              :             self.tenant_shard_id,
    1508              :             cancel.clone(),
    1509              :         )
    1510              :         .await?;
    1511              :         let (offloaded_add, tenant_manifest) =
    1512              :             match remote_timeline_client::download_tenant_manifest(
    1513              :                 remote_storage,
    1514              :                 &self.tenant_shard_id,
    1515              :                 self.generation,
    1516              :                 &cancel,
    1517              :             )
    1518              :             .await
    1519              :             {
    1520              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1521              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1522              :                     tenant_manifest,
    1523              :                 ),
    1524              :                 Err(DownloadError::NotFound) => {
    1525              :                     ("no manifest".to_string(), TenantManifest::empty())
    1526              :                 }
    1527              :                 Err(e) => Err(e)?,
    1528              :             };
    1529              : 
    1530              :         info!(
    1531              :             "found {} timelines, and {offloaded_add}",
    1532              :             remote_timeline_ids.len()
    1533              :         );
    1534              : 
    1535              :         for k in other_keys {
    1536              :             warn!("Unexpected non timeline key {k}");
    1537              :         }
    1538              : 
    1539              :         // Avoid downloading IndexPart of offloaded timelines.
    1540              :         let mut offloaded_with_prefix = HashSet::new();
    1541              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1542              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1543              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1544              :             } else {
    1545              :                 // We'll take care later of timelines in the manifest without a prefix
    1546              :             }
    1547              :         }
    1548              : 
    1549              :         let timelines = self
    1550              :             .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
    1551              :             .await?;
    1552              : 
    1553              :         Ok(TenantPreload {
    1554              :             tenant_manifest,
    1555              :             timelines: timelines
    1556              :                 .into_iter()
    1557            6 :                 .map(|(id, tl)| (id, Some(tl)))
    1558            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1559              :                 .collect(),
    1560              :         })
    1561              :     }
    1562              : 
    1563              :     ///
    1564              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1565              :     ///
    1566              :     /// No background tasks are started as part of this routine.
    1567              :     ///
    1568          192 :     async fn attach(
    1569          192 :         self: &Arc<Tenant>,
    1570          192 :         preload: Option<TenantPreload>,
    1571          192 :         ctx: &RequestContext,
    1572          192 :     ) -> anyhow::Result<()> {
    1573          192 :         span::debug_assert_current_span_has_tenant_id();
    1574          192 : 
    1575          192 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1576              : 
    1577          192 :         let Some(preload) = preload else {
    1578            0 :             anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
    1579              :         };
    1580              : 
    1581          192 :         let mut offloaded_timeline_ids = HashSet::new();
    1582          192 :         let mut offloaded_timelines_list = Vec::new();
    1583          192 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1584            0 :             let timeline_id = timeline_manifest.timeline_id;
    1585            0 :             let offloaded_timeline =
    1586            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1587            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1588            0 :             offloaded_timeline_ids.insert(timeline_id);
    1589            0 :         }
    1590              :         // Complete deletions for offloaded timeline id's from manifest.
    1591              :         // The manifest will be uploaded later in this function.
    1592          192 :         offloaded_timelines_list
    1593          192 :             .retain(|(offloaded_id, offloaded)| {
    1594            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1595            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1596            0 :                 let delete = !preload.timelines.contains_key(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 : 
    1604          192 :         let mut timelines_to_resume_deletions = vec![];
    1605          192 : 
    1606          192 :         let mut remote_index_and_client = HashMap::new();
    1607          192 :         let mut timeline_ancestors = HashMap::new();
    1608          192 :         let mut existent_timelines = HashSet::new();
    1609          198 :         for (timeline_id, preload) in preload.timelines {
    1610            6 :             let Some(preload) = preload else { continue };
    1611              :             // This is an invariant of the `preload` function's API
    1612            6 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1613            6 :             let index_part = match preload.index_part {
    1614            6 :                 Ok(i) => {
    1615            6 :                     debug!("remote index part exists for timeline {timeline_id}");
    1616              :                     // We found index_part on the remote, this is the standard case.
    1617            6 :                     existent_timelines.insert(timeline_id);
    1618            6 :                     i
    1619              :                 }
    1620              :                 Err(DownloadError::NotFound) => {
    1621              :                     // There is no index_part on the remote. We only get here
    1622              :                     // if there is some prefix for the timeline in the remote storage.
    1623              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1624              :                     // remnant from a prior incomplete creation or deletion attempt.
    1625              :                     // Delete the local directory as the deciding criterion for a
    1626              :                     // timeline's existence is presence of index_part.
    1627            0 :                     info!(%timeline_id, "index_part not found on remote");
    1628            0 :                     continue;
    1629              :                 }
    1630            0 :                 Err(DownloadError::Fatal(why)) => {
    1631            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1632            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1633            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1634            0 :                     anyhow::bail!(why.to_string());
    1635              :                 }
    1636            0 :                 Err(e) => {
    1637            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1638            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1639            0 :                     // as it might be a temporary issue and we don't want to re-download
    1640            0 :                     // everything after it resolves.
    1641            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1642              : 
    1643            0 :                     existent_timelines.insert(timeline_id);
    1644            0 :                     continue;
    1645              :                 }
    1646              :             };
    1647            6 :             match index_part {
    1648            6 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1649            6 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1650            6 :                     remote_index_and_client.insert(timeline_id, (index_part, preload.client));
    1651            6 :                 }
    1652            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1653            0 :                     info!(
    1654            0 :                         "timeline {} is deleted, picking to resume deletion",
    1655              :                         timeline_id
    1656              :                     );
    1657            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1658              :                 }
    1659              :             }
    1660              :         }
    1661              : 
    1662          192 :         let mut gc_blocks = HashMap::new();
    1663              : 
    1664              :         // For every timeline, download the metadata file, scan the local directory,
    1665              :         // and build a layer map that contains an entry for each remote and local
    1666              :         // layer file.
    1667          192 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1668          198 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1669            6 :             let (index_part, remote_client) = remote_index_and_client
    1670            6 :                 .remove(&timeline_id)
    1671            6 :                 .expect("just put it in above");
    1672              : 
    1673            6 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1674              :                 // could just filter these away, but it helps while testing
    1675            0 :                 anyhow::ensure!(
    1676            0 :                     !blocking.reasons.is_empty(),
    1677            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1678              :                 );
    1679            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1680            0 :                 assert!(prev.is_none());
    1681            6 :             }
    1682              : 
    1683              :             // TODO again handle early failure
    1684            6 :             let effect = self
    1685            6 :                 .load_remote_timeline(
    1686            6 :                     timeline_id,
    1687            6 :                     index_part,
    1688            6 :                     remote_metadata,
    1689            6 :                     TimelineResources {
    1690            6 :                         remote_client,
    1691            6 :                         pagestream_throttle: self.pagestream_throttle.clone(),
    1692            6 :                         l0_flush_global_state: self.l0_flush_global_state.clone(),
    1693            6 :                     },
    1694            6 :                     LoadTimelineCause::Attach,
    1695            6 :                     ctx,
    1696            6 :                 )
    1697            6 :                 .await
    1698            6 :                 .with_context(|| {
    1699            0 :                     format!(
    1700            0 :                         "failed to load remote timeline {} for tenant {}",
    1701            0 :                         timeline_id, self.tenant_shard_id
    1702            0 :                     )
    1703            6 :                 })?;
    1704              : 
    1705            6 :             match effect {
    1706            6 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1707            6 :                     // activation happens later, on Tenant::activate
    1708            6 :                 }
    1709              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1710              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1711            0 :                         timeline,
    1712            0 :                         import_pgdata,
    1713            0 :                         guard,
    1714            0 :                     },
    1715            0 :                 ) => {
    1716            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1717            0 :                         timeline,
    1718            0 :                         import_pgdata,
    1719            0 :                         ActivateTimelineArgs::No,
    1720            0 :                         guard,
    1721            0 :                     ));
    1722            0 :                 }
    1723              :             }
    1724              :         }
    1725              : 
    1726              :         // Walk through deleted timelines, resume deletion
    1727          192 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1728            0 :             remote_timeline_client
    1729            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1730            0 :                 .context("init queue stopped")
    1731            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1732              : 
    1733            0 :             DeleteTimelineFlow::resume_deletion(
    1734            0 :                 Arc::clone(self),
    1735            0 :                 timeline_id,
    1736            0 :                 &index_part.metadata,
    1737            0 :                 remote_timeline_client,
    1738            0 :             )
    1739            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1740            0 :             .await
    1741            0 :             .context("resume_deletion")
    1742            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1743              :         }
    1744          192 :         let needs_manifest_upload =
    1745          192 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1746          192 :         {
    1747          192 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1748          192 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1749          192 :         }
    1750          192 :         if needs_manifest_upload {
    1751            0 :             self.store_tenant_manifest().await?;
    1752          192 :         }
    1753              : 
    1754              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1755              :         // IndexPart is the source of truth.
    1756          192 :         self.clean_up_timelines(&existent_timelines)?;
    1757              : 
    1758          192 :         self.gc_block.set_scanned(gc_blocks);
    1759          192 : 
    1760          192 :         fail::fail_point!("attach-before-activate", |_| {
    1761            0 :             anyhow::bail!("attach-before-activate");
    1762          192 :         });
    1763          192 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1764              : 
    1765          192 :         info!("Done");
    1766              : 
    1767          192 :         Ok(())
    1768          192 :     }
    1769              : 
    1770              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1771              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1772              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1773          192 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1774          192 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1775              : 
    1776          192 :         let entries = match timelines_dir.read_dir_utf8() {
    1777          192 :             Ok(d) => d,
    1778            0 :             Err(e) => {
    1779            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1780            0 :                     return Ok(());
    1781              :                 } else {
    1782            0 :                     return Err(e).context("list timelines directory for tenant");
    1783              :                 }
    1784              :             }
    1785              :         };
    1786              : 
    1787          200 :         for entry in entries {
    1788            8 :             let entry = entry.context("read timeline dir entry")?;
    1789            8 :             let entry_path = entry.path();
    1790              : 
    1791            8 :             let purge = if crate::is_temporary(entry_path)
    1792              :                 // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
    1793            8 :                 || is_uninit_mark(entry_path)
    1794            8 :                 || crate::is_delete_mark(entry_path)
    1795              :             {
    1796            0 :                 true
    1797              :             } else {
    1798            8 :                 match TimelineId::try_from(entry_path.file_name()) {
    1799            8 :                     Ok(i) => {
    1800            8 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1801            8 :                         !existent_timelines.contains(&i)
    1802              :                     }
    1803            0 :                     Err(e) => {
    1804            0 :                         tracing::warn!(
    1805            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1806              :                         );
    1807              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1808            0 :                         false
    1809              :                     }
    1810              :                 }
    1811              :             };
    1812              : 
    1813            8 :             if purge {
    1814            2 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1815            2 :                 if let Err(e) = match entry.file_type() {
    1816            2 :                     Ok(t) => if t.is_dir() {
    1817            2 :                         std::fs::remove_dir_all(entry_path)
    1818              :                     } else {
    1819            0 :                         std::fs::remove_file(entry_path)
    1820              :                     }
    1821            2 :                     .or_else(fs_ext::ignore_not_found),
    1822            0 :                     Err(e) => Err(e),
    1823              :                 } {
    1824            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1825            2 :                 }
    1826            6 :             }
    1827              :         }
    1828              : 
    1829          192 :         Ok(())
    1830          192 :     }
    1831              : 
    1832              :     /// Get sum of all remote timelines sizes
    1833              :     ///
    1834              :     /// This function relies on the index_part instead of listing the remote storage
    1835            0 :     pub fn remote_size(&self) -> u64 {
    1836            0 :         let mut size = 0;
    1837              : 
    1838            0 :         for timeline in self.list_timelines() {
    1839            0 :             size += timeline.remote_client.get_remote_physical_size();
    1840            0 :         }
    1841              : 
    1842            0 :         size
    1843            0 :     }
    1844              : 
    1845            6 :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1846              :     async fn load_remote_timeline(
    1847              :         self: &Arc<Self>,
    1848              :         timeline_id: TimelineId,
    1849              :         index_part: IndexPart,
    1850              :         remote_metadata: TimelineMetadata,
    1851              :         resources: TimelineResources,
    1852              :         cause: LoadTimelineCause,
    1853              :         ctx: &RequestContext,
    1854              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1855              :         span::debug_assert_current_span_has_tenant_id();
    1856              : 
    1857              :         info!("downloading index file for timeline {}", timeline_id);
    1858              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1859              :             .await
    1860              :             .context("Failed to create new timeline directory")?;
    1861              : 
    1862              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1863              :             let timelines = self.timelines.lock().unwrap();
    1864              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1865            0 :                 || {
    1866            0 :                     anyhow::anyhow!(
    1867            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1868            0 :                     )
    1869            0 :                 },
    1870              :             )?))
    1871              :         } else {
    1872              :             None
    1873              :         };
    1874              : 
    1875              :         self.timeline_init_and_sync(
    1876              :             timeline_id,
    1877              :             resources,
    1878              :             index_part,
    1879              :             remote_metadata,
    1880              :             ancestor,
    1881              :             cause,
    1882              :             ctx,
    1883              :         )
    1884              :         .await
    1885              :     }
    1886              : 
    1887          192 :     async fn load_timelines_metadata(
    1888          192 :         self: &Arc<Tenant>,
    1889          192 :         timeline_ids: HashSet<TimelineId>,
    1890          192 :         remote_storage: &GenericRemoteStorage,
    1891          192 :         cancel: CancellationToken,
    1892          192 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1893          192 :         let mut part_downloads = JoinSet::new();
    1894          198 :         for timeline_id in timeline_ids {
    1895            6 :             let cancel_clone = cancel.clone();
    1896            6 :             part_downloads.spawn(
    1897            6 :                 self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
    1898            6 :                     .instrument(info_span!("download_index_part", %timeline_id)),
    1899              :             );
    1900              :         }
    1901              : 
    1902          192 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1903              : 
    1904              :         loop {
    1905          198 :             tokio::select!(
    1906          198 :                 next = part_downloads.join_next() => {
    1907          198 :                     match next {
    1908            6 :                         Some(result) => {
    1909            6 :                             let preload = result.context("join preload task")?;
    1910            6 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1911              :                         },
    1912              :                         None => {
    1913          192 :                             break;
    1914              :                         }
    1915              :                     }
    1916              :                 },
    1917          198 :                 _ = cancel.cancelled() => {
    1918            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1919              :                 }
    1920              :             )
    1921              :         }
    1922              : 
    1923          192 :         Ok(timeline_preloads)
    1924          192 :     }
    1925              : 
    1926            6 :     fn build_timeline_client(
    1927            6 :         &self,
    1928            6 :         timeline_id: TimelineId,
    1929            6 :         remote_storage: GenericRemoteStorage,
    1930            6 :     ) -> RemoteTimelineClient {
    1931            6 :         RemoteTimelineClient::new(
    1932            6 :             remote_storage.clone(),
    1933            6 :             self.deletion_queue_client.clone(),
    1934            6 :             self.conf,
    1935            6 :             self.tenant_shard_id,
    1936            6 :             timeline_id,
    1937            6 :             self.generation,
    1938            6 :             &self.tenant_conf.load().location,
    1939            6 :         )
    1940            6 :     }
    1941              : 
    1942            6 :     fn load_timeline_metadata(
    1943            6 :         self: &Arc<Tenant>,
    1944            6 :         timeline_id: TimelineId,
    1945            6 :         remote_storage: GenericRemoteStorage,
    1946            6 :         cancel: CancellationToken,
    1947            6 :     ) -> impl Future<Output = TimelinePreload> {
    1948            6 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    1949            6 :         async move {
    1950            6 :             debug_assert_current_span_has_tenant_and_timeline_id();
    1951            6 :             debug!("starting index part download");
    1952              : 
    1953            6 :             let index_part = client.download_index_file(&cancel).await;
    1954              : 
    1955            6 :             debug!("finished index part download");
    1956              : 
    1957            6 :             TimelinePreload {
    1958            6 :                 client,
    1959            6 :                 timeline_id,
    1960            6 :                 index_part,
    1961            6 :             }
    1962            6 :         }
    1963            6 :     }
    1964              : 
    1965            0 :     fn check_to_be_archived_has_no_unarchived_children(
    1966            0 :         timeline_id: TimelineId,
    1967            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1968            0 :     ) -> Result<(), TimelineArchivalError> {
    1969            0 :         let children: Vec<TimelineId> = timelines
    1970            0 :             .iter()
    1971            0 :             .filter_map(|(id, entry)| {
    1972            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    1973            0 :                     return None;
    1974            0 :                 }
    1975            0 :                 if entry.is_archived() == Some(true) {
    1976            0 :                     return None;
    1977            0 :                 }
    1978            0 :                 Some(*id)
    1979            0 :             })
    1980            0 :             .collect();
    1981            0 : 
    1982            0 :         if !children.is_empty() {
    1983            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    1984            0 :         }
    1985            0 :         Ok(())
    1986            0 :     }
    1987              : 
    1988            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    1989            0 :         ancestor_timeline_id: TimelineId,
    1990            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    1991            0 :         offloaded_timelines: &std::sync::MutexGuard<
    1992            0 :             '_,
    1993            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    1994            0 :         >,
    1995            0 :     ) -> Result<(), TimelineArchivalError> {
    1996            0 :         let has_archived_parent =
    1997            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    1998            0 :                 ancestor_timeline.is_archived() == Some(true)
    1999            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2000            0 :                 true
    2001              :             } else {
    2002            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2003            0 :                 if cfg!(debug_assertions) {
    2004            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2005            0 :                 }
    2006            0 :                 return Err(TimelineArchivalError::NotFound);
    2007              :             };
    2008            0 :         if has_archived_parent {
    2009            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2010            0 :                 ancestor_timeline_id,
    2011            0 :             ));
    2012            0 :         }
    2013            0 :         Ok(())
    2014            0 :     }
    2015              : 
    2016            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2017            0 :         timeline: &Arc<Timeline>,
    2018            0 :     ) -> Result<(), TimelineArchivalError> {
    2019            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2020            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2021            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2022            0 :                     ancestor_timeline.timeline_id,
    2023            0 :                 ));
    2024            0 :             }
    2025            0 :         }
    2026            0 :         Ok(())
    2027            0 :     }
    2028              : 
    2029              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2030              :     ///
    2031              :     /// Counterpart to [`offload_timeline`].
    2032            0 :     async fn unoffload_timeline(
    2033            0 :         self: &Arc<Self>,
    2034            0 :         timeline_id: TimelineId,
    2035            0 :         broker_client: storage_broker::BrokerClientChannel,
    2036            0 :         ctx: RequestContext,
    2037            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2038            0 :         info!("unoffloading timeline");
    2039              : 
    2040              :         // We activate the timeline below manually, so this must be called on an active timeline.
    2041              :         // We expect callers of this function to ensure this.
    2042            0 :         match self.current_state() {
    2043              :             TenantState::Activating { .. }
    2044              :             | TenantState::Attaching
    2045              :             | TenantState::Broken { .. } => {
    2046            0 :                 panic!("Timeline expected to be active")
    2047              :             }
    2048            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2049            0 :             TenantState::Active => {}
    2050            0 :         }
    2051            0 :         let cancel = self.cancel.clone();
    2052            0 : 
    2053            0 :         // Protect against concurrent attempts to use this TimelineId
    2054            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2055            0 :         let allow_offloaded = true;
    2056            0 :         let _create_guard = self
    2057            0 :             .create_timeline_create_guard(
    2058            0 :                 timeline_id,
    2059            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2060            0 :                 allow_offloaded,
    2061            0 :             )
    2062            0 :             .map_err(|err| match err {
    2063            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2064              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2065            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2066              :                 }
    2067            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2068            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2069            0 :             })?;
    2070              : 
    2071            0 :         let timeline_preload = self
    2072            0 :             .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
    2073            0 :             .await;
    2074              : 
    2075            0 :         let index_part = match timeline_preload.index_part {
    2076            0 :             Ok(index_part) => {
    2077            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2078            0 :                 index_part
    2079              :             }
    2080              :             Err(DownloadError::NotFound) => {
    2081            0 :                 error!(%timeline_id, "index_part not found on remote");
    2082            0 :                 return Err(TimelineArchivalError::NotFound);
    2083              :             }
    2084            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2085            0 :             Err(e) => {
    2086            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2087            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2088            0 :                 return Err(TimelineArchivalError::Other(
    2089            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2090            0 :                 ));
    2091              :             }
    2092              :         };
    2093            0 :         let index_part = match index_part {
    2094            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2095            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2096            0 :                 info!("timeline is deleted according to index_part.json");
    2097            0 :                 return Err(TimelineArchivalError::NotFound);
    2098              :             }
    2099              :         };
    2100            0 :         let remote_metadata = index_part.metadata.clone();
    2101            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2102            0 :         self.load_remote_timeline(
    2103            0 :             timeline_id,
    2104            0 :             index_part,
    2105            0 :             remote_metadata,
    2106            0 :             timeline_resources,
    2107            0 :             LoadTimelineCause::Unoffload,
    2108            0 :             &ctx,
    2109            0 :         )
    2110            0 :         .await
    2111            0 :         .with_context(|| {
    2112            0 :             format!(
    2113            0 :                 "failed to load remote timeline {} for tenant {}",
    2114            0 :                 timeline_id, self.tenant_shard_id
    2115            0 :             )
    2116            0 :         })
    2117            0 :         .map_err(TimelineArchivalError::Other)?;
    2118              : 
    2119            0 :         let timeline = {
    2120            0 :             let timelines = self.timelines.lock().unwrap();
    2121            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2122            0 :                 warn!("timeline not available directly after attach");
    2123              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2124              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2125            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2126            0 :                     "timeline not available directly after attach"
    2127            0 :                 )));
    2128              :             };
    2129            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2130            0 :             match offloaded_timelines.remove(&timeline_id) {
    2131            0 :                 Some(offloaded) => {
    2132            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2133            0 :                 }
    2134            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2135              :             }
    2136              : 
    2137            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2138            0 : 
    2139            0 :             Arc::clone(timeline)
    2140            0 :         };
    2141            0 : 
    2142            0 :         // Upload new list of offloaded timelines to S3
    2143            0 :         self.store_tenant_manifest().await?;
    2144              : 
    2145              :         // Activate the timeline (if it makes sense)
    2146            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2147            0 :             let background_jobs_can_start = None;
    2148            0 :             timeline.activate(
    2149            0 :                 self.clone(),
    2150            0 :                 broker_client.clone(),
    2151            0 :                 background_jobs_can_start,
    2152            0 :                 &ctx,
    2153            0 :             );
    2154            0 :         }
    2155              : 
    2156            0 :         info!("timeline unoffloading complete");
    2157            0 :         Ok(timeline)
    2158            0 :     }
    2159              : 
    2160            0 :     pub(crate) async fn apply_timeline_archival_config(
    2161            0 :         self: &Arc<Self>,
    2162            0 :         timeline_id: TimelineId,
    2163            0 :         new_state: TimelineArchivalState,
    2164            0 :         broker_client: storage_broker::BrokerClientChannel,
    2165            0 :         ctx: RequestContext,
    2166            0 :     ) -> Result<(), TimelineArchivalError> {
    2167            0 :         info!("setting timeline archival config");
    2168              :         // First part: figure out what is needed to do, and do validation
    2169            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2170            0 :             let timelines = self.timelines.lock().unwrap();
    2171              : 
    2172            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2173            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2174            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2175            0 :                     return Err(TimelineArchivalError::NotFound);
    2176              :                 };
    2177            0 :                 if new_state == TimelineArchivalState::Archived {
    2178              :                     // It's offloaded already, so nothing to do
    2179            0 :                     return Ok(());
    2180            0 :                 }
    2181            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2182            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2183            0 :                         ancestor_timeline_id,
    2184            0 :                         &timelines,
    2185            0 :                         &offloaded_timelines,
    2186            0 :                     )?;
    2187            0 :                 }
    2188            0 :                 break 'outer None;
    2189              :             };
    2190              : 
    2191              :             // Do some validation. We release the timelines lock below, so there is potential
    2192              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2193              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2194            0 :             match new_state {
    2195              :                 TimelineArchivalState::Unarchived => {
    2196            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2197              :                 }
    2198              :                 TimelineArchivalState::Archived => {
    2199            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2200              :                 }
    2201              :             }
    2202            0 :             Some(Arc::clone(timeline))
    2203              :         };
    2204              : 
    2205              :         // Second part: unoffload timeline (if needed)
    2206            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2207            0 :             timeline
    2208              :         } else {
    2209              :             // Turn offloaded timeline into a non-offloaded one
    2210            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2211            0 :                 .await?
    2212              :         };
    2213              : 
    2214              :         // Third part: upload new timeline archival state and block until it is present in S3
    2215            0 :         let upload_needed = match timeline
    2216            0 :             .remote_client
    2217            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2218              :         {
    2219            0 :             Ok(upload_needed) => upload_needed,
    2220            0 :             Err(e) => {
    2221            0 :                 if timeline.cancel.is_cancelled() {
    2222            0 :                     return Err(TimelineArchivalError::Cancelled);
    2223              :                 } else {
    2224            0 :                     return Err(TimelineArchivalError::Other(e));
    2225              :                 }
    2226              :             }
    2227              :         };
    2228              : 
    2229            0 :         if upload_needed {
    2230            0 :             info!("Uploading new state");
    2231              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2232            0 :             let Ok(v) =
    2233            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2234              :             else {
    2235            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2236            0 :                 return Err(TimelineArchivalError::Timeout);
    2237              :             };
    2238            0 :             v.map_err(|e| match e {
    2239            0 :                 WaitCompletionError::NotInitialized(e) => {
    2240            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2241              :                 }
    2242              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2243            0 :                     TimelineArchivalError::Cancelled
    2244              :                 }
    2245            0 :             })?;
    2246            0 :         }
    2247            0 :         Ok(())
    2248            0 :     }
    2249              : 
    2250            2 :     pub fn get_offloaded_timeline(
    2251            2 :         &self,
    2252            2 :         timeline_id: TimelineId,
    2253            2 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2254            2 :         self.timelines_offloaded
    2255            2 :             .lock()
    2256            2 :             .unwrap()
    2257            2 :             .get(&timeline_id)
    2258            2 :             .map(Arc::clone)
    2259            2 :             .ok_or(GetTimelineError::NotFound {
    2260            2 :                 tenant_id: self.tenant_shard_id,
    2261            2 :                 timeline_id,
    2262            2 :             })
    2263            2 :     }
    2264              : 
    2265            4 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2266            4 :         self.tenant_shard_id
    2267            4 :     }
    2268              : 
    2269              :     /// Get Timeline handle for given Neon timeline ID.
    2270              :     /// This function is idempotent. It doesn't change internal state in any way.
    2271          222 :     pub fn get_timeline(
    2272          222 :         &self,
    2273          222 :         timeline_id: TimelineId,
    2274          222 :         active_only: bool,
    2275          222 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2276          222 :         let timelines_accessor = self.timelines.lock().unwrap();
    2277          222 :         let timeline = timelines_accessor
    2278          222 :             .get(&timeline_id)
    2279          222 :             .ok_or(GetTimelineError::NotFound {
    2280          222 :                 tenant_id: self.tenant_shard_id,
    2281          222 :                 timeline_id,
    2282          222 :             })?;
    2283              : 
    2284          220 :         if active_only && !timeline.is_active() {
    2285            0 :             Err(GetTimelineError::NotActive {
    2286            0 :                 tenant_id: self.tenant_shard_id,
    2287            0 :                 timeline_id,
    2288            0 :                 state: timeline.current_state(),
    2289            0 :             })
    2290              :         } else {
    2291          220 :             Ok(Arc::clone(timeline))
    2292              :         }
    2293          222 :     }
    2294              : 
    2295              :     /// Lists timelines the tenant contains.
    2296              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2297            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2298            0 :         self.timelines
    2299            0 :             .lock()
    2300            0 :             .unwrap()
    2301            0 :             .values()
    2302            0 :             .map(Arc::clone)
    2303            0 :             .collect()
    2304            0 :     }
    2305              : 
    2306              :     /// Lists timelines the tenant manages, including offloaded ones.
    2307              :     ///
    2308              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2309            0 :     pub fn list_timelines_and_offloaded(
    2310            0 :         &self,
    2311            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2312            0 :         let timelines = self
    2313            0 :             .timelines
    2314            0 :             .lock()
    2315            0 :             .unwrap()
    2316            0 :             .values()
    2317            0 :             .map(Arc::clone)
    2318            0 :             .collect();
    2319            0 :         let offloaded = self
    2320            0 :             .timelines_offloaded
    2321            0 :             .lock()
    2322            0 :             .unwrap()
    2323            0 :             .values()
    2324            0 :             .map(Arc::clone)
    2325            0 :             .collect();
    2326            0 :         (timelines, offloaded)
    2327            0 :     }
    2328              : 
    2329            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2330            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2331            0 :     }
    2332              : 
    2333              :     /// This is used by tests & import-from-basebackup.
    2334              :     ///
    2335              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2336              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2337              :     ///
    2338              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2339              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2340              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2341              :     /// to the [`Tenant::timelines`].
    2342              :     ///
    2343              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2344          184 :     pub(crate) async fn create_empty_timeline(
    2345          184 :         self: &Arc<Self>,
    2346          184 :         new_timeline_id: TimelineId,
    2347          184 :         initdb_lsn: Lsn,
    2348          184 :         pg_version: u32,
    2349          184 :         _ctx: &RequestContext,
    2350          184 :     ) -> anyhow::Result<UninitializedTimeline> {
    2351          184 :         anyhow::ensure!(
    2352          184 :             self.is_active(),
    2353            0 :             "Cannot create empty timelines on inactive tenant"
    2354              :         );
    2355              : 
    2356              :         // Protect against concurrent attempts to use this TimelineId
    2357          184 :         let create_guard = match self
    2358          184 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2359          184 :             .await?
    2360              :         {
    2361          182 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2362              :             StartCreatingTimelineResult::Idempotent(_) => {
    2363            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2364              :             }
    2365              :         };
    2366              : 
    2367          182 :         let new_metadata = TimelineMetadata::new(
    2368          182 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2369          182 :             // make it valid, before calling finish_creation()
    2370          182 :             Lsn(0),
    2371          182 :             None,
    2372          182 :             None,
    2373          182 :             Lsn(0),
    2374          182 :             initdb_lsn,
    2375          182 :             initdb_lsn,
    2376          182 :             pg_version,
    2377          182 :         );
    2378          182 :         self.prepare_new_timeline(
    2379          182 :             new_timeline_id,
    2380          182 :             &new_metadata,
    2381          182 :             create_guard,
    2382          182 :             initdb_lsn,
    2383          182 :             None,
    2384          182 :         )
    2385          182 :         .await
    2386          184 :     }
    2387              : 
    2388              :     /// Helper for unit tests to create an empty timeline.
    2389              :     ///
    2390              :     /// The timeline is has state value `Active` but its background loops are not running.
    2391              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2392              :     // Our current tests don't need the background loops.
    2393              :     #[cfg(test)]
    2394          174 :     pub async fn create_test_timeline(
    2395          174 :         self: &Arc<Self>,
    2396          174 :         new_timeline_id: TimelineId,
    2397          174 :         initdb_lsn: Lsn,
    2398          174 :         pg_version: u32,
    2399          174 :         ctx: &RequestContext,
    2400          174 :     ) -> anyhow::Result<Arc<Timeline>> {
    2401          174 :         let uninit_tl = self
    2402          174 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2403          174 :             .await?;
    2404          174 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2405          174 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2406              : 
    2407              :         // Setup minimum keys required for the timeline to be usable.
    2408          174 :         let mut modification = tline.begin_modification(initdb_lsn);
    2409          174 :         modification
    2410          174 :             .init_empty_test_timeline()
    2411          174 :             .context("init_empty_test_timeline")?;
    2412          174 :         modification
    2413          174 :             .commit(ctx)
    2414          174 :             .await
    2415          174 :             .context("commit init_empty_test_timeline modification")?;
    2416              : 
    2417              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2418          174 :         tline.maybe_spawn_flush_loop();
    2419          174 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2420              : 
    2421              :         // Make sure the freeze_and_flush reaches remote storage.
    2422          174 :         tline.remote_client.wait_completion().await.unwrap();
    2423              : 
    2424          174 :         let tl = uninit_tl.finish_creation()?;
    2425              :         // The non-test code would call tl.activate() here.
    2426          174 :         tl.set_state(TimelineState::Active);
    2427          174 :         Ok(tl)
    2428          174 :     }
    2429              : 
    2430              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2431              :     #[cfg(test)]
    2432              :     #[allow(clippy::too_many_arguments)]
    2433           32 :     pub async fn create_test_timeline_with_layers(
    2434           32 :         self: &Arc<Self>,
    2435           32 :         new_timeline_id: TimelineId,
    2436           32 :         initdb_lsn: Lsn,
    2437           32 :         pg_version: u32,
    2438           32 :         ctx: &RequestContext,
    2439           32 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2440           32 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2441           32 :         end_lsn: Lsn,
    2442           32 :     ) -> anyhow::Result<Arc<Timeline>> {
    2443              :         use checks::check_valid_layermap;
    2444              :         use itertools::Itertools;
    2445              : 
    2446           32 :         let tline = self
    2447           32 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2448           32 :             .await?;
    2449           32 :         tline.force_advance_lsn(end_lsn);
    2450          100 :         for deltas in delta_layer_desc {
    2451           68 :             tline
    2452           68 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2453           68 :                 .await?;
    2454              :         }
    2455           80 :         for (lsn, images) in image_layer_desc {
    2456           48 :             tline
    2457           48 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2458           48 :                 .await?;
    2459              :         }
    2460           32 :         let layer_names = tline
    2461           32 :             .layers
    2462           32 :             .read()
    2463           32 :             .await
    2464           32 :             .layer_map()
    2465           32 :             .unwrap()
    2466           32 :             .iter_historic_layers()
    2467          148 :             .map(|layer| layer.layer_name())
    2468           32 :             .collect_vec();
    2469           32 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2470            0 :             bail!("invalid layermap: {err}");
    2471           32 :         }
    2472           32 :         Ok(tline)
    2473           32 :     }
    2474              : 
    2475              :     /// Create a new timeline.
    2476              :     ///
    2477              :     /// Returns the new timeline ID and reference to its Timeline object.
    2478              :     ///
    2479              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2480              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2481              :     #[allow(clippy::too_many_arguments)]
    2482            0 :     pub(crate) async fn create_timeline(
    2483            0 :         self: &Arc<Tenant>,
    2484            0 :         params: CreateTimelineParams,
    2485            0 :         broker_client: storage_broker::BrokerClientChannel,
    2486            0 :         ctx: &RequestContext,
    2487            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2488            0 :         if !self.is_active() {
    2489            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2490            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2491              :             } else {
    2492            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2493            0 :                     "Cannot create timelines on inactive tenant"
    2494            0 :                 )));
    2495              :             }
    2496            0 :         }
    2497              : 
    2498            0 :         let _gate = self
    2499            0 :             .gate
    2500            0 :             .enter()
    2501            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2502              : 
    2503            0 :         let result: CreateTimelineResult = match params {
    2504              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2505            0 :                 new_timeline_id,
    2506            0 :                 existing_initdb_timeline_id,
    2507            0 :                 pg_version,
    2508            0 :             }) => {
    2509            0 :                 self.bootstrap_timeline(
    2510            0 :                     new_timeline_id,
    2511            0 :                     pg_version,
    2512            0 :                     existing_initdb_timeline_id,
    2513            0 :                     ctx,
    2514            0 :                 )
    2515            0 :                 .await?
    2516              :             }
    2517              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2518            0 :                 new_timeline_id,
    2519            0 :                 ancestor_timeline_id,
    2520            0 :                 mut ancestor_start_lsn,
    2521              :             }) => {
    2522            0 :                 let ancestor_timeline = self
    2523            0 :                     .get_timeline(ancestor_timeline_id, false)
    2524            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2525              : 
    2526              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2527              :                 // ready for other purposes either.
    2528            0 :                 if !ancestor_timeline.is_active() {
    2529            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2530            0 :                 }
    2531            0 : 
    2532            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2533            0 :                     info!("tried to branch archived timeline");
    2534            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2535            0 :                 }
    2536              : 
    2537            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2538            0 :                     *lsn = lsn.align();
    2539            0 : 
    2540            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2541            0 :                     if ancestor_ancestor_lsn > *lsn {
    2542              :                         // can we safely just branch from the ancestor instead?
    2543            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2544            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2545            0 :                             lsn,
    2546            0 :                             ancestor_timeline_id,
    2547            0 :                             ancestor_ancestor_lsn,
    2548            0 :                         )));
    2549            0 :                     }
    2550            0 : 
    2551            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2552            0 :                     // to the requested branch point. The repository code itself doesn't
    2553            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2554            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2555            0 :                     // sizes etc. and that would get confused if the previous page versions
    2556            0 :                     // are not in the repository yet.
    2557            0 :                     ancestor_timeline
    2558            0 :                         .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
    2559            0 :                         .await
    2560            0 :                         .map_err(|e| match e {
    2561            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2562            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2563              :                             }
    2564            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2565            0 :                         })?;
    2566            0 :                 }
    2567              : 
    2568            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2569            0 :                     .await?
    2570              :             }
    2571            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2572            0 :                 self.create_timeline_import_pgdata(
    2573            0 :                     params,
    2574            0 :                     ActivateTimelineArgs::Yes {
    2575            0 :                         broker_client: broker_client.clone(),
    2576            0 :                     },
    2577            0 :                     ctx,
    2578            0 :                 )
    2579            0 :                 .await?
    2580              :             }
    2581              :         };
    2582              : 
    2583              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2584              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2585              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2586              :         //
    2587              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2588              :         // assume that, because they can see the timeline via API, that the creation is done and
    2589              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2590              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2591              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2592              :         //
    2593              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2594              :         // creation API until it returns success. Only then is durability guaranteed.
    2595            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2596            0 :         result
    2597            0 :             .timeline()
    2598            0 :             .remote_client
    2599            0 :             .wait_completion()
    2600            0 :             .await
    2601            0 :             .map_err(|e| match e {
    2602              :                 WaitCompletionError::NotInitialized(
    2603            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2604            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2605            0 :                 e => CreateTimelineError::Other(e.into()),
    2606            0 :             })
    2607            0 :             .context("wait for timeline initial uploads to complete")?;
    2608              : 
    2609              :         // The creating task is responsible for activating the timeline.
    2610              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2611              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2612            0 :         let activated_timeline = match result {
    2613            0 :             CreateTimelineResult::Created(timeline) => {
    2614            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2615            0 :                 timeline
    2616              :             }
    2617            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2618            0 :                 info!(
    2619            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2620              :                 );
    2621            0 :                 timeline
    2622              :             }
    2623            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2624            0 :                 info!("import task spawned, timeline will become visible and activated once the import is done");
    2625            0 :                 timeline
    2626              :             }
    2627              :         };
    2628              : 
    2629            0 :         Ok(activated_timeline)
    2630            0 :     }
    2631              : 
    2632              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2633              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2634              :     /// [`Tenant::timelines`] map when the import completes.
    2635              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2636              :     /// for the response.
    2637            0 :     async fn create_timeline_import_pgdata(
    2638            0 :         self: &Arc<Tenant>,
    2639            0 :         params: CreateTimelineParamsImportPgdata,
    2640            0 :         activate: ActivateTimelineArgs,
    2641            0 :         ctx: &RequestContext,
    2642            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2643            0 :         let CreateTimelineParamsImportPgdata {
    2644            0 :             new_timeline_id,
    2645            0 :             location,
    2646            0 :             idempotency_key,
    2647            0 :         } = params;
    2648            0 : 
    2649            0 :         let started_at = chrono::Utc::now().naive_utc();
    2650              : 
    2651              :         //
    2652              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2653              :         // is the canonical way we do it.
    2654              :         // - create an empty timeline in-memory
    2655              :         // - use its remote_timeline_client to do the upload
    2656              :         // - dispose of the uninit timeline
    2657              :         // - keep the creation guard alive
    2658              : 
    2659            0 :         let timeline_create_guard = match self
    2660            0 :             .start_creating_timeline(
    2661            0 :                 new_timeline_id,
    2662            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2663            0 :                     idempotency_key: idempotency_key.clone(),
    2664            0 :                 }),
    2665            0 :             )
    2666            0 :             .await?
    2667              :         {
    2668            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2669            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2670            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    2671              :             }
    2672              :         };
    2673              : 
    2674            0 :         let mut uninit_timeline = {
    2675            0 :             let this = &self;
    2676            0 :             let initdb_lsn = Lsn(0);
    2677            0 :             let _ctx = ctx;
    2678            0 :             async move {
    2679            0 :                 let new_metadata = TimelineMetadata::new(
    2680            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2681            0 :                     // make it valid, before calling finish_creation()
    2682            0 :                     Lsn(0),
    2683            0 :                     None,
    2684            0 :                     None,
    2685            0 :                     Lsn(0),
    2686            0 :                     initdb_lsn,
    2687            0 :                     initdb_lsn,
    2688            0 :                     15,
    2689            0 :                 );
    2690            0 :                 this.prepare_new_timeline(
    2691            0 :                     new_timeline_id,
    2692            0 :                     &new_metadata,
    2693            0 :                     timeline_create_guard,
    2694            0 :                     initdb_lsn,
    2695            0 :                     None,
    2696            0 :                 )
    2697            0 :                 .await
    2698            0 :             }
    2699            0 :         }
    2700            0 :         .await?;
    2701              : 
    2702            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2703            0 :             idempotency_key,
    2704            0 :             location,
    2705            0 :             started_at,
    2706            0 :         };
    2707            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2708            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2709            0 :         );
    2710            0 :         uninit_timeline
    2711            0 :             .raw_timeline()
    2712            0 :             .unwrap()
    2713            0 :             .remote_client
    2714            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2715              : 
    2716              :         // wait_completion happens in caller
    2717              : 
    2718            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2719            0 : 
    2720            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2721            0 :             timeline.clone(),
    2722            0 :             index_part,
    2723            0 :             activate,
    2724            0 :             timeline_create_guard,
    2725            0 :         ));
    2726            0 : 
    2727            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2728            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2729            0 :     }
    2730              : 
    2731            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
    2732              :     async fn create_timeline_import_pgdata_task(
    2733              :         self: Arc<Tenant>,
    2734              :         timeline: Arc<Timeline>,
    2735              :         index_part: import_pgdata::index_part_format::Root,
    2736              :         activate: ActivateTimelineArgs,
    2737              :         timeline_create_guard: TimelineCreateGuard,
    2738              :     ) {
    2739              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2740              :         info!("starting");
    2741              :         scopeguard::defer! {info!("exiting")};
    2742              : 
    2743              :         let res = self
    2744              :             .create_timeline_import_pgdata_task_impl(
    2745              :                 timeline,
    2746              :                 index_part,
    2747              :                 activate,
    2748              :                 timeline_create_guard,
    2749              :             )
    2750              :             .await;
    2751              :         if let Err(err) = &res {
    2752              :             error!(?err, "task failed");
    2753              :             // TODO sleep & retry, sensitive to tenant shutdown
    2754              :             // TODO: allow timeline deletion requests => should cancel the task
    2755              :         }
    2756              :     }
    2757              : 
    2758            0 :     async fn create_timeline_import_pgdata_task_impl(
    2759            0 :         self: Arc<Tenant>,
    2760            0 :         timeline: Arc<Timeline>,
    2761            0 :         index_part: import_pgdata::index_part_format::Root,
    2762            0 :         activate: ActivateTimelineArgs,
    2763            0 :         timeline_create_guard: TimelineCreateGuard,
    2764            0 :     ) -> Result<(), anyhow::Error> {
    2765            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2766            0 : 
    2767            0 :         info!("importing pgdata");
    2768            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2769            0 :             .await
    2770            0 :             .context("import")?;
    2771            0 :         info!("import done");
    2772              : 
    2773              :         //
    2774              :         // Reload timeline from remote.
    2775              :         // This proves that the remote state is attachable, and it reuses the code.
    2776              :         //
    2777              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2778              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2779              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2780              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2781              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2782              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2783              :         // to manifest because of the long runtime of this import task.
    2784              : 
    2785              :         //        in theory this shouldn't even .await anything except for coop yield
    2786            0 :         info!("shutting down timeline");
    2787            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2788            0 :         info!("timeline shut down, reloading from remote");
    2789              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2790              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2791              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2792              :         // };
    2793            0 :         let timeline_id = timeline.timeline_id;
    2794            0 : 
    2795            0 :         // load from object storage like Tenant::attach does
    2796            0 :         let resources = self.build_timeline_resources(timeline_id);
    2797            0 :         let index_part = resources
    2798            0 :             .remote_client
    2799            0 :             .download_index_file(&self.cancel)
    2800            0 :             .await?;
    2801            0 :         let index_part = match index_part {
    2802              :             MaybeDeletedIndexPart::Deleted(_) => {
    2803              :                 // likely concurrent delete call, cplane should prevent this
    2804            0 :                 anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
    2805              :             }
    2806            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2807            0 :         };
    2808            0 :         let metadata = index_part.metadata.clone();
    2809            0 :         self
    2810            0 :             .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
    2811            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2812            0 :             .await?
    2813            0 :             .ready_to_activate()
    2814            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2815              : 
    2816            0 :         anyhow::Ok(())
    2817            0 :     }
    2818              : 
    2819            0 :     pub(crate) async fn delete_timeline(
    2820            0 :         self: Arc<Self>,
    2821            0 :         timeline_id: TimelineId,
    2822            0 :     ) -> Result<(), DeleteTimelineError> {
    2823            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2824              : 
    2825            0 :         Ok(())
    2826            0 :     }
    2827              : 
    2828              :     /// perform one garbage collection iteration, removing old data files from disk.
    2829              :     /// this function is periodically called by gc task.
    2830              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2831              :     ///
    2832              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2833              :     ///
    2834              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2835              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2836              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2837              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2838              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2839              :     /// requires more history to be retained.
    2840              :     //
    2841          754 :     pub(crate) async fn gc_iteration(
    2842          754 :         &self,
    2843          754 :         target_timeline_id: Option<TimelineId>,
    2844          754 :         horizon: u64,
    2845          754 :         pitr: Duration,
    2846          754 :         cancel: &CancellationToken,
    2847          754 :         ctx: &RequestContext,
    2848          754 :     ) -> Result<GcResult, GcError> {
    2849          754 :         // Don't start doing work during shutdown
    2850          754 :         if let TenantState::Stopping { .. } = self.current_state() {
    2851            0 :             return Ok(GcResult::default());
    2852          754 :         }
    2853          754 : 
    2854          754 :         // there is a global allowed_error for this
    2855          754 :         if !self.is_active() {
    2856            0 :             return Err(GcError::NotActive);
    2857          754 :         }
    2858          754 : 
    2859          754 :         {
    2860          754 :             let conf = self.tenant_conf.load();
    2861          754 : 
    2862          754 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2863          754 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2864          754 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2865          754 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2866          754 :             if !conf.location.may_delete_layers_hint() {
    2867            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2868            0 :                 return Ok(GcResult::default());
    2869          754 :             }
    2870          754 : 
    2871          754 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2872          750 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2873          750 :                 return Ok(GcResult::default());
    2874            4 :             }
    2875              :         }
    2876              : 
    2877            4 :         let _guard = match self.gc_block.start().await {
    2878            4 :             Ok(guard) => guard,
    2879            0 :             Err(reasons) => {
    2880            0 :                 info!("Skipping GC: {reasons}");
    2881            0 :                 return Ok(GcResult::default());
    2882              :             }
    2883              :         };
    2884              : 
    2885            4 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2886            4 :             .await
    2887          754 :     }
    2888              : 
    2889              :     /// Perform one compaction iteration.
    2890              :     /// This function is periodically called by compactor task.
    2891              :     /// Also it can be explicitly requested per timeline through page server
    2892              :     /// api's 'compact' command.
    2893              :     ///
    2894              :     /// Returns whether we have pending compaction task.
    2895            0 :     async fn compaction_iteration(
    2896            0 :         self: &Arc<Self>,
    2897            0 :         cancel: &CancellationToken,
    2898            0 :         ctx: &RequestContext,
    2899            0 :     ) -> Result<bool, timeline::CompactionError> {
    2900            0 :         // Don't start doing work during shutdown, or when broken, we do not need those in the logs
    2901            0 :         if !self.is_active() {
    2902            0 :             return Ok(false);
    2903            0 :         }
    2904            0 : 
    2905            0 :         {
    2906            0 :             let conf = self.tenant_conf.load();
    2907            0 : 
    2908            0 :             // Note that compaction usually requires deletions, but we don't respect
    2909            0 :             // may_delete_layers_hint here: that is because tenants in AttachedMulti
    2910            0 :             // should proceed with compaction even if they can't do deletion, to avoid
    2911            0 :             // accumulating dangerously deep stacks of L0 layers.  Deletions will be
    2912            0 :             // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
    2913            0 :             // to AttachedSingle state.
    2914            0 :             if !conf.location.may_upload_layers_hint() {
    2915            0 :                 info!("Skipping compaction in location state {:?}", conf.location);
    2916            0 :                 return Ok(false);
    2917            0 :             }
    2918            0 :         }
    2919            0 : 
    2920            0 :         // Scan through the hashmap and collect a list of all the timelines,
    2921            0 :         // while holding the lock. Then drop the lock and actually perform the
    2922            0 :         // compactions.  We don't want to block everything else while the
    2923            0 :         // compaction runs.
    2924            0 :         let timelines_to_compact_or_offload;
    2925            0 :         {
    2926            0 :             let timelines = self.timelines.lock().unwrap();
    2927            0 :             timelines_to_compact_or_offload = timelines
    2928            0 :                 .iter()
    2929            0 :                 .filter_map(|(timeline_id, timeline)| {
    2930            0 :                     let (is_active, (can_offload, _)) =
    2931            0 :                         (timeline.is_active(), timeline.can_offload());
    2932            0 :                     let has_no_unoffloaded_children = {
    2933            0 :                         !timelines
    2934            0 :                             .iter()
    2935            0 :                             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
    2936              :                     };
    2937            0 :                     let config_allows_offload = self.conf.timeline_offloading
    2938            0 :                         || self
    2939            0 :                             .tenant_conf
    2940            0 :                             .load()
    2941            0 :                             .tenant_conf
    2942            0 :                             .timeline_offloading
    2943            0 :                             .unwrap_or_default();
    2944            0 :                     let can_offload =
    2945            0 :                         can_offload && has_no_unoffloaded_children && config_allows_offload;
    2946            0 :                     if (is_active, can_offload) == (false, false) {
    2947            0 :                         None
    2948              :                     } else {
    2949            0 :                         Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
    2950              :                     }
    2951            0 :                 })
    2952            0 :                 .collect::<Vec<_>>();
    2953            0 :             drop(timelines);
    2954            0 :         }
    2955            0 : 
    2956            0 :         // Before doing any I/O work, check our circuit breaker
    2957            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2958            0 :             info!("Skipping compaction due to previous failures");
    2959            0 :             return Ok(false);
    2960            0 :         }
    2961            0 : 
    2962            0 :         let mut has_pending_task = false;
    2963              : 
    2964            0 :         for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
    2965              :         {
    2966              :             // pending_task_left == None: cannot compact, maybe still pending tasks
    2967              :             // pending_task_left == Some(true): compaction task left
    2968              :             // pending_task_left == Some(false): no compaction task left
    2969            0 :             let pending_task_left = if *can_compact {
    2970            0 :                 let has_pending_l0_compaction_task = timeline
    2971            0 :                     .compact(cancel, EnumSet::empty(), ctx)
    2972            0 :                     .instrument(info_span!("compact_timeline", %timeline_id))
    2973            0 :                     .await
    2974            0 :                     .inspect_err(|e| match e {
    2975            0 :                         timeline::CompactionError::ShuttingDown => (),
    2976            0 :                         timeline::CompactionError::Offload(_) => {
    2977            0 :                             // Failures to offload timelines do not trip the circuit breaker, because
    2978            0 :                             // they do not do lots of writes the way compaction itself does: it is cheap
    2979            0 :                             // to retry, and it would be bad to stop all compaction because of an issue with offloading.
    2980            0 :                         }
    2981            0 :                         timeline::CompactionError::Other(e) => {
    2982            0 :                             self.compaction_circuit_breaker
    2983            0 :                                 .lock()
    2984            0 :                                 .unwrap()
    2985            0 :                                 .fail(&CIRCUIT_BREAKERS_BROKEN, e);
    2986            0 :                         }
    2987            0 :                     })?;
    2988            0 :                 if has_pending_l0_compaction_task {
    2989            0 :                     Some(true)
    2990              :                 } else {
    2991              :                     let mut has_pending_scheduled_compaction_task;
    2992            0 :                     let next_scheduled_compaction_task = {
    2993            0 :                         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    2994            0 :                         if let Some(tline_pending_tasks) = guard.get_mut(timeline_id) {
    2995            0 :                             if !tline_pending_tasks.is_empty() {
    2996            0 :                                 info!(
    2997            0 :                                     "{} tasks left in the compaction schedule queue",
    2998            0 :                                     tline_pending_tasks.len()
    2999              :                                 );
    3000            0 :                             }
    3001            0 :                             let next_task = tline_pending_tasks.pop_front();
    3002            0 :                             has_pending_scheduled_compaction_task = !tline_pending_tasks.is_empty();
    3003            0 :                             next_task
    3004              :                         } else {
    3005            0 :                             has_pending_scheduled_compaction_task = false;
    3006            0 :                             None
    3007              :                         }
    3008              :                     };
    3009            0 :                     if let Some(mut next_scheduled_compaction_task) = next_scheduled_compaction_task
    3010              :                     {
    3011            0 :                         if !next_scheduled_compaction_task
    3012            0 :                             .options
    3013            0 :                             .flags
    3014            0 :                             .contains(CompactFlags::EnhancedGcBottomMostCompaction)
    3015              :                         {
    3016            0 :                             warn!("ignoring scheduled compaction task: scheduled task must be gc compaction: {:?}", next_scheduled_compaction_task.options);
    3017            0 :                         } else if next_scheduled_compaction_task.options.sub_compaction {
    3018            0 :                             info!("running scheduled enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs");
    3019            0 :                             let jobs = timeline
    3020            0 :                                 .gc_compaction_split_jobs(next_scheduled_compaction_task.options)
    3021            0 :                                 .await
    3022            0 :                                 .map_err(CompactionError::Other)?;
    3023            0 :                             if jobs.is_empty() {
    3024            0 :                                 info!("no jobs to run, skipping scheduled compaction task");
    3025              :                             } else {
    3026            0 :                                 has_pending_scheduled_compaction_task = true;
    3027            0 :                                 let jobs_len = jobs.len();
    3028            0 :                                 let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3029            0 :                                 let tline_pending_tasks = guard.entry(*timeline_id).or_default();
    3030            0 :                                 for (idx, job) in jobs.into_iter().enumerate() {
    3031            0 :                                     tline_pending_tasks.push_back(if idx == jobs_len - 1 {
    3032            0 :                                         ScheduledCompactionTask {
    3033            0 :                                             options: job,
    3034            0 :                                             // The last job in the queue sends the signal and releases the gc guard
    3035            0 :                                             result_tx: next_scheduled_compaction_task
    3036            0 :                                                 .result_tx
    3037            0 :                                                 .take(),
    3038            0 :                                             gc_block: next_scheduled_compaction_task
    3039            0 :                                                 .gc_block
    3040            0 :                                                 .take(),
    3041            0 :                                         }
    3042              :                                     } else {
    3043            0 :                                         ScheduledCompactionTask {
    3044            0 :                                             options: job,
    3045            0 :                                             result_tx: None,
    3046            0 :                                             gc_block: None,
    3047            0 :                                         }
    3048              :                                     });
    3049              :                                 }
    3050            0 :                                 info!("scheduled enhanced gc bottom-most compaction with sub-compaction, split into {} jobs", jobs_len);
    3051              :                             }
    3052              :                         } else {
    3053            0 :                             let _ = timeline
    3054            0 :                                 .compact_with_options(
    3055            0 :                                     cancel,
    3056            0 :                                     next_scheduled_compaction_task.options,
    3057            0 :                                     ctx,
    3058            0 :                                 )
    3059            0 :                                 .instrument(info_span!("scheduled_compact_timeline", %timeline_id))
    3060            0 :                                 .await?;
    3061            0 :                             if let Some(tx) = next_scheduled_compaction_task.result_tx.take() {
    3062            0 :                                 // TODO: we can send compaction statistics in the future
    3063            0 :                                 tx.send(()).ok();
    3064            0 :                             }
    3065              :                         }
    3066            0 :                     }
    3067            0 :                     Some(has_pending_scheduled_compaction_task)
    3068              :                 }
    3069              :             } else {
    3070            0 :                 None
    3071              :             };
    3072            0 :             has_pending_task |= pending_task_left.unwrap_or(false);
    3073            0 :             if pending_task_left == Some(false) && *can_offload {
    3074            0 :                 offload_timeline(self, timeline)
    3075            0 :                     .instrument(info_span!("offload_timeline", %timeline_id))
    3076            0 :                     .await?;
    3077            0 :             }
    3078              :         }
    3079              : 
    3080            0 :         self.compaction_circuit_breaker
    3081            0 :             .lock()
    3082            0 :             .unwrap()
    3083            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3084            0 : 
    3085            0 :         Ok(has_pending_task)
    3086            0 :     }
    3087              : 
    3088              :     /// Cancel scheduled compaction tasks
    3089            0 :     pub(crate) fn cancel_scheduled_compaction(
    3090            0 :         &self,
    3091            0 :         timeline_id: TimelineId,
    3092            0 :     ) -> Vec<ScheduledCompactionTask> {
    3093            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3094            0 :         if let Some(tline_pending_tasks) = guard.get_mut(&timeline_id) {
    3095            0 :             let current_tline_pending_tasks = std::mem::take(tline_pending_tasks);
    3096            0 :             current_tline_pending_tasks.into_iter().collect()
    3097              :         } else {
    3098            0 :             Vec::new()
    3099              :         }
    3100            0 :     }
    3101              : 
    3102              :     /// Schedule a compaction task for a timeline.
    3103            0 :     pub(crate) async fn schedule_compaction(
    3104            0 :         &self,
    3105            0 :         timeline_id: TimelineId,
    3106            0 :         options: CompactOptions,
    3107            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3108            0 :         let gc_guard = match self.gc_block.start().await {
    3109            0 :             Ok(guard) => guard,
    3110            0 :             Err(e) => {
    3111            0 :                 bail!("cannot run gc-compaction because gc is blocked: {}", e);
    3112              :             }
    3113              :         };
    3114            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3115            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3116            0 :         let tline_pending_tasks = guard.entry(timeline_id).or_default();
    3117            0 :         tline_pending_tasks.push_back(ScheduledCompactionTask {
    3118            0 :             options,
    3119            0 :             result_tx: Some(tx),
    3120            0 :             gc_block: Some(gc_guard),
    3121            0 :         });
    3122            0 :         Ok(rx)
    3123            0 :     }
    3124              : 
    3125              :     // Call through to all timelines to freeze ephemeral layers if needed.  Usually
    3126              :     // this happens during ingest: this background housekeeping is for freezing layers
    3127              :     // that are open but haven't been written to for some time.
    3128            0 :     async fn ingest_housekeeping(&self) {
    3129            0 :         // Scan through the hashmap and collect a list of all the timelines,
    3130            0 :         // while holding the lock. Then drop the lock and actually perform the
    3131            0 :         // compactions.  We don't want to block everything else while the
    3132            0 :         // compaction runs.
    3133            0 :         let timelines = {
    3134            0 :             self.timelines
    3135            0 :                 .lock()
    3136            0 :                 .unwrap()
    3137            0 :                 .values()
    3138            0 :                 .filter_map(|timeline| {
    3139            0 :                     if timeline.is_active() {
    3140            0 :                         Some(timeline.clone())
    3141              :                     } else {
    3142            0 :                         None
    3143              :                     }
    3144            0 :                 })
    3145            0 :                 .collect::<Vec<_>>()
    3146              :         };
    3147              : 
    3148            0 :         for timeline in &timelines {
    3149            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3150              :         }
    3151            0 :     }
    3152              : 
    3153            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3154            0 :         let timelines = self.timelines.lock().unwrap();
    3155            0 :         !timelines
    3156            0 :             .iter()
    3157            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3158            0 :     }
    3159              : 
    3160         1702 :     pub fn current_state(&self) -> TenantState {
    3161         1702 :         self.state.borrow().clone()
    3162         1702 :     }
    3163              : 
    3164          942 :     pub fn is_active(&self) -> bool {
    3165          942 :         self.current_state() == TenantState::Active
    3166          942 :     }
    3167              : 
    3168            0 :     pub fn generation(&self) -> Generation {
    3169            0 :         self.generation
    3170            0 :     }
    3171              : 
    3172            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3173            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3174            0 :     }
    3175              : 
    3176              :     /// Changes tenant status to active, unless shutdown was already requested.
    3177              :     ///
    3178              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3179              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3180            0 :     fn activate(
    3181            0 :         self: &Arc<Self>,
    3182            0 :         broker_client: BrokerClientChannel,
    3183            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3184            0 :         ctx: &RequestContext,
    3185            0 :     ) {
    3186            0 :         span::debug_assert_current_span_has_tenant_id();
    3187            0 : 
    3188            0 :         let mut activating = false;
    3189            0 :         self.state.send_modify(|current_state| {
    3190              :             use pageserver_api::models::ActivatingFrom;
    3191            0 :             match &*current_state {
    3192              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3193            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3194              :                 }
    3195            0 :                 TenantState::Attaching => {
    3196            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3197            0 :                 }
    3198            0 :             }
    3199            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3200            0 :             activating = true;
    3201            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3202            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3203            0 :         });
    3204            0 : 
    3205            0 :         if activating {
    3206            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3207            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3208            0 :             let timelines_to_activate = timelines_accessor
    3209            0 :                 .values()
    3210            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3211            0 : 
    3212            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3213            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3214            0 : 
    3215            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3216            0 :             // down when they notice that the tenant is inactive.
    3217            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3218            0 : 
    3219            0 :             let mut activated_timelines = 0;
    3220              : 
    3221            0 :             for timeline in timelines_to_activate {
    3222            0 :                 timeline.activate(
    3223            0 :                     self.clone(),
    3224            0 :                     broker_client.clone(),
    3225            0 :                     background_jobs_can_start,
    3226            0 :                     ctx,
    3227            0 :                 );
    3228            0 :                 activated_timelines += 1;
    3229            0 :             }
    3230              : 
    3231            0 :             self.state.send_modify(move |current_state| {
    3232            0 :                 assert!(
    3233            0 :                     matches!(current_state, TenantState::Activating(_)),
    3234            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3235              :                 );
    3236            0 :                 *current_state = TenantState::Active;
    3237            0 : 
    3238            0 :                 let elapsed = self.constructed_at.elapsed();
    3239            0 :                 let total_timelines = timelines_accessor.len();
    3240            0 : 
    3241            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3242            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3243            0 :                 info!(
    3244            0 :                     since_creation_millis = elapsed.as_millis(),
    3245            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3246            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3247            0 :                     activated_timelines,
    3248            0 :                     total_timelines,
    3249            0 :                     post_state = <&'static str>::from(&*current_state),
    3250            0 :                     "activation attempt finished"
    3251              :                 );
    3252              : 
    3253            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3254            0 :             });
    3255            0 :         }
    3256            0 :     }
    3257              : 
    3258              :     /// Shutdown the tenant and join all of the spawned tasks.
    3259              :     ///
    3260              :     /// The method caters for all use-cases:
    3261              :     /// - pageserver shutdown (freeze_and_flush == true)
    3262              :     /// - detach + ignore (freeze_and_flush == false)
    3263              :     ///
    3264              :     /// This will attempt to shutdown even if tenant is broken.
    3265              :     ///
    3266              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3267              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3268              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3269              :     /// the ongoing shutdown.
    3270            6 :     async fn shutdown(
    3271            6 :         &self,
    3272            6 :         shutdown_progress: completion::Barrier,
    3273            6 :         shutdown_mode: timeline::ShutdownMode,
    3274            6 :     ) -> Result<(), completion::Barrier> {
    3275            6 :         span::debug_assert_current_span_has_tenant_id();
    3276              : 
    3277              :         // Set tenant (and its timlines) to Stoppping state.
    3278              :         //
    3279              :         // Since we can only transition into Stopping state after activation is complete,
    3280              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3281              :         //
    3282              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3283              :         // 1. Lock out any new requests to the tenants.
    3284              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3285              :         // 3. Signal cancellation for other tenant background loops.
    3286              :         // 4. ???
    3287              :         //
    3288              :         // The waiting for the cancellation is not done uniformly.
    3289              :         // We certainly wait for WAL receivers to shut down.
    3290              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3291              :         // But the tenant background loops are joined-on in our caller.
    3292              :         // It's mesed up.
    3293              :         // we just ignore the failure to stop
    3294              : 
    3295              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3296              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3297              :         // is very slow.
    3298            6 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3299            0 :             self.cancel.cancel();
    3300            0 : 
    3301            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3302            0 :             // are children of ours, so their flush loops will have shut down already
    3303            0 :             timeline::ShutdownMode::Hard
    3304              :         } else {
    3305            6 :             shutdown_mode
    3306              :         };
    3307              : 
    3308            6 :         match self.set_stopping(shutdown_progress, false, false).await {
    3309            6 :             Ok(()) => {}
    3310            0 :             Err(SetStoppingError::Broken) => {
    3311            0 :                 // assume that this is acceptable
    3312            0 :             }
    3313            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3314            0 :                 // give caller the option to wait for this this shutdown
    3315            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3316            0 :                 return Err(other);
    3317              :             }
    3318              :         };
    3319              : 
    3320            6 :         let mut js = tokio::task::JoinSet::new();
    3321            6 :         {
    3322            6 :             let timelines = self.timelines.lock().unwrap();
    3323            6 :             timelines.values().for_each(|timeline| {
    3324            6 :                 let timeline = Arc::clone(timeline);
    3325            6 :                 let timeline_id = timeline.timeline_id;
    3326            6 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3327            6 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3328            6 :             });
    3329            6 :         }
    3330            6 :         {
    3331            6 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3332            6 :             timelines_offloaded.values().for_each(|timeline| {
    3333            0 :                 timeline.defuse_for_tenant_drop();
    3334            6 :             });
    3335            6 :         }
    3336            6 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3337            6 :         tracing::info!("Waiting for timelines...");
    3338           12 :         while let Some(res) = js.join_next().await {
    3339            0 :             match res {
    3340            6 :                 Ok(()) => {}
    3341            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3342            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3343            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3344              :             }
    3345              :         }
    3346              : 
    3347            6 :         if let ShutdownMode::Reload = shutdown_mode {
    3348            0 :             tracing::info!("Flushing deletion queue");
    3349            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3350            0 :                 match e {
    3351            0 :                     DeletionQueueError::ShuttingDown => {
    3352            0 :                         // This is the only error we expect for now. In the future, if more error
    3353            0 :                         // variants are added, we should handle them here.
    3354            0 :                     }
    3355              :                 }
    3356            0 :             }
    3357            6 :         }
    3358              : 
    3359              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3360              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3361            6 :         tracing::debug!("Cancelling CancellationToken");
    3362            6 :         self.cancel.cancel();
    3363            6 : 
    3364            6 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3365            6 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3366            6 :         //
    3367            6 :         // this will additionally shutdown and await all timeline tasks.
    3368            6 :         tracing::debug!("Waiting for tasks...");
    3369            6 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3370              : 
    3371            6 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3372            6 :             walredo_mgr.shutdown().await;
    3373            0 :         }
    3374              : 
    3375              :         // Wait for any in-flight operations to complete
    3376            6 :         self.gate.close().await;
    3377              : 
    3378            6 :         remove_tenant_metrics(&self.tenant_shard_id);
    3379            6 : 
    3380            6 :         Ok(())
    3381            6 :     }
    3382              : 
    3383              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3384              :     ///
    3385              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3386              :     ///
    3387              :     /// This function is not cancel-safe!
    3388              :     ///
    3389              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3390              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3391            6 :     async fn set_stopping(
    3392            6 :         &self,
    3393            6 :         progress: completion::Barrier,
    3394            6 :         _allow_transition_from_loading: bool,
    3395            6 :         allow_transition_from_attaching: bool,
    3396            6 :     ) -> Result<(), SetStoppingError> {
    3397            6 :         let mut rx = self.state.subscribe();
    3398            6 : 
    3399            6 :         // cannot stop before we're done activating, so wait out until we're done activating
    3400            6 :         rx.wait_for(|state| match state {
    3401            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3402              :             TenantState::Activating(_) | TenantState::Attaching => {
    3403            0 :                 info!(
    3404            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3405            0 :                     <&'static str>::from(state)
    3406              :                 );
    3407            0 :                 false
    3408              :             }
    3409            6 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3410            6 :         })
    3411            6 :         .await
    3412            6 :         .expect("cannot drop self.state while on a &self method");
    3413            6 : 
    3414            6 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3415            6 :         let mut err = None;
    3416            6 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3417              :             TenantState::Activating(_) => {
    3418            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3419              :             }
    3420              :             TenantState::Attaching => {
    3421            0 :                 if !allow_transition_from_attaching {
    3422            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3423            0 :                 };
    3424            0 :                 *current_state = TenantState::Stopping { progress };
    3425            0 :                 true
    3426              :             }
    3427              :             TenantState::Active => {
    3428              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3429              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3430              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3431            6 :                 *current_state = TenantState::Stopping { progress };
    3432            6 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3433            6 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3434            6 :                 true
    3435              :             }
    3436            0 :             TenantState::Broken { reason, .. } => {
    3437            0 :                 info!(
    3438            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3439              :                 );
    3440            0 :                 err = Some(SetStoppingError::Broken);
    3441            0 :                 false
    3442              :             }
    3443            0 :             TenantState::Stopping { progress } => {
    3444            0 :                 info!("Tenant is already in Stopping state");
    3445            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3446            0 :                 false
    3447              :             }
    3448            6 :         });
    3449            6 :         match (stopping, err) {
    3450            6 :             (true, None) => {} // continue
    3451            0 :             (false, Some(err)) => return Err(err),
    3452            0 :             (true, Some(_)) => unreachable!(
    3453            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3454            0 :             ),
    3455            0 :             (false, None) => unreachable!(
    3456            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3457            0 :             ),
    3458              :         }
    3459              : 
    3460            6 :         let timelines_accessor = self.timelines.lock().unwrap();
    3461            6 :         let not_broken_timelines = timelines_accessor
    3462            6 :             .values()
    3463            6 :             .filter(|timeline| !timeline.is_broken());
    3464           12 :         for timeline in not_broken_timelines {
    3465            6 :             timeline.set_state(TimelineState::Stopping);
    3466            6 :         }
    3467            6 :         Ok(())
    3468            6 :     }
    3469              : 
    3470              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3471              :     /// `remove_tenant_from_memory`
    3472              :     ///
    3473              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3474              :     ///
    3475              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3476            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3477            0 :         let mut rx = self.state.subscribe();
    3478            0 : 
    3479            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3480            0 :         // So, wait until it's done.
    3481            0 :         rx.wait_for(|state| match state {
    3482              :             TenantState::Activating(_) | TenantState::Attaching => {
    3483            0 :                 info!(
    3484            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3485            0 :                     <&'static str>::from(state)
    3486              :                 );
    3487            0 :                 false
    3488              :             }
    3489            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3490            0 :         })
    3491            0 :         .await
    3492            0 :         .expect("cannot drop self.state while on a &self method");
    3493            0 : 
    3494            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3495            0 :         self.set_broken_no_wait(reason)
    3496            0 :     }
    3497              : 
    3498            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3499            0 :         let reason = reason.to_string();
    3500            0 :         self.state.send_modify(|current_state| {
    3501            0 :             match *current_state {
    3502              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3503            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3504              :                 }
    3505              :                 TenantState::Active => {
    3506            0 :                     if cfg!(feature = "testing") {
    3507            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3508            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3509              :                     } else {
    3510            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3511              :                     }
    3512              :                 }
    3513              :                 TenantState::Broken { .. } => {
    3514            0 :                     warn!("Tenant is already in Broken state");
    3515              :                 }
    3516              :                 // This is the only "expected" path, any other path is a bug.
    3517              :                 TenantState::Stopping { .. } => {
    3518            0 :                     warn!(
    3519            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3520              :                         reason
    3521              :                     );
    3522            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3523              :                 }
    3524              :            }
    3525            0 :         });
    3526            0 :     }
    3527              : 
    3528            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3529            0 :         self.state.subscribe()
    3530            0 :     }
    3531              : 
    3532              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3533              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3534            0 :     pub(crate) fn activate_now(&self) {
    3535            0 :         self.activate_now_sem.add_permits(1);
    3536            0 :     }
    3537              : 
    3538            0 :     pub(crate) async fn wait_to_become_active(
    3539            0 :         &self,
    3540            0 :         timeout: Duration,
    3541            0 :     ) -> Result<(), GetActiveTenantError> {
    3542            0 :         let mut receiver = self.state.subscribe();
    3543              :         loop {
    3544            0 :             let current_state = receiver.borrow_and_update().clone();
    3545            0 :             match current_state {
    3546              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3547              :                     // in these states, there's a chance that we can reach ::Active
    3548            0 :                     self.activate_now();
    3549            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3550            0 :                         Ok(r) => {
    3551            0 :                             r.map_err(
    3552            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3553              :                                 // Tenant existed but was dropped: report it as non-existent
    3554            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3555            0 :                         )?
    3556              :                         }
    3557              :                         Err(TimeoutCancellableError::Cancelled) => {
    3558            0 :                             return Err(GetActiveTenantError::Cancelled);
    3559              :                         }
    3560              :                         Err(TimeoutCancellableError::Timeout) => {
    3561            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3562            0 :                                 latest_state: Some(self.current_state()),
    3563            0 :                                 wait_time: timeout,
    3564            0 :                             });
    3565              :                         }
    3566              :                     }
    3567              :                 }
    3568              :                 TenantState::Active { .. } => {
    3569            0 :                     return Ok(());
    3570              :                 }
    3571            0 :                 TenantState::Broken { reason, .. } => {
    3572            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3573            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3574            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3575              :                 }
    3576              :                 TenantState::Stopping { .. } => {
    3577              :                     // There's no chance the tenant can transition back into ::Active
    3578            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3579              :                 }
    3580              :             }
    3581              :         }
    3582            0 :     }
    3583              : 
    3584            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3585            0 :         self.tenant_conf.load().location.attach_mode
    3586            0 :     }
    3587              : 
    3588              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3589              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3590              :     /// rare external API calls, like a reconciliation at startup.
    3591            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3592            0 :         let conf = self.tenant_conf.load();
    3593              : 
    3594            0 :         let location_config_mode = match conf.location.attach_mode {
    3595            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3596            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3597            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3598              :         };
    3599              : 
    3600              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3601            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3602            0 : 
    3603            0 :         models::LocationConfig {
    3604            0 :             mode: location_config_mode,
    3605            0 :             generation: self.generation.into(),
    3606            0 :             secondary_conf: None,
    3607            0 :             shard_number: self.shard_identity.number.0,
    3608            0 :             shard_count: self.shard_identity.count.literal(),
    3609            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3610            0 :             tenant_conf: tenant_config,
    3611            0 :         }
    3612            0 :     }
    3613              : 
    3614            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3615            0 :         &self.tenant_shard_id
    3616            0 :     }
    3617              : 
    3618            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3619            0 :         self.shard_identity.stripe_size
    3620            0 :     }
    3621              : 
    3622            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3623            0 :         self.generation
    3624            0 :     }
    3625              : 
    3626              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3627              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3628              :     /// resetting this tenant to a valid state if we fail.
    3629            0 :     pub(crate) async fn split_prepare(
    3630            0 :         &self,
    3631            0 :         child_shards: &Vec<TenantShardId>,
    3632            0 :     ) -> anyhow::Result<()> {
    3633            0 :         let (timelines, offloaded) = {
    3634            0 :             let timelines = self.timelines.lock().unwrap();
    3635            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3636            0 :             (timelines.clone(), offloaded.clone())
    3637            0 :         };
    3638            0 :         let timelines_iter = timelines
    3639            0 :             .values()
    3640            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3641            0 :             .chain(
    3642            0 :                 offloaded
    3643            0 :                     .values()
    3644            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3645            0 :             );
    3646            0 :         for timeline in timelines_iter {
    3647              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3648              :             // to ensure that they do not start a split if currently in the process of doing these.
    3649              : 
    3650            0 :             let timeline_id = timeline.timeline_id();
    3651              : 
    3652            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3653              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3654              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3655              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3656            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3657            0 :                 timeline
    3658            0 :                     .remote_client
    3659            0 :                     .schedule_index_upload_for_file_changes()?;
    3660            0 :                 timeline.remote_client.wait_completion().await?;
    3661            0 :             }
    3662              : 
    3663            0 :             let remote_client = match timeline {
    3664            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3665            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3666            0 :                     let remote_client = self
    3667            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3668            0 :                     Arc::new(remote_client)
    3669              :                 }
    3670              :             };
    3671              : 
    3672              :             // Shut down the timeline's remote client: this means that the indices we write
    3673              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3674            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3675            0 :             remote_client.shutdown().await;
    3676              : 
    3677              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3678              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3679              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3680              :             // we use here really is the remotely persistent one).
    3681            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3682            0 :             let result = remote_client
    3683            0 :                 .download_index_file(&self.cancel)
    3684            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))
    3685            0 :                 .await?;
    3686            0 :             let index_part = match result {
    3687              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3688            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3689              :                 }
    3690            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3691              :             };
    3692              : 
    3693            0 :             for child_shard in child_shards {
    3694            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3695            0 :                 upload_index_part(
    3696            0 :                     &self.remote_storage,
    3697            0 :                     child_shard,
    3698            0 :                     &timeline_id,
    3699            0 :                     self.generation,
    3700            0 :                     &index_part,
    3701            0 :                     &self.cancel,
    3702            0 :                 )
    3703            0 :                 .await?;
    3704              :             }
    3705              :         }
    3706              : 
    3707            0 :         let tenant_manifest = self.build_tenant_manifest();
    3708            0 :         for child_shard in child_shards {
    3709            0 :             tracing::info!(
    3710            0 :                 "Uploading tenant manifest for child {}",
    3711            0 :                 child_shard.to_index()
    3712              :             );
    3713            0 :             upload_tenant_manifest(
    3714            0 :                 &self.remote_storage,
    3715            0 :                 child_shard,
    3716            0 :                 self.generation,
    3717            0 :                 &tenant_manifest,
    3718            0 :                 &self.cancel,
    3719            0 :             )
    3720            0 :             .await?;
    3721              :         }
    3722              : 
    3723            0 :         Ok(())
    3724            0 :     }
    3725              : 
    3726            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3727            0 :         let mut result = TopTenantShardItem {
    3728            0 :             id: self.tenant_shard_id,
    3729            0 :             resident_size: 0,
    3730            0 :             physical_size: 0,
    3731            0 :             max_logical_size: 0,
    3732            0 :         };
    3733              : 
    3734            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3735            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3736            0 : 
    3737            0 :             result.physical_size += timeline
    3738            0 :                 .remote_client
    3739            0 :                 .metrics
    3740            0 :                 .remote_physical_size_gauge
    3741            0 :                 .get();
    3742            0 :             result.max_logical_size = std::cmp::max(
    3743            0 :                 result.max_logical_size,
    3744            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3745            0 :             );
    3746            0 :         }
    3747              : 
    3748            0 :         result
    3749            0 :     }
    3750              : }
    3751              : 
    3752              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3753              : /// perform a topological sort, so that the parent of each timeline comes
    3754              : /// before the children.
    3755              : /// E extracts the ancestor from T
    3756              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3757          192 : fn tree_sort_timelines<T, E>(
    3758          192 :     timelines: HashMap<TimelineId, T>,
    3759          192 :     extractor: E,
    3760          192 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3761          192 : where
    3762          192 :     E: Fn(&T) -> Option<TimelineId>,
    3763          192 : {
    3764          192 :     let mut result = Vec::with_capacity(timelines.len());
    3765          192 : 
    3766          192 :     let mut now = Vec::with_capacity(timelines.len());
    3767          192 :     // (ancestor, children)
    3768          192 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3769          192 :         HashMap::with_capacity(timelines.len());
    3770              : 
    3771          198 :     for (timeline_id, value) in timelines {
    3772            6 :         if let Some(ancestor_id) = extractor(&value) {
    3773            2 :             let children = later.entry(ancestor_id).or_default();
    3774            2 :             children.push((timeline_id, value));
    3775            4 :         } else {
    3776            4 :             now.push((timeline_id, value));
    3777            4 :         }
    3778              :     }
    3779              : 
    3780          198 :     while let Some((timeline_id, metadata)) = now.pop() {
    3781            6 :         result.push((timeline_id, metadata));
    3782              :         // All children of this can be loaded now
    3783            6 :         if let Some(mut children) = later.remove(&timeline_id) {
    3784            2 :             now.append(&mut children);
    3785            4 :         }
    3786              :     }
    3787              : 
    3788              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3789          192 :     if !later.is_empty() {
    3790            0 :         for (missing_id, orphan_ids) in later {
    3791            0 :             for (orphan_id, _) in orphan_ids {
    3792            0 :                 error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
    3793              :             }
    3794              :         }
    3795            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3796          192 :     }
    3797          192 : 
    3798          192 :     Ok(result)
    3799          192 : }
    3800              : 
    3801              : enum ActivateTimelineArgs {
    3802              :     Yes {
    3803              :         broker_client: storage_broker::BrokerClientChannel,
    3804              :     },
    3805              :     No,
    3806              : }
    3807              : 
    3808              : impl Tenant {
    3809            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3810            0 :         self.tenant_conf.load().tenant_conf.clone()
    3811            0 :     }
    3812              : 
    3813            0 :     pub fn effective_config(&self) -> TenantConf {
    3814            0 :         self.tenant_specific_overrides()
    3815            0 :             .merge(self.conf.default_tenant_conf.clone())
    3816            0 :     }
    3817              : 
    3818            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3819            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3820            0 :         tenant_conf
    3821            0 :             .checkpoint_distance
    3822            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3823            0 :     }
    3824              : 
    3825            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3826            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3827            0 :         tenant_conf
    3828            0 :             .checkpoint_timeout
    3829            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3830            0 :     }
    3831              : 
    3832            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3833            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3834            0 :         tenant_conf
    3835            0 :             .compaction_target_size
    3836            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3837            0 :     }
    3838              : 
    3839            0 :     pub fn get_compaction_period(&self) -> Duration {
    3840            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3841            0 :         tenant_conf
    3842            0 :             .compaction_period
    3843            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3844            0 :     }
    3845              : 
    3846            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3847            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3848            0 :         tenant_conf
    3849            0 :             .compaction_threshold
    3850            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3851            0 :     }
    3852              : 
    3853            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3854            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3855            0 :         tenant_conf
    3856            0 :             .gc_horizon
    3857            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3858            0 :     }
    3859              : 
    3860            0 :     pub fn get_gc_period(&self) -> Duration {
    3861            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3862            0 :         tenant_conf
    3863            0 :             .gc_period
    3864            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3865            0 :     }
    3866              : 
    3867            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3868            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3869            0 :         tenant_conf
    3870            0 :             .image_creation_threshold
    3871            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3872            0 :     }
    3873              : 
    3874            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3875            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3876            0 :         tenant_conf
    3877            0 :             .pitr_interval
    3878            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3879            0 :     }
    3880              : 
    3881            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3882            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3883            0 :         tenant_conf
    3884            0 :             .min_resident_size_override
    3885            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3886            0 :     }
    3887              : 
    3888            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3889            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3890            0 :         let heatmap_period = tenant_conf
    3891            0 :             .heatmap_period
    3892            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    3893            0 :         if heatmap_period.is_zero() {
    3894            0 :             None
    3895              :         } else {
    3896            0 :             Some(heatmap_period)
    3897              :         }
    3898            0 :     }
    3899              : 
    3900            4 :     pub fn get_lsn_lease_length(&self) -> Duration {
    3901            4 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3902            4 :         tenant_conf
    3903            4 :             .lsn_lease_length
    3904            4 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    3905            4 :     }
    3906              : 
    3907              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    3908            2 :     fn build_tenant_manifest(&self) -> TenantManifest {
    3909            2 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3910            2 : 
    3911            2 :         let mut timeline_manifests = timelines_offloaded
    3912            2 :             .iter()
    3913            2 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    3914            2 :             .collect::<Vec<_>>();
    3915            2 :         // Sort the manifests so that our output is deterministic
    3916            2 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    3917            2 : 
    3918            2 :         TenantManifest {
    3919            2 :             version: LATEST_TENANT_MANIFEST_VERSION,
    3920            2 :             offloaded_timelines: timeline_manifests,
    3921            2 :         }
    3922            2 :     }
    3923              : 
    3924            0 :     pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
    3925            0 :         // Use read-copy-update in order to avoid overwriting the location config
    3926            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    3927            0 :         // this race is not possible if both request types come from the storage
    3928            0 :         // controller (as they should!) because an exclusive op lock is required
    3929            0 :         // on the storage controller side.
    3930            0 : 
    3931            0 :         self.tenant_conf.rcu(|inner| {
    3932            0 :             Arc::new(AttachedTenantConf {
    3933            0 :                 tenant_conf: new_tenant_conf.clone(),
    3934            0 :                 location: inner.location,
    3935            0 :                 // Attached location is not changed, no need to update lsn lease deadline.
    3936            0 :                 lsn_lease_deadline: inner.lsn_lease_deadline,
    3937            0 :             })
    3938            0 :         });
    3939            0 : 
    3940            0 :         let updated = self.tenant_conf.load().clone();
    3941            0 : 
    3942            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3943            0 :         // Don't hold self.timelines.lock() during the notifies.
    3944            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3945            0 :         // mutexes in struct Timeline in the future.
    3946            0 :         let timelines = self.list_timelines();
    3947            0 :         for timeline in timelines {
    3948            0 :             timeline.tenant_conf_updated(&updated);
    3949            0 :         }
    3950            0 :     }
    3951              : 
    3952            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    3953            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    3954            0 : 
    3955            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    3956            0 : 
    3957            0 :         self.tenant_conf_updated(&new_tenant_conf);
    3958            0 :         // Don't hold self.timelines.lock() during the notifies.
    3959            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    3960            0 :         // mutexes in struct Timeline in the future.
    3961            0 :         let timelines = self.list_timelines();
    3962            0 :         for timeline in timelines {
    3963            0 :             timeline.tenant_conf_updated(&new_conf);
    3964            0 :         }
    3965            0 :     }
    3966              : 
    3967          192 :     fn get_pagestream_throttle_config(
    3968          192 :         psconf: &'static PageServerConf,
    3969          192 :         overrides: &TenantConfOpt,
    3970          192 :     ) -> throttle::Config {
    3971          192 :         overrides
    3972          192 :             .timeline_get_throttle
    3973          192 :             .clone()
    3974          192 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    3975          192 :     }
    3976              : 
    3977            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    3978            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    3979            0 :         self.pagestream_throttle.reconfigure(conf)
    3980            0 :     }
    3981              : 
    3982              :     /// Helper function to create a new Timeline struct.
    3983              :     ///
    3984              :     /// The returned Timeline is in Loading state. The caller is responsible for
    3985              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    3986              :     /// map.
    3987              :     ///
    3988              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    3989              :     /// and we might not have the ancestor present anymore which is fine for to be
    3990              :     /// deleted timelines.
    3991              :     #[allow(clippy::too_many_arguments)]
    3992          418 :     fn create_timeline_struct(
    3993          418 :         &self,
    3994          418 :         new_timeline_id: TimelineId,
    3995          418 :         new_metadata: &TimelineMetadata,
    3996          418 :         ancestor: Option<Arc<Timeline>>,
    3997          418 :         resources: TimelineResources,
    3998          418 :         cause: CreateTimelineCause,
    3999          418 :         create_idempotency: CreateTimelineIdempotency,
    4000          418 :     ) -> anyhow::Result<Arc<Timeline>> {
    4001          418 :         let state = match cause {
    4002              :             CreateTimelineCause::Load => {
    4003          418 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4004          418 :                 anyhow::ensure!(
    4005          418 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4006            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4007              :                 );
    4008          418 :                 TimelineState::Loading
    4009              :             }
    4010            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4011              :         };
    4012              : 
    4013          418 :         let pg_version = new_metadata.pg_version();
    4014          418 : 
    4015          418 :         let timeline = Timeline::new(
    4016          418 :             self.conf,
    4017          418 :             Arc::clone(&self.tenant_conf),
    4018          418 :             new_metadata,
    4019          418 :             ancestor,
    4020          418 :             new_timeline_id,
    4021          418 :             self.tenant_shard_id,
    4022          418 :             self.generation,
    4023          418 :             self.shard_identity,
    4024          418 :             self.walredo_mgr.clone(),
    4025          418 :             resources,
    4026          418 :             pg_version,
    4027          418 :             state,
    4028          418 :             self.attach_wal_lag_cooldown.clone(),
    4029          418 :             create_idempotency,
    4030          418 :             self.cancel.child_token(),
    4031          418 :         );
    4032          418 : 
    4033          418 :         Ok(timeline)
    4034          418 :     }
    4035              : 
    4036              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4037              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4038              :     #[allow(clippy::too_many_arguments)]
    4039          192 :     fn new(
    4040          192 :         state: TenantState,
    4041          192 :         conf: &'static PageServerConf,
    4042          192 :         attached_conf: AttachedTenantConf,
    4043          192 :         shard_identity: ShardIdentity,
    4044          192 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4045          192 :         tenant_shard_id: TenantShardId,
    4046          192 :         remote_storage: GenericRemoteStorage,
    4047          192 :         deletion_queue_client: DeletionQueueClient,
    4048          192 :         l0_flush_global_state: L0FlushGlobalState,
    4049          192 :     ) -> Tenant {
    4050          192 :         debug_assert!(
    4051          192 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4052              :         );
    4053              : 
    4054          192 :         let (state, mut rx) = watch::channel(state);
    4055          192 : 
    4056          192 :         tokio::spawn(async move {
    4057          192 :             // reflect tenant state in metrics:
    4058          192 :             // - global per tenant state: TENANT_STATE_METRIC
    4059          192 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4060          192 :             //
    4061          192 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4062          192 :             // alerting.
    4063          192 : 
    4064          192 :             let tid = tenant_shard_id.to_string();
    4065          192 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4066          192 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4067              : 
    4068          384 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4069          384 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4070          384 :             }
    4071              : 
    4072          192 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4073          192 : 
    4074          192 :             let is_broken = tuple.1;
    4075          192 :             let mut counted_broken = if is_broken {
    4076              :                 // add the id to the set right away, there should not be any updates on the channel
    4077              :                 // after before tenant is removed, if ever
    4078            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4079            0 :                 true
    4080              :             } else {
    4081          192 :                 false
    4082              :             };
    4083              : 
    4084              :             loop {
    4085          384 :                 let labels = &tuple.0;
    4086          384 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4087          384 :                 current.inc();
    4088          384 : 
    4089          384 :                 if rx.changed().await.is_err() {
    4090              :                     // tenant has been dropped
    4091           14 :                     current.dec();
    4092           14 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4093           14 :                     break;
    4094          192 :                 }
    4095          192 : 
    4096          192 :                 current.dec();
    4097          192 :                 tuple = inspect_state(&rx.borrow_and_update());
    4098          192 : 
    4099          192 :                 let is_broken = tuple.1;
    4100          192 :                 if is_broken && !counted_broken {
    4101            0 :                     counted_broken = true;
    4102            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4103            0 :                     // access
    4104            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4105          192 :                 }
    4106              :             }
    4107          192 :         });
    4108          192 : 
    4109          192 :         Tenant {
    4110          192 :             tenant_shard_id,
    4111          192 :             shard_identity,
    4112          192 :             generation: attached_conf.location.generation,
    4113          192 :             conf,
    4114          192 :             // using now here is good enough approximation to catch tenants with really long
    4115          192 :             // activation times.
    4116          192 :             constructed_at: Instant::now(),
    4117          192 :             timelines: Mutex::new(HashMap::new()),
    4118          192 :             timelines_creating: Mutex::new(HashSet::new()),
    4119          192 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4120          192 :             tenant_manifest_upload: Default::default(),
    4121          192 :             gc_cs: tokio::sync::Mutex::new(()),
    4122          192 :             walredo_mgr,
    4123          192 :             remote_storage,
    4124          192 :             deletion_queue_client,
    4125          192 :             state,
    4126          192 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4127          192 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4128          192 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4129          192 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4130          192 :                 format!("compaction-{tenant_shard_id}"),
    4131          192 :                 5,
    4132          192 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4133          192 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4134          192 :                 // use an extremely long backoff.
    4135          192 :                 Some(Duration::from_secs(3600 * 24)),
    4136          192 :             )),
    4137          192 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4138          192 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4139          192 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4140          192 :             cancel: CancellationToken::default(),
    4141          192 :             gate: Gate::default(),
    4142          192 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4143          192 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4144          192 :                 crate::metrics::tenant_throttling::Metrics::new(&tenant_shard_id),
    4145          192 :             )),
    4146          192 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4147          192 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4148          192 :             gc_block: Default::default(),
    4149          192 :             l0_flush_global_state,
    4150          192 :         }
    4151          192 :     }
    4152              : 
    4153              :     /// Locate and load config
    4154            0 :     pub(super) fn load_tenant_config(
    4155            0 :         conf: &'static PageServerConf,
    4156            0 :         tenant_shard_id: &TenantShardId,
    4157            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4158            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4159            0 : 
    4160            0 :         info!("loading tenant configuration from {config_path}");
    4161              : 
    4162              :         // load and parse file
    4163            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4164            0 :             match e.kind() {
    4165              :                 std::io::ErrorKind::NotFound => {
    4166              :                     // The config should almost always exist for a tenant directory:
    4167              :                     //  - When attaching a tenant, the config is the first thing we write
    4168              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4169              :                     //    before deleting contents.
    4170              :                     //
    4171              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4172              :                     // between creating directory and writing config.  Callers should handle that as if the
    4173              :                     // directory didn't exist.
    4174              : 
    4175            0 :                     LoadConfigError::NotFound(config_path)
    4176              :                 }
    4177              :                 _ => {
    4178              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4179              :                     // that we cannot cleanly recover
    4180            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4181              :                 }
    4182              :             }
    4183            0 :         })?;
    4184              : 
    4185            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4186            0 :     }
    4187              : 
    4188            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4189              :     pub(super) async fn persist_tenant_config(
    4190              :         conf: &'static PageServerConf,
    4191              :         tenant_shard_id: &TenantShardId,
    4192              :         location_conf: &LocationConf,
    4193              :     ) -> std::io::Result<()> {
    4194              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4195              : 
    4196              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4197              :     }
    4198              : 
    4199            0 :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4200              :     pub(super) async fn persist_tenant_config_at(
    4201              :         tenant_shard_id: &TenantShardId,
    4202              :         config_path: &Utf8Path,
    4203              :         location_conf: &LocationConf,
    4204              :     ) -> std::io::Result<()> {
    4205              :         debug!("persisting tenantconf to {config_path}");
    4206              : 
    4207              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4208              : #  It is read in case of pageserver restart.
    4209              : "#
    4210              :         .to_string();
    4211              : 
    4212            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4213            0 :             Err(std::io::Error::new(
    4214            0 :                 std::io::ErrorKind::Other,
    4215            0 :                 "tenant-config-before-write",
    4216            0 :             ))
    4217            0 :         });
    4218              : 
    4219              :         // Convert the config to a toml file.
    4220              :         conf_content +=
    4221              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4222              : 
    4223              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4224              : 
    4225              :         let conf_content = conf_content.into_bytes();
    4226              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4227              :     }
    4228              : 
    4229              :     //
    4230              :     // How garbage collection works:
    4231              :     //
    4232              :     //                    +--bar------------->
    4233              :     //                   /
    4234              :     //             +----+-----foo---------------->
    4235              :     //            /
    4236              :     // ----main--+-------------------------->
    4237              :     //                \
    4238              :     //                 +-----baz-------->
    4239              :     //
    4240              :     //
    4241              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4242              :     //    `gc_infos` are being refreshed
    4243              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4244              :     //    all the points where other timelines have been branched off.
    4245              :     //    We will refrain from removing page versions at those LSNs.
    4246              :     // 3. For each timeline, scan all layer files on the timeline.
    4247              :     //    Remove all files for which a newer file exists and which
    4248              :     //    don't cover any branch point LSNs.
    4249              :     //
    4250              :     // TODO:
    4251              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4252              :     //   don't need to keep that in the parent anymore. But currently
    4253              :     //   we do.
    4254            4 :     async fn gc_iteration_internal(
    4255            4 :         &self,
    4256            4 :         target_timeline_id: Option<TimelineId>,
    4257            4 :         horizon: u64,
    4258            4 :         pitr: Duration,
    4259            4 :         cancel: &CancellationToken,
    4260            4 :         ctx: &RequestContext,
    4261            4 :     ) -> Result<GcResult, GcError> {
    4262            4 :         let mut totals: GcResult = Default::default();
    4263            4 :         let now = Instant::now();
    4264              : 
    4265            4 :         let gc_timelines = self
    4266            4 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4267            4 :             .await?;
    4268              : 
    4269            4 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4270              : 
    4271              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4272            4 :         if !gc_timelines.is_empty() {
    4273            4 :             info!("{} timelines need GC", gc_timelines.len());
    4274              :         } else {
    4275            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4276              :         }
    4277              : 
    4278              :         // Perform GC for each timeline.
    4279              :         //
    4280              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4281              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4282              :         // with branch creation.
    4283              :         //
    4284              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4285              :         // creation task can run concurrently with timeline's GC iteration.
    4286            8 :         for timeline in gc_timelines {
    4287            4 :             if cancel.is_cancelled() {
    4288              :                 // We were requested to shut down. Stop and return with the progress we
    4289              :                 // made.
    4290            0 :                 break;
    4291            4 :             }
    4292            4 :             let result = match timeline.gc().await {
    4293              :                 Err(GcError::TimelineCancelled) => {
    4294            0 :                     if target_timeline_id.is_some() {
    4295              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4296            0 :                         return Err(GcError::TimelineCancelled);
    4297              :                     } else {
    4298              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4299              :                         // skip past this and proceed to try GC on other timelines.
    4300            0 :                         continue;
    4301              :                     }
    4302              :                 }
    4303            4 :                 r => r?,
    4304              :             };
    4305            4 :             totals += result;
    4306              :         }
    4307              : 
    4308            4 :         totals.elapsed = now.elapsed();
    4309            4 :         Ok(totals)
    4310            4 :     }
    4311              : 
    4312              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4313              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4314              :     /// [`Tenant::get_gc_horizon`].
    4315              :     ///
    4316              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4317            0 :     pub(crate) async fn refresh_gc_info(
    4318            0 :         &self,
    4319            0 :         cancel: &CancellationToken,
    4320            0 :         ctx: &RequestContext,
    4321            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4322            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4323            0 :         // might be that these configuration values get applied faster than what it was previously,
    4324            0 :         // since these were only read from the gc task.
    4325            0 :         let horizon = self.get_gc_horizon();
    4326            0 :         let pitr = self.get_pitr_interval();
    4327            0 : 
    4328            0 :         // refresh all timelines
    4329            0 :         let target_timeline_id = None;
    4330            0 : 
    4331            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4332            0 :             .await
    4333            0 :     }
    4334              : 
    4335              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4336              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4337              :     ///
    4338              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4339            0 :     fn initialize_gc_info(
    4340            0 :         &self,
    4341            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4342            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4343            0 :         restrict_to_timeline: Option<TimelineId>,
    4344            0 :     ) {
    4345            0 :         if restrict_to_timeline.is_none() {
    4346              :             // This function must be called before activation: after activation timeline create/delete operations
    4347              :             // might happen, and this function is not safe to run concurrently with those.
    4348            0 :             assert!(!self.is_active());
    4349            0 :         }
    4350              : 
    4351              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4352              :         // the branch point where it was created.
    4353            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4354            0 :             BTreeMap::new();
    4355            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4356            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4357            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4358            0 :                 ancestor_children.push((
    4359            0 :                     timeline_entry.get_ancestor_lsn(),
    4360            0 :                     *timeline_id,
    4361            0 :                     MaybeOffloaded::No,
    4362            0 :                 ));
    4363            0 :             }
    4364            0 :         });
    4365            0 :         timelines_offloaded
    4366            0 :             .iter()
    4367            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4368            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4369            0 :                     return;
    4370              :                 };
    4371            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4372            0 :                     return;
    4373              :                 };
    4374            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4375            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4376            0 :             });
    4377            0 : 
    4378            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4379            0 :         let horizon = self.get_gc_horizon();
    4380              : 
    4381              :         // Populate each timeline's GcInfo with information about its child branches
    4382            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4383            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4384              :         } else {
    4385            0 :             itertools::Either::Right(timelines.values())
    4386              :         };
    4387            0 :         for timeline in timelines_to_write {
    4388            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4389            0 :                 .remove(&timeline.timeline_id)
    4390            0 :                 .unwrap_or_default();
    4391            0 : 
    4392            0 :             branchpoints.sort_by_key(|b| b.0);
    4393            0 : 
    4394            0 :             let mut target = timeline.gc_info.write().unwrap();
    4395            0 : 
    4396            0 :             target.retain_lsns = branchpoints;
    4397            0 : 
    4398            0 :             let space_cutoff = timeline
    4399            0 :                 .get_last_record_lsn()
    4400            0 :                 .checked_sub(horizon)
    4401            0 :                 .unwrap_or(Lsn(0));
    4402            0 : 
    4403            0 :             target.cutoffs = GcCutoffs {
    4404            0 :                 space: space_cutoff,
    4405            0 :                 time: Lsn::INVALID,
    4406            0 :             };
    4407            0 :         }
    4408            0 :     }
    4409              : 
    4410            4 :     async fn refresh_gc_info_internal(
    4411            4 :         &self,
    4412            4 :         target_timeline_id: Option<TimelineId>,
    4413            4 :         horizon: u64,
    4414            4 :         pitr: Duration,
    4415            4 :         cancel: &CancellationToken,
    4416            4 :         ctx: &RequestContext,
    4417            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4418            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4419            4 :         // currently visible timelines.
    4420            4 :         let timelines = self
    4421            4 :             .timelines
    4422            4 :             .lock()
    4423            4 :             .unwrap()
    4424            4 :             .values()
    4425            4 :             .filter(|tl| match target_timeline_id.as_ref() {
    4426            4 :                 Some(target) => &tl.timeline_id == target,
    4427            0 :                 None => true,
    4428            4 :             })
    4429            4 :             .cloned()
    4430            4 :             .collect::<Vec<_>>();
    4431            4 : 
    4432            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4433              :             // We were to act on a particular timeline and it wasn't found
    4434            0 :             return Err(GcError::TimelineNotFound);
    4435            4 :         }
    4436            4 : 
    4437            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4438            4 :             HashMap::with_capacity(timelines.len());
    4439              : 
    4440            4 :         for timeline in timelines.iter() {
    4441            4 :             let cutoff = timeline
    4442            4 :                 .get_last_record_lsn()
    4443            4 :                 .checked_sub(horizon)
    4444            4 :                 .unwrap_or(Lsn(0));
    4445              : 
    4446            4 :             let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
    4447            4 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4448            4 :             assert!(old.is_none());
    4449              :         }
    4450              : 
    4451            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    4452            0 :             return Err(GcError::TenantCancelled);
    4453            4 :         }
    4454              : 
    4455              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4456              :         // because that will stall branch creation.
    4457            4 :         let gc_cs = self.gc_cs.lock().await;
    4458              : 
    4459              :         // Ok, we now know all the branch points.
    4460              :         // Update the GC information for each timeline.
    4461            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4462            8 :         for timeline in timelines {
    4463              :             // We filtered the timeline list above
    4464            4 :             if let Some(target_timeline_id) = target_timeline_id {
    4465            4 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4466            0 :             }
    4467              : 
    4468              :             {
    4469            4 :                 let mut target = timeline.gc_info.write().unwrap();
    4470            4 : 
    4471            4 :                 // Cull any expired leases
    4472            4 :                 let now = SystemTime::now();
    4473            6 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4474            4 : 
    4475            4 :                 timeline
    4476            4 :                     .metrics
    4477            4 :                     .valid_lsn_lease_count_gauge
    4478            4 :                     .set(target.leases.len() as u64);
    4479              : 
    4480              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4481            4 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4482            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4483            0 :                         target.within_ancestor_pitr =
    4484            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4485            0 :                     }
    4486            4 :                 }
    4487              : 
    4488              :                 // Update metrics that depend on GC state
    4489            4 :                 timeline
    4490            4 :                     .metrics
    4491            4 :                     .archival_size
    4492            4 :                     .set(if target.within_ancestor_pitr {
    4493            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4494              :                     } else {
    4495            4 :                         0
    4496              :                     });
    4497            4 :                 timeline.metrics.pitr_history_size.set(
    4498            4 :                     timeline
    4499            4 :                         .get_last_record_lsn()
    4500            4 :                         .checked_sub(target.cutoffs.time)
    4501            4 :                         .unwrap_or(Lsn(0))
    4502            4 :                         .0,
    4503            4 :                 );
    4504              : 
    4505              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4506              :                 // - this timeline was created while we were finding cutoffs
    4507              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4508            4 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4509            4 :                     let original_cutoffs = target.cutoffs.clone();
    4510            4 :                     // GC cutoffs should never go back
    4511            4 :                     target.cutoffs = GcCutoffs {
    4512            4 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4513            4 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4514            4 :                     }
    4515            0 :                 }
    4516              :             }
    4517              : 
    4518            4 :             gc_timelines.push(timeline);
    4519              :         }
    4520            4 :         drop(gc_cs);
    4521            4 :         Ok(gc_timelines)
    4522            4 :     }
    4523              : 
    4524              :     /// A substitute for `branch_timeline` for use in unit tests.
    4525              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4526              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4527              :     /// timeline background tasks are launched, except the flush loop.
    4528              :     #[cfg(test)]
    4529          232 :     async fn branch_timeline_test(
    4530          232 :         self: &Arc<Self>,
    4531          232 :         src_timeline: &Arc<Timeline>,
    4532          232 :         dst_id: TimelineId,
    4533          232 :         ancestor_lsn: Option<Lsn>,
    4534          232 :         ctx: &RequestContext,
    4535          232 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4536          232 :         let tl = self
    4537          232 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4538          232 :             .await?
    4539          228 :             .into_timeline_for_test();
    4540          228 :         tl.set_state(TimelineState::Active);
    4541          228 :         Ok(tl)
    4542          232 :     }
    4543              : 
    4544              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4545              :     #[cfg(test)]
    4546              :     #[allow(clippy::too_many_arguments)]
    4547            6 :     pub async fn branch_timeline_test_with_layers(
    4548            6 :         self: &Arc<Self>,
    4549            6 :         src_timeline: &Arc<Timeline>,
    4550            6 :         dst_id: TimelineId,
    4551            6 :         ancestor_lsn: Option<Lsn>,
    4552            6 :         ctx: &RequestContext,
    4553            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4554            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4555            6 :         end_lsn: Lsn,
    4556            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4557              :         use checks::check_valid_layermap;
    4558              :         use itertools::Itertools;
    4559              : 
    4560            6 :         let tline = self
    4561            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4562            6 :             .await?;
    4563            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4564            6 :             ancestor_lsn
    4565              :         } else {
    4566            0 :             tline.get_last_record_lsn()
    4567              :         };
    4568            6 :         assert!(end_lsn >= ancestor_lsn);
    4569            6 :         tline.force_advance_lsn(end_lsn);
    4570           12 :         for deltas in delta_layer_desc {
    4571            6 :             tline
    4572            6 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4573            6 :                 .await?;
    4574              :         }
    4575           10 :         for (lsn, images) in image_layer_desc {
    4576            4 :             tline
    4577            4 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4578            4 :                 .await?;
    4579              :         }
    4580            6 :         let layer_names = tline
    4581            6 :             .layers
    4582            6 :             .read()
    4583            6 :             .await
    4584            6 :             .layer_map()
    4585            6 :             .unwrap()
    4586            6 :             .iter_historic_layers()
    4587           10 :             .map(|layer| layer.layer_name())
    4588            6 :             .collect_vec();
    4589            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4590            0 :             bail!("invalid layermap: {err}");
    4591            6 :         }
    4592            6 :         Ok(tline)
    4593            6 :     }
    4594              : 
    4595              :     /// Branch an existing timeline.
    4596            0 :     async fn branch_timeline(
    4597            0 :         self: &Arc<Self>,
    4598            0 :         src_timeline: &Arc<Timeline>,
    4599            0 :         dst_id: TimelineId,
    4600            0 :         start_lsn: Option<Lsn>,
    4601            0 :         ctx: &RequestContext,
    4602            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4603            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4604            0 :             .await
    4605            0 :     }
    4606              : 
    4607          232 :     async fn branch_timeline_impl(
    4608          232 :         self: &Arc<Self>,
    4609          232 :         src_timeline: &Arc<Timeline>,
    4610          232 :         dst_id: TimelineId,
    4611          232 :         start_lsn: Option<Lsn>,
    4612          232 :         _ctx: &RequestContext,
    4613          232 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4614          232 :         let src_id = src_timeline.timeline_id;
    4615              : 
    4616              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4617              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4618              :         // valid while we are creating the branch.
    4619          232 :         let _gc_cs = self.gc_cs.lock().await;
    4620              : 
    4621              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4622          232 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4623            2 :             let lsn = src_timeline.get_last_record_lsn();
    4624            2 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4625            2 :             lsn
    4626          232 :         });
    4627              : 
    4628              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4629          232 :         let timeline_create_guard = match self
    4630          232 :             .start_creating_timeline(
    4631          232 :                 dst_id,
    4632          232 :                 CreateTimelineIdempotency::Branch {
    4633          232 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4634          232 :                     ancestor_start_lsn: start_lsn,
    4635          232 :                 },
    4636          232 :             )
    4637          232 :             .await?
    4638              :         {
    4639          232 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4640            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4641            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4642              :             }
    4643              :         };
    4644              : 
    4645              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4646              :         // horizon on the source timeline
    4647              :         //
    4648              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4649              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4650              :         // planned GC cutoff in 'gc_info' is normally larger than
    4651              :         // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
    4652              :         // changed the GC settings for the tenant to make the PITR window
    4653              :         // larger, but some of the data was already removed by an earlier GC
    4654              :         // iteration.
    4655              : 
    4656              :         // check against last actual 'latest_gc_cutoff' first
    4657          232 :         let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
    4658          232 :         src_timeline
    4659          232 :             .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
    4660          232 :             .context(format!(
    4661          232 :                 "invalid branch start lsn: less than latest GC cutoff {}",
    4662          232 :                 *latest_gc_cutoff_lsn,
    4663          232 :             ))
    4664          232 :             .map_err(CreateTimelineError::AncestorLsn)?;
    4665              : 
    4666              :         // and then the planned GC cutoff
    4667              :         {
    4668          228 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4669          228 :             let cutoff = gc_info.min_cutoff();
    4670          228 :             if start_lsn < cutoff {
    4671            0 :                 return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4672            0 :                     "invalid branch start lsn: less than planned GC cutoff {cutoff}"
    4673            0 :                 )));
    4674          228 :             }
    4675          228 :         }
    4676          228 : 
    4677          228 :         //
    4678          228 :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4679          228 :         // so that GC cannot advance the GC cutoff until we are finished.
    4680          228 :         // Proceed with the branch creation.
    4681          228 :         //
    4682          228 : 
    4683          228 :         // Determine prev-LSN for the new timeline. We can only determine it if
    4684          228 :         // the timeline was branched at the current end of the source timeline.
    4685          228 :         let RecordLsn {
    4686          228 :             last: src_last,
    4687          228 :             prev: src_prev,
    4688          228 :         } = src_timeline.get_last_record_rlsn();
    4689          228 :         let dst_prev = if src_last == start_lsn {
    4690          216 :             Some(src_prev)
    4691              :         } else {
    4692           12 :             None
    4693              :         };
    4694              : 
    4695              :         // Create the metadata file, noting the ancestor of the new timeline.
    4696              :         // There is initially no data in it, but all the read-calls know to look
    4697              :         // into the ancestor.
    4698          228 :         let metadata = TimelineMetadata::new(
    4699          228 :             start_lsn,
    4700          228 :             dst_prev,
    4701          228 :             Some(src_id),
    4702          228 :             start_lsn,
    4703          228 :             *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4704          228 :             src_timeline.initdb_lsn,
    4705          228 :             src_timeline.pg_version,
    4706          228 :         );
    4707              : 
    4708          228 :         let uninitialized_timeline = self
    4709          228 :             .prepare_new_timeline(
    4710          228 :                 dst_id,
    4711          228 :                 &metadata,
    4712          228 :                 timeline_create_guard,
    4713          228 :                 start_lsn + 1,
    4714          228 :                 Some(Arc::clone(src_timeline)),
    4715          228 :             )
    4716          228 :             .await?;
    4717              : 
    4718          228 :         let new_timeline = uninitialized_timeline.finish_creation()?;
    4719              : 
    4720              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4721              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4722              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4723              :         // could get incorrect information and remove more layers, than needed.
    4724              :         // See also https://github.com/neondatabase/neon/issues/3865
    4725          228 :         new_timeline
    4726          228 :             .remote_client
    4727          228 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4728          228 :             .context("branch initial metadata upload")?;
    4729              : 
    4730              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4731              : 
    4732          228 :         Ok(CreateTimelineResult::Created(new_timeline))
    4733          232 :     }
    4734              : 
    4735              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4736              :     #[cfg(test)]
    4737            2 :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4738              :     pub(crate) async fn bootstrap_timeline_test(
    4739              :         self: &Arc<Self>,
    4740              :         timeline_id: TimelineId,
    4741              :         pg_version: u32,
    4742              :         load_existing_initdb: Option<TimelineId>,
    4743              :         ctx: &RequestContext,
    4744              :     ) -> anyhow::Result<Arc<Timeline>> {
    4745              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4746              :             .await
    4747              :             .map_err(anyhow::Error::new)
    4748            2 :             .map(|r| r.into_timeline_for_test())
    4749              :     }
    4750              : 
    4751              :     /// Get exclusive access to the timeline ID for creation.
    4752              :     ///
    4753              :     /// Timeline-creating code paths must use this function before making changes
    4754              :     /// to in-memory or persistent state.
    4755              :     ///
    4756              :     /// The `state` parameter is a description of the timeline creation operation
    4757              :     /// we intend to perform.
    4758              :     /// If the timeline was already created in the meantime, we check whether this
    4759              :     /// request conflicts or is idempotent , based on `state`.
    4760          418 :     async fn start_creating_timeline(
    4761          418 :         self: &Arc<Self>,
    4762          418 :         new_timeline_id: TimelineId,
    4763          418 :         idempotency: CreateTimelineIdempotency,
    4764          418 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4765          418 :         let allow_offloaded = false;
    4766          418 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4767          416 :             Ok(create_guard) => {
    4768          416 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4769          416 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4770              :             }
    4771            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4772              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4773              :                 // Creation is in progress, we cannot create it again, and we cannot
    4774              :                 // check if this request matches the existing one, so caller must try
    4775              :                 // again later.
    4776            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4777              :             }
    4778            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4779              :             Err(TimelineExclusionError::AlreadyExists {
    4780            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4781            0 :                 ..
    4782            0 :             }) => {
    4783            0 :                 info!("timeline already exists but is offloaded");
    4784            0 :                 Err(CreateTimelineError::Conflict)
    4785              :             }
    4786              :             Err(TimelineExclusionError::AlreadyExists {
    4787            2 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4788            2 :                 arg,
    4789            2 :             }) => {
    4790            2 :                 {
    4791            2 :                     let existing = &existing.create_idempotency;
    4792            2 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4793            2 :                     debug!("timeline already exists");
    4794              : 
    4795            2 :                     match (existing, &arg) {
    4796              :                         // FailWithConflict => no idempotency check
    4797              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4798              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4799            2 :                             warn!("timeline already exists, failing request");
    4800            2 :                             return Err(CreateTimelineError::Conflict);
    4801              :                         }
    4802              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4803            0 :                         (x, y) if x == y => {
    4804            0 :                             info!("timeline already exists and idempotency matches, succeeding request");
    4805              :                             // fallthrough
    4806              :                         }
    4807              :                         (_, _) => {
    4808            0 :                             warn!("idempotency conflict, failing request");
    4809            0 :                             return Err(CreateTimelineError::Conflict);
    4810              :                         }
    4811              :                     }
    4812              :                 }
    4813              : 
    4814            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4815              :             }
    4816              :         }
    4817          418 :     }
    4818              : 
    4819            0 :     async fn upload_initdb(
    4820            0 :         &self,
    4821            0 :         timelines_path: &Utf8PathBuf,
    4822            0 :         pgdata_path: &Utf8PathBuf,
    4823            0 :         timeline_id: &TimelineId,
    4824            0 :     ) -> anyhow::Result<()> {
    4825            0 :         let temp_path = timelines_path.join(format!(
    4826            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4827            0 :         ));
    4828            0 : 
    4829            0 :         scopeguard::defer! {
    4830            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4831            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4832            0 :             }
    4833            0 :         }
    4834              : 
    4835            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4836              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4837            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4838            0 :             warn!(
    4839            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4840              :             );
    4841            0 :         }
    4842              : 
    4843            0 :         pausable_failpoint!("before-initdb-upload");
    4844              : 
    4845            0 :         backoff::retry(
    4846            0 :             || async {
    4847            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4848            0 :                     &self.remote_storage,
    4849            0 :                     &self.tenant_shard_id.tenant_id,
    4850            0 :                     timeline_id,
    4851            0 :                     pgdata_zstd.try_clone().await?,
    4852            0 :                     tar_zst_size,
    4853            0 :                     &self.cancel,
    4854            0 :                 )
    4855            0 :                 .await
    4856            0 :             },
    4857            0 :             |_| false,
    4858            0 :             3,
    4859            0 :             u32::MAX,
    4860            0 :             "persist_initdb_tar_zst",
    4861            0 :             &self.cancel,
    4862            0 :         )
    4863            0 :         .await
    4864            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    4865            0 :         .and_then(|x| x)
    4866            0 :     }
    4867              : 
    4868              :     /// - run initdb to init temporary instance and get bootstrap data
    4869              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    4870            2 :     async fn bootstrap_timeline(
    4871            2 :         self: &Arc<Self>,
    4872            2 :         timeline_id: TimelineId,
    4873            2 :         pg_version: u32,
    4874            2 :         load_existing_initdb: Option<TimelineId>,
    4875            2 :         ctx: &RequestContext,
    4876            2 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4877            2 :         let timeline_create_guard = match self
    4878            2 :             .start_creating_timeline(
    4879            2 :                 timeline_id,
    4880            2 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    4881            2 :             )
    4882            2 :             .await?
    4883              :         {
    4884            2 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4885            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4886            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline))
    4887              :             }
    4888              :         };
    4889              : 
    4890              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    4891              :         // temporary directory for basebackup files for the given timeline.
    4892              : 
    4893            2 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    4894            2 :         let pgdata_path = path_with_suffix_extension(
    4895            2 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    4896            2 :             TEMP_FILE_SUFFIX,
    4897            2 :         );
    4898            2 : 
    4899            2 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    4900            2 :         // we won't race with other creations or existent timelines with the same path.
    4901            2 :         if pgdata_path.exists() {
    4902            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    4903            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    4904            0 :             })?;
    4905            2 :         }
    4906              : 
    4907              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    4908            2 :         scopeguard::defer! {
    4909            2 :             if let Err(e) = fs::remove_dir_all(&pgdata_path) {
    4910            2 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    4911            2 :                 error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
    4912            2 :             }
    4913            2 :         }
    4914            2 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    4915            2 :             if existing_initdb_timeline_id != timeline_id {
    4916            0 :                 let source_path = &remote_initdb_archive_path(
    4917            0 :                     &self.tenant_shard_id.tenant_id,
    4918            0 :                     &existing_initdb_timeline_id,
    4919            0 :                 );
    4920            0 :                 let dest_path =
    4921            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    4922            0 : 
    4923            0 :                 // if this fails, it will get retried by retried control plane requests
    4924            0 :                 self.remote_storage
    4925            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    4926            0 :                     .await
    4927            0 :                     .context("copy initdb tar")?;
    4928            2 :             }
    4929            2 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    4930            2 :                 self::remote_timeline_client::download_initdb_tar_zst(
    4931            2 :                     self.conf,
    4932            2 :                     &self.remote_storage,
    4933            2 :                     &self.tenant_shard_id,
    4934            2 :                     &existing_initdb_timeline_id,
    4935            2 :                     &self.cancel,
    4936            2 :                 )
    4937            2 :                 .await
    4938            2 :                 .context("download initdb tar")?;
    4939              : 
    4940            2 :             scopeguard::defer! {
    4941            2 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    4942            2 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    4943            2 :                 }
    4944            2 :             }
    4945            2 : 
    4946            2 :             let buf_read =
    4947            2 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    4948            2 :             extract_zst_tarball(&pgdata_path, buf_read)
    4949            2 :                 .await
    4950            2 :                 .context("extract initdb tar")?;
    4951              :         } else {
    4952              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    4953            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    4954            0 :                 .await
    4955            0 :                 .context("run initdb")?;
    4956              : 
    4957              :             // Upload the created data dir to S3
    4958            0 :             if self.tenant_shard_id().is_shard_zero() {
    4959            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    4960            0 :                     .await?;
    4961            0 :             }
    4962              :         }
    4963            2 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    4964            2 : 
    4965            2 :         // Import the contents of the data directory at the initial checkpoint
    4966            2 :         // LSN, and any WAL after that.
    4967            2 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    4968            2 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    4969            2 :         let new_metadata = TimelineMetadata::new(
    4970            2 :             Lsn(0),
    4971            2 :             None,
    4972            2 :             None,
    4973            2 :             Lsn(0),
    4974            2 :             pgdata_lsn,
    4975            2 :             pgdata_lsn,
    4976            2 :             pg_version,
    4977            2 :         );
    4978            2 :         let raw_timeline = self
    4979            2 :             .prepare_new_timeline(
    4980            2 :                 timeline_id,
    4981            2 :                 &new_metadata,
    4982            2 :                 timeline_create_guard,
    4983            2 :                 pgdata_lsn,
    4984            2 :                 None,
    4985            2 :             )
    4986            2 :             .await?;
    4987              : 
    4988            2 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    4989            2 :         let unfinished_timeline = raw_timeline.raw_timeline()?;
    4990              : 
    4991              :         // Flush the new layer files to disk, before we make the timeline as available to
    4992              :         // the outside world.
    4993              :         //
    4994              :         // Flush loop needs to be spawned in order to be able to flush.
    4995            2 :         unfinished_timeline.maybe_spawn_flush_loop();
    4996            2 : 
    4997            2 :         import_datadir::import_timeline_from_postgres_datadir(
    4998            2 :             unfinished_timeline,
    4999            2 :             &pgdata_path,
    5000            2 :             pgdata_lsn,
    5001            2 :             ctx,
    5002            2 :         )
    5003            2 :         .await
    5004            2 :         .with_context(|| {
    5005            0 :             format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
    5006            2 :         })?;
    5007              : 
    5008            2 :         fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5009            0 :             Err(CreateTimelineError::Other(anyhow::anyhow!(
    5010            0 :                 "failpoint before-checkpoint-new-timeline"
    5011            0 :             )))
    5012            2 :         });
    5013              : 
    5014            2 :         unfinished_timeline
    5015            2 :             .freeze_and_flush()
    5016            2 :             .await
    5017            2 :             .with_context(|| {
    5018            0 :                 format!(
    5019            0 :                     "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
    5020            0 :                 )
    5021            2 :             })?;
    5022              : 
    5023              :         // All done!
    5024            2 :         let timeline = raw_timeline.finish_creation()?;
    5025              : 
    5026              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5027              : 
    5028            2 :         Ok(CreateTimelineResult::Created(timeline))
    5029            2 :     }
    5030              : 
    5031          412 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5032          412 :         RemoteTimelineClient::new(
    5033          412 :             self.remote_storage.clone(),
    5034          412 :             self.deletion_queue_client.clone(),
    5035          412 :             self.conf,
    5036          412 :             self.tenant_shard_id,
    5037          412 :             timeline_id,
    5038          412 :             self.generation,
    5039          412 :             &self.tenant_conf.load().location,
    5040          412 :         )
    5041          412 :     }
    5042              : 
    5043              :     /// Call this before constructing a timeline, to build its required structures
    5044          412 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5045          412 :         TimelineResources {
    5046          412 :             remote_client: self.build_timeline_remote_client(timeline_id),
    5047          412 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5048          412 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5049          412 :         }
    5050          412 :     }
    5051              : 
    5052              :     /// Creates intermediate timeline structure and its files.
    5053              :     ///
    5054              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5055              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5056              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5057          412 :     async fn prepare_new_timeline<'a>(
    5058          412 :         &'a self,
    5059          412 :         new_timeline_id: TimelineId,
    5060          412 :         new_metadata: &TimelineMetadata,
    5061          412 :         create_guard: TimelineCreateGuard,
    5062          412 :         start_lsn: Lsn,
    5063          412 :         ancestor: Option<Arc<Timeline>>,
    5064          412 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5065          412 :         let tenant_shard_id = self.tenant_shard_id;
    5066          412 : 
    5067          412 :         let resources = self.build_timeline_resources(new_timeline_id);
    5068          412 :         resources
    5069          412 :             .remote_client
    5070          412 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5071              : 
    5072          412 :         let timeline_struct = self
    5073          412 :             .create_timeline_struct(
    5074          412 :                 new_timeline_id,
    5075          412 :                 new_metadata,
    5076          412 :                 ancestor,
    5077          412 :                 resources,
    5078          412 :                 CreateTimelineCause::Load,
    5079          412 :                 create_guard.idempotency.clone(),
    5080          412 :             )
    5081          412 :             .context("Failed to create timeline data structure")?;
    5082              : 
    5083          412 :         timeline_struct.init_empty_layer_map(start_lsn);
    5084              : 
    5085          412 :         if let Err(e) = self
    5086          412 :             .create_timeline_files(&create_guard.timeline_path)
    5087          412 :             .await
    5088              :         {
    5089            0 :             error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
    5090            0 :             cleanup_timeline_directory(create_guard);
    5091            0 :             return Err(e);
    5092          412 :         }
    5093          412 : 
    5094          412 :         debug!(
    5095            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5096              :         );
    5097              : 
    5098          412 :         Ok(UninitializedTimeline::new(
    5099          412 :             self,
    5100          412 :             new_timeline_id,
    5101          412 :             Some((timeline_struct, create_guard)),
    5102          412 :         ))
    5103          412 :     }
    5104              : 
    5105          412 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5106          412 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5107              : 
    5108          412 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5109            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5110          412 :         });
    5111              : 
    5112          412 :         Ok(())
    5113          412 :     }
    5114              : 
    5115              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5116              :     /// concurrent attempts to create the same timeline.
    5117              :     ///
    5118              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5119              :     /// offloaded timelines or not.
    5120          418 :     fn create_timeline_create_guard(
    5121          418 :         self: &Arc<Self>,
    5122          418 :         timeline_id: TimelineId,
    5123          418 :         idempotency: CreateTimelineIdempotency,
    5124          418 :         allow_offloaded: bool,
    5125          418 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5126          418 :         let tenant_shard_id = self.tenant_shard_id;
    5127          418 : 
    5128          418 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5129              : 
    5130          418 :         let create_guard = TimelineCreateGuard::new(
    5131          418 :             self,
    5132          418 :             timeline_id,
    5133          418 :             timeline_path.clone(),
    5134          418 :             idempotency,
    5135          418 :             allow_offloaded,
    5136          418 :         )?;
    5137              : 
    5138              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5139              :         // for creation.
    5140              :         // A timeline directory should never exist on disk already:
    5141              :         // - a previous failed creation would have cleaned up after itself
    5142              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5143              :         //
    5144              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5145              :         // this error may indicate a bug in cleanup on failed creations.
    5146          416 :         if timeline_path.exists() {
    5147            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5148            0 :                 "Timeline directory already exists! This is a bug."
    5149            0 :             )));
    5150          416 :         }
    5151          416 : 
    5152          416 :         Ok(create_guard)
    5153          418 :     }
    5154              : 
    5155              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5156              :     ///
    5157              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5158            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5159              :     pub async fn gather_size_inputs(
    5160              :         &self,
    5161              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5162              :         // (only if it is shorter than the real cutoff).
    5163              :         max_retention_period: Option<u64>,
    5164              :         cause: LogicalSizeCalculationCause,
    5165              :         cancel: &CancellationToken,
    5166              :         ctx: &RequestContext,
    5167              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5168              :         let logical_sizes_at_once = self
    5169              :             .conf
    5170              :             .concurrent_tenant_size_logical_size_queries
    5171              :             .inner();
    5172              : 
    5173              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5174              :         //
    5175              :         // But the only case where we need to run multiple of these at once is when we
    5176              :         // request a size for a tenant manually via API, while another background calculation
    5177              :         // is in progress (which is not a common case).
    5178              :         //
    5179              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5180              :         let mut shared_cache = tokio::select! {
    5181              :             locked = self.cached_logical_sizes.lock() => locked,
    5182              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5183              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5184              :         };
    5185              : 
    5186              :         size::gather_inputs(
    5187              :             self,
    5188              :             logical_sizes_at_once,
    5189              :             max_retention_period,
    5190              :             &mut shared_cache,
    5191              :             cause,
    5192              :             cancel,
    5193              :             ctx,
    5194              :         )
    5195              :         .await
    5196              :     }
    5197              : 
    5198              :     /// Calculate synthetic tenant size and cache the result.
    5199              :     /// This is periodically called by background worker.
    5200              :     /// result is cached in tenant struct
    5201            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5202              :     pub async fn calculate_synthetic_size(
    5203              :         &self,
    5204              :         cause: LogicalSizeCalculationCause,
    5205              :         cancel: &CancellationToken,
    5206              :         ctx: &RequestContext,
    5207              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5208              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5209              : 
    5210              :         let size = inputs.calculate();
    5211              : 
    5212              :         self.set_cached_synthetic_size(size);
    5213              : 
    5214              :         Ok(size)
    5215              :     }
    5216              : 
    5217              :     /// Cache given synthetic size and update the metric value
    5218            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5219            0 :         self.cached_synthetic_tenant_size
    5220            0 :             .store(size, Ordering::Relaxed);
    5221            0 : 
    5222            0 :         // Only shard zero should be calculating synthetic sizes
    5223            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5224              : 
    5225            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5226            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5227            0 :             .unwrap()
    5228            0 :             .set(size);
    5229            0 :     }
    5230              : 
    5231            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5232            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5233            0 :     }
    5234              : 
    5235              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5236              :     ///
    5237              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5238              :     /// from an external API handler.
    5239              :     ///
    5240              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5241              :     /// still bounded by tenant/timeline shutdown.
    5242            0 :     #[tracing::instrument(skip_all)]
    5243              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5244              :         let timelines = self.timelines.lock().unwrap().clone();
    5245              : 
    5246            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5247            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5248            0 :             timeline.freeze_and_flush().await?;
    5249            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5250            0 :             timeline.remote_client.wait_completion().await?;
    5251              : 
    5252            0 :             Ok(())
    5253            0 :         }
    5254              : 
    5255              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5256              :         // aborted when this function's future is cancelled: they should stay alive
    5257              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5258              :         // before Timeline shutdown completes.
    5259              :         let mut results = FuturesUnordered::new();
    5260              : 
    5261              :         for (_timeline_id, timeline) in timelines {
    5262              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5263              :             // means that if this function's future is cancelled, the Timeline shutdown
    5264              :             // will still wait for any I/O in here to complete.
    5265              :             let Ok(gate) = timeline.gate.enter() else {
    5266              :                 continue;
    5267              :             };
    5268            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5269              :             results.push(jh);
    5270              :         }
    5271              : 
    5272              :         while let Some(r) = results.next().await {
    5273              :             if let Err(e) = r {
    5274              :                 if !e.is_cancelled() && !e.is_panic() {
    5275              :                     tracing::error!("unexpected join error: {e:?}");
    5276              :                 }
    5277              :             }
    5278              :         }
    5279              : 
    5280              :         // The flushes we did above were just writes, but the Tenant might have had
    5281              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5282              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5283              :         // because it's typically a no-op.
    5284              :         match self.deletion_queue_client.flush_execute().await {
    5285              :             Ok(_) => {}
    5286              :             Err(DeletionQueueError::ShuttingDown) => {}
    5287              :         }
    5288              : 
    5289              :         Ok(())
    5290              :     }
    5291              : 
    5292            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5293            0 :         self.tenant_conf.load().tenant_conf.clone()
    5294            0 :     }
    5295              : 
    5296              :     /// How much local storage would this tenant like to have?  It can cope with
    5297              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5298              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5299              :     /// by keeping important things on local disk.
    5300              :     ///
    5301              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5302              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5303              :     /// actually use more than they report here.
    5304            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5305            0 :         let timelines = self.timelines.lock().unwrap();
    5306            0 : 
    5307            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5308            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5309            0 :         // of them is used actively enough to occupy space on disk.
    5310            0 :         timelines
    5311            0 :             .values()
    5312            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5313            0 :             .max()
    5314            0 :             .unwrap_or(0)
    5315            0 :     }
    5316              : 
    5317              :     /// Serialize and write the latest TenantManifest to remote storage.
    5318            2 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5319              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5320              :         // must be loaded while holding this lock. This makes it safe to call this function
    5321              :         // from anywhere without worrying about colliding updates.
    5322            2 :         let mut guard = tokio::select! {
    5323            2 :             g = self.tenant_manifest_upload.lock() => {
    5324            2 :                 g
    5325              :             },
    5326            2 :             _ = self.cancel.cancelled() => {
    5327            0 :                 return Err(TenantManifestError::Cancelled);
    5328              :             }
    5329              :         };
    5330              : 
    5331            2 :         let manifest = self.build_tenant_manifest();
    5332            2 :         if Some(&manifest) == (*guard).as_ref() {
    5333              :             // Optimisation: skip uploads that don't change anything.
    5334            0 :             return Ok(());
    5335            2 :         }
    5336            2 : 
    5337            2 :         upload_tenant_manifest(
    5338            2 :             &self.remote_storage,
    5339            2 :             &self.tenant_shard_id,
    5340            2 :             self.generation,
    5341            2 :             &manifest,
    5342            2 :             &self.cancel,
    5343            2 :         )
    5344            2 :         .await
    5345            2 :         .map_err(|e| {
    5346            0 :             if self.cancel.is_cancelled() {
    5347            0 :                 TenantManifestError::Cancelled
    5348              :             } else {
    5349            0 :                 TenantManifestError::RemoteStorage(e)
    5350              :             }
    5351            2 :         })?;
    5352              : 
    5353              :         // Store the successfully uploaded manifest, so that future callers can avoid
    5354              :         // re-uploading the same thing.
    5355            2 :         *guard = Some(manifest);
    5356            2 : 
    5357            2 :         Ok(())
    5358            2 :     }
    5359              : }
    5360              : 
    5361              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5362              : /// to get bootstrap data for timeline initialization.
    5363            0 : async fn run_initdb(
    5364            0 :     conf: &'static PageServerConf,
    5365            0 :     initdb_target_dir: &Utf8Path,
    5366            0 :     pg_version: u32,
    5367            0 :     cancel: &CancellationToken,
    5368            0 : ) -> Result<(), InitdbError> {
    5369            0 :     let initdb_bin_path = conf
    5370            0 :         .pg_bin_dir(pg_version)
    5371            0 :         .map_err(InitdbError::Other)?
    5372            0 :         .join("initdb");
    5373            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5374            0 :     info!(
    5375            0 :         "running {} in {}, libdir: {}",
    5376              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5377              :     );
    5378              : 
    5379            0 :     let _permit = INIT_DB_SEMAPHORE.acquire().await;
    5380              : 
    5381            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5382            0 :         superuser: &conf.superuser,
    5383            0 :         locale: &conf.locale,
    5384            0 :         initdb_bin: &initdb_bin_path,
    5385            0 :         pg_version,
    5386            0 :         library_search_path: &initdb_lib_dir,
    5387            0 :         pgdata: initdb_target_dir,
    5388            0 :     })
    5389            0 :     .await
    5390            0 :     .map_err(InitdbError::Inner);
    5391            0 : 
    5392            0 :     // This isn't true cancellation support, see above. Still return an error to
    5393            0 :     // excercise the cancellation code path.
    5394            0 :     if cancel.is_cancelled() {
    5395            0 :         return Err(InitdbError::Cancelled);
    5396            0 :     }
    5397            0 : 
    5398            0 :     res
    5399            0 : }
    5400              : 
    5401              : /// Dump contents of a layer file to stdout.
    5402            0 : pub async fn dump_layerfile_from_path(
    5403            0 :     path: &Utf8Path,
    5404            0 :     verbose: bool,
    5405            0 :     ctx: &RequestContext,
    5406            0 : ) -> anyhow::Result<()> {
    5407              :     use std::os::unix::fs::FileExt;
    5408              : 
    5409              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5410              :     // file.
    5411            0 :     let file = File::open(path)?;
    5412            0 :     let mut header_buf = [0u8; 2];
    5413            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5414              : 
    5415            0 :     match u16::from_be_bytes(header_buf) {
    5416              :         crate::IMAGE_FILE_MAGIC => {
    5417            0 :             ImageLayer::new_for_path(path, file)?
    5418            0 :                 .dump(verbose, ctx)
    5419            0 :                 .await?
    5420              :         }
    5421              :         crate::DELTA_FILE_MAGIC => {
    5422            0 :             DeltaLayer::new_for_path(path, file)?
    5423            0 :                 .dump(verbose, ctx)
    5424            0 :                 .await?
    5425              :         }
    5426            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5427              :     }
    5428              : 
    5429            0 :     Ok(())
    5430            0 : }
    5431              : 
    5432              : #[cfg(test)]
    5433              : pub(crate) mod harness {
    5434              :     use bytes::{Bytes, BytesMut};
    5435              :     use once_cell::sync::OnceCell;
    5436              :     use pageserver_api::models::ShardParameters;
    5437              :     use pageserver_api::shard::ShardIndex;
    5438              :     use utils::logging;
    5439              : 
    5440              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5441              :     use crate::l0_flush::L0FlushConfig;
    5442              :     use crate::walredo::apply_neon;
    5443              :     use pageserver_api::key::Key;
    5444              :     use pageserver_api::record::NeonWalRecord;
    5445              : 
    5446              :     use super::*;
    5447              :     use hex_literal::hex;
    5448              :     use utils::id::TenantId;
    5449              : 
    5450              :     pub const TIMELINE_ID: TimelineId =
    5451              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5452              :     pub const NEW_TIMELINE_ID: TimelineId =
    5453              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5454              : 
    5455              :     /// Convenience function to create a page image with given string as the only content
    5456      5028714 :     pub fn test_img(s: &str) -> Bytes {
    5457      5028714 :         let mut buf = BytesMut::new();
    5458      5028714 :         buf.extend_from_slice(s.as_bytes());
    5459      5028714 :         buf.resize(64, 0);
    5460      5028714 : 
    5461      5028714 :         buf.freeze()
    5462      5028714 :     }
    5463              : 
    5464              :     impl From<TenantConf> for TenantConfOpt {
    5465          192 :         fn from(tenant_conf: TenantConf) -> Self {
    5466          192 :             Self {
    5467          192 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5468          192 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5469          192 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5470          192 :                 compaction_period: Some(tenant_conf.compaction_period),
    5471          192 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5472          192 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5473          192 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5474          192 :                 gc_period: Some(tenant_conf.gc_period),
    5475          192 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5476          192 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5477          192 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5478          192 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5479          192 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5480          192 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5481          192 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5482          192 :                 evictions_low_residence_duration_metric_threshold: Some(
    5483          192 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5484          192 :                 ),
    5485          192 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5486          192 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5487          192 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5488          192 :                 image_layer_creation_check_threshold: Some(
    5489          192 :                     tenant_conf.image_layer_creation_check_threshold,
    5490          192 :                 ),
    5491          192 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5492          192 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5493          192 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5494          192 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5495          192 :             }
    5496          192 :         }
    5497              :     }
    5498              : 
    5499              :     pub struct TenantHarness {
    5500              :         pub conf: &'static PageServerConf,
    5501              :         pub tenant_conf: TenantConf,
    5502              :         pub tenant_shard_id: TenantShardId,
    5503              :         pub generation: Generation,
    5504              :         pub shard: ShardIndex,
    5505              :         pub remote_storage: GenericRemoteStorage,
    5506              :         pub remote_fs_dir: Utf8PathBuf,
    5507              :         pub deletion_queue: MockDeletionQueue,
    5508              :     }
    5509              : 
    5510              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5511              : 
    5512          208 :     pub(crate) fn setup_logging() {
    5513          208 :         LOG_HANDLE.get_or_init(|| {
    5514          196 :             logging::init(
    5515          196 :                 logging::LogFormat::Test,
    5516          196 :                 // enable it in case the tests exercise code paths that use
    5517          196 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5518          196 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5519          196 :                 logging::Output::Stdout,
    5520          196 :             )
    5521          196 :             .expect("Failed to init test logging")
    5522          208 :         });
    5523          208 :     }
    5524              : 
    5525              :     impl TenantHarness {
    5526          192 :         pub async fn create_custom(
    5527          192 :             test_name: &'static str,
    5528          192 :             tenant_conf: TenantConf,
    5529          192 :             tenant_id: TenantId,
    5530          192 :             shard_identity: ShardIdentity,
    5531          192 :             generation: Generation,
    5532          192 :         ) -> anyhow::Result<Self> {
    5533          192 :             setup_logging();
    5534          192 : 
    5535          192 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5536          192 :             let _ = fs::remove_dir_all(&repo_dir);
    5537          192 :             fs::create_dir_all(&repo_dir)?;
    5538              : 
    5539          192 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5540          192 :             // Make a static copy of the config. This can never be free'd, but that's
    5541          192 :             // OK in a test.
    5542          192 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5543          192 : 
    5544          192 :             let shard = shard_identity.shard_index();
    5545          192 :             let tenant_shard_id = TenantShardId {
    5546          192 :                 tenant_id,
    5547          192 :                 shard_number: shard.shard_number,
    5548          192 :                 shard_count: shard.shard_count,
    5549          192 :             };
    5550          192 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5551          192 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5552              : 
    5553              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5554          192 :             let remote_fs_dir = conf.workdir.join("localfs");
    5555          192 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5556          192 :             let config = RemoteStorageConfig {
    5557          192 :                 storage: RemoteStorageKind::LocalFs {
    5558          192 :                     local_path: remote_fs_dir.clone(),
    5559          192 :                 },
    5560          192 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5561          192 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5562          192 :             };
    5563          192 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5564          192 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5565          192 : 
    5566          192 :             Ok(Self {
    5567          192 :                 conf,
    5568          192 :                 tenant_conf,
    5569          192 :                 tenant_shard_id,
    5570          192 :                 generation,
    5571          192 :                 shard,
    5572          192 :                 remote_storage,
    5573          192 :                 remote_fs_dir,
    5574          192 :                 deletion_queue,
    5575          192 :             })
    5576          192 :         }
    5577              : 
    5578          180 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5579          180 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5580          180 :             // The tests perform them manually if needed.
    5581          180 :             let tenant_conf = TenantConf {
    5582          180 :                 gc_period: Duration::ZERO,
    5583          180 :                 compaction_period: Duration::ZERO,
    5584          180 :                 ..TenantConf::default()
    5585          180 :             };
    5586          180 :             let tenant_id = TenantId::generate();
    5587          180 :             let shard = ShardIdentity::unsharded();
    5588          180 :             Self::create_custom(
    5589          180 :                 test_name,
    5590          180 :                 tenant_conf,
    5591          180 :                 tenant_id,
    5592          180 :                 shard,
    5593          180 :                 Generation::new(0xdeadbeef),
    5594          180 :             )
    5595          180 :             .await
    5596          180 :         }
    5597              : 
    5598           20 :         pub fn span(&self) -> tracing::Span {
    5599           20 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5600           20 :         }
    5601              : 
    5602          192 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5603          192 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5604          192 :             (
    5605          192 :                 self.do_try_load(&ctx)
    5606          192 :                     .await
    5607          192 :                     .expect("failed to load test tenant"),
    5608          192 :                 ctx,
    5609          192 :             )
    5610          192 :         }
    5611              : 
    5612          192 :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5613              :         pub(crate) async fn do_try_load(
    5614              :             &self,
    5615              :             ctx: &RequestContext,
    5616              :         ) -> anyhow::Result<Arc<Tenant>> {
    5617              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5618              : 
    5619              :             let tenant = Arc::new(Tenant::new(
    5620              :                 TenantState::Attaching,
    5621              :                 self.conf,
    5622              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5623              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5624              :                     self.generation,
    5625              :                     &ShardParameters::default(),
    5626              :                 ))
    5627              :                 .unwrap(),
    5628              :                 // This is a legacy/test code path: sharding isn't supported here.
    5629              :                 ShardIdentity::unsharded(),
    5630              :                 Some(walredo_mgr),
    5631              :                 self.tenant_shard_id,
    5632              :                 self.remote_storage.clone(),
    5633              :                 self.deletion_queue.new_client(),
    5634              :                 // TODO: ideally we should run all unit tests with both configs
    5635              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5636              :             ));
    5637              : 
    5638              :             let preload = tenant
    5639              :                 .preload(&self.remote_storage, CancellationToken::new())
    5640              :                 .await?;
    5641              :             tenant.attach(Some(preload), ctx).await?;
    5642              : 
    5643              :             tenant.state.send_replace(TenantState::Active);
    5644              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5645              :                 timeline.set_state(TimelineState::Active);
    5646              :             }
    5647              :             Ok(tenant)
    5648              :         }
    5649              : 
    5650            2 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5651            2 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5652            2 :         }
    5653              :     }
    5654              : 
    5655              :     // Mock WAL redo manager that doesn't do much
    5656              :     pub(crate) struct TestRedoManager;
    5657              : 
    5658              :     impl TestRedoManager {
    5659              :         /// # Cancel-Safety
    5660              :         ///
    5661              :         /// This method is cancellation-safe.
    5662          410 :         pub async fn request_redo(
    5663          410 :             &self,
    5664          410 :             key: Key,
    5665          410 :             lsn: Lsn,
    5666          410 :             base_img: Option<(Lsn, Bytes)>,
    5667          410 :             records: Vec<(Lsn, NeonWalRecord)>,
    5668          410 :             _pg_version: u32,
    5669          410 :         ) -> Result<Bytes, walredo::Error> {
    5670          570 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5671          410 :             if records_neon {
    5672              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5673          410 :                 let mut page = match (base_img, records.first()) {
    5674          344 :                     (Some((_lsn, img)), _) => {
    5675          344 :                         let mut page = BytesMut::new();
    5676          344 :                         page.extend_from_slice(&img);
    5677          344 :                         page
    5678              :                     }
    5679           66 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5680              :                     _ => {
    5681            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5682              :                     }
    5683              :                 };
    5684              : 
    5685          980 :                 for (record_lsn, record) in records {
    5686          570 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5687              :                 }
    5688          410 :                 Ok(page.freeze())
    5689              :             } else {
    5690              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5691            0 :                 let s = format!(
    5692            0 :                     "redo for {} to get to {}, with {} and {} records",
    5693            0 :                     key,
    5694            0 :                     lsn,
    5695            0 :                     if base_img.is_some() {
    5696            0 :                         "base image"
    5697              :                     } else {
    5698            0 :                         "no base image"
    5699              :                     },
    5700            0 :                     records.len()
    5701            0 :                 );
    5702            0 :                 println!("{s}");
    5703            0 : 
    5704            0 :                 Ok(test_img(&s))
    5705              :             }
    5706          410 :         }
    5707              :     }
    5708              : }
    5709              : 
    5710              : #[cfg(test)]
    5711              : mod tests {
    5712              :     use std::collections::{BTreeMap, BTreeSet};
    5713              : 
    5714              :     use super::*;
    5715              :     use crate::keyspace::KeySpaceAccum;
    5716              :     use crate::tenant::harness::*;
    5717              :     use crate::tenant::timeline::CompactFlags;
    5718              :     use crate::DEFAULT_PG_VERSION;
    5719              :     use bytes::{Bytes, BytesMut};
    5720              :     use hex_literal::hex;
    5721              :     use itertools::Itertools;
    5722              :     use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
    5723              :     use pageserver_api::keyspace::KeySpace;
    5724              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5725              :     use pageserver_api::value::Value;
    5726              :     use pageserver_compaction::helpers::overlaps_with;
    5727              :     use rand::{thread_rng, Rng};
    5728              :     use storage_layer::PersistentLayerKey;
    5729              :     use tests::storage_layer::ValuesReconstructState;
    5730              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5731              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5732              :     use utils::id::TenantId;
    5733              : 
    5734              :     #[cfg(feature = "testing")]
    5735              :     use pageserver_api::record::NeonWalRecord;
    5736              :     #[cfg(feature = "testing")]
    5737              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5738              :     #[cfg(feature = "testing")]
    5739              :     use timeline::GcInfo;
    5740              : 
    5741              :     static TEST_KEY: Lazy<Key> =
    5742           18 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5743              : 
    5744              :     #[tokio::test]
    5745            2 :     async fn test_basic() -> anyhow::Result<()> {
    5746            2 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5747            2 :         let tline = tenant
    5748            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5749            2 :             .await?;
    5750            2 : 
    5751            2 :         let mut writer = tline.writer().await;
    5752            2 :         writer
    5753            2 :             .put(
    5754            2 :                 *TEST_KEY,
    5755            2 :                 Lsn(0x10),
    5756            2 :                 &Value::Image(test_img("foo at 0x10")),
    5757            2 :                 &ctx,
    5758            2 :             )
    5759            2 :             .await?;
    5760            2 :         writer.finish_write(Lsn(0x10));
    5761            2 :         drop(writer);
    5762            2 : 
    5763            2 :         let mut writer = tline.writer().await;
    5764            2 :         writer
    5765            2 :             .put(
    5766            2 :                 *TEST_KEY,
    5767            2 :                 Lsn(0x20),
    5768            2 :                 &Value::Image(test_img("foo at 0x20")),
    5769            2 :                 &ctx,
    5770            2 :             )
    5771            2 :             .await?;
    5772            2 :         writer.finish_write(Lsn(0x20));
    5773            2 :         drop(writer);
    5774            2 : 
    5775            2 :         assert_eq!(
    5776            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5777            2 :             test_img("foo at 0x10")
    5778            2 :         );
    5779            2 :         assert_eq!(
    5780            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5781            2 :             test_img("foo at 0x10")
    5782            2 :         );
    5783            2 :         assert_eq!(
    5784            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5785            2 :             test_img("foo at 0x20")
    5786            2 :         );
    5787            2 : 
    5788            2 :         Ok(())
    5789            2 :     }
    5790              : 
    5791              :     #[tokio::test]
    5792            2 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5793            2 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5794            2 :             .await?
    5795            2 :             .load()
    5796            2 :             .await;
    5797            2 :         let _ = tenant
    5798            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5799            2 :             .await?;
    5800            2 : 
    5801            2 :         match tenant
    5802            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5803            2 :             .await
    5804            2 :         {
    5805            2 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5806            2 :             Err(e) => assert_eq!(
    5807            2 :                 e.to_string(),
    5808            2 :                 "timeline already exists with different parameters".to_string()
    5809            2 :             ),
    5810            2 :         }
    5811            2 : 
    5812            2 :         Ok(())
    5813            2 :     }
    5814              : 
    5815              :     /// Convenience function to create a page image with given string as the only content
    5816           10 :     pub fn test_value(s: &str) -> Value {
    5817           10 :         let mut buf = BytesMut::new();
    5818           10 :         buf.extend_from_slice(s.as_bytes());
    5819           10 :         Value::Image(buf.freeze())
    5820           10 :     }
    5821              : 
    5822              :     ///
    5823              :     /// Test branch creation
    5824              :     ///
    5825              :     #[tokio::test]
    5826            2 :     async fn test_branch() -> anyhow::Result<()> {
    5827            2 :         use std::str::from_utf8;
    5828            2 : 
    5829            2 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    5830            2 :         let tline = tenant
    5831            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5832            2 :             .await?;
    5833            2 :         let mut writer = tline.writer().await;
    5834            2 : 
    5835            2 :         #[allow(non_snake_case)]
    5836            2 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    5837            2 :         #[allow(non_snake_case)]
    5838            2 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    5839            2 : 
    5840            2 :         // Insert a value on the timeline
    5841            2 :         writer
    5842            2 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    5843            2 :             .await?;
    5844            2 :         writer
    5845            2 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    5846            2 :             .await?;
    5847            2 :         writer.finish_write(Lsn(0x20));
    5848            2 : 
    5849            2 :         writer
    5850            2 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    5851            2 :             .await?;
    5852            2 :         writer.finish_write(Lsn(0x30));
    5853            2 :         writer
    5854            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    5855            2 :             .await?;
    5856            2 :         writer.finish_write(Lsn(0x40));
    5857            2 : 
    5858            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5859            2 : 
    5860            2 :         // Branch the history, modify relation differently on the new timeline
    5861            2 :         tenant
    5862            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    5863            2 :             .await?;
    5864            2 :         let newtline = tenant
    5865            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    5866            2 :             .expect("Should have a local timeline");
    5867            2 :         let mut new_writer = newtline.writer().await;
    5868            2 :         new_writer
    5869            2 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    5870            2 :             .await?;
    5871            2 :         new_writer.finish_write(Lsn(0x40));
    5872            2 : 
    5873            2 :         // Check page contents on both branches
    5874            2 :         assert_eq!(
    5875            2 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5876            2 :             "foo at 0x40"
    5877            2 :         );
    5878            2 :         assert_eq!(
    5879            2 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    5880            2 :             "bar at 0x40"
    5881            2 :         );
    5882            2 :         assert_eq!(
    5883            2 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    5884            2 :             "foobar at 0x20"
    5885            2 :         );
    5886            2 : 
    5887            2 :         //assert_current_logical_size(&tline, Lsn(0x40));
    5888            2 : 
    5889            2 :         Ok(())
    5890            2 :     }
    5891              : 
    5892           20 :     async fn make_some_layers(
    5893           20 :         tline: &Timeline,
    5894           20 :         start_lsn: Lsn,
    5895           20 :         ctx: &RequestContext,
    5896           20 :     ) -> anyhow::Result<()> {
    5897           20 :         let mut lsn = start_lsn;
    5898              :         {
    5899           20 :             let mut writer = tline.writer().await;
    5900              :             // Create a relation on the timeline
    5901           20 :             writer
    5902           20 :                 .put(
    5903           20 :                     *TEST_KEY,
    5904           20 :                     lsn,
    5905           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5906           20 :                     ctx,
    5907           20 :                 )
    5908           20 :                 .await?;
    5909           20 :             writer.finish_write(lsn);
    5910           20 :             lsn += 0x10;
    5911           20 :             writer
    5912           20 :                 .put(
    5913           20 :                     *TEST_KEY,
    5914           20 :                     lsn,
    5915           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5916           20 :                     ctx,
    5917           20 :                 )
    5918           20 :                 .await?;
    5919           20 :             writer.finish_write(lsn);
    5920           20 :             lsn += 0x10;
    5921           20 :         }
    5922           20 :         tline.freeze_and_flush().await?;
    5923              :         {
    5924           20 :             let mut writer = tline.writer().await;
    5925           20 :             writer
    5926           20 :                 .put(
    5927           20 :                     *TEST_KEY,
    5928           20 :                     lsn,
    5929           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5930           20 :                     ctx,
    5931           20 :                 )
    5932           20 :                 .await?;
    5933           20 :             writer.finish_write(lsn);
    5934           20 :             lsn += 0x10;
    5935           20 :             writer
    5936           20 :                 .put(
    5937           20 :                     *TEST_KEY,
    5938           20 :                     lsn,
    5939           20 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    5940           20 :                     ctx,
    5941           20 :                 )
    5942           20 :                 .await?;
    5943           20 :             writer.finish_write(lsn);
    5944           20 :         }
    5945           20 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    5946           20 :     }
    5947              : 
    5948              :     #[tokio::test(start_paused = true)]
    5949            2 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    5950            2 :         let (tenant, ctx) =
    5951            2 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    5952            2 :                 .await?
    5953            2 :                 .load()
    5954            2 :                 .await;
    5955            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    5956            2 :         // initial transition into AttachedSingle.
    5957            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    5958            2 :         tokio::time::resume();
    5959            2 :         let tline = tenant
    5960            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5961            2 :             .await?;
    5962            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    5963            2 : 
    5964            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    5965            2 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    5966            2 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    5967            2 :         // below should fail.
    5968            2 :         tenant
    5969            2 :             .gc_iteration(
    5970            2 :                 Some(TIMELINE_ID),
    5971            2 :                 0x10,
    5972            2 :                 Duration::ZERO,
    5973            2 :                 &CancellationToken::new(),
    5974            2 :                 &ctx,
    5975            2 :             )
    5976            2 :             .await?;
    5977            2 : 
    5978            2 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    5979            2 :         match tenant
    5980            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    5981            2 :             .await
    5982            2 :         {
    5983            2 :             Ok(_) => panic!("branching should have failed"),
    5984            2 :             Err(err) => {
    5985            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    5986            2 :                     panic!("wrong error type")
    5987            2 :                 };
    5988            2 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    5989            2 :                 assert!(err
    5990            2 :                     .source()
    5991            2 :                     .unwrap()
    5992            2 :                     .to_string()
    5993            2 :                     .contains("we might've already garbage collected needed data"))
    5994            2 :             }
    5995            2 :         }
    5996            2 : 
    5997            2 :         Ok(())
    5998            2 :     }
    5999              : 
    6000              :     #[tokio::test]
    6001            2 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6002            2 :         let (tenant, ctx) =
    6003            2 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6004            2 :                 .await?
    6005            2 :                 .load()
    6006            2 :                 .await;
    6007            2 : 
    6008            2 :         let tline = tenant
    6009            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6010            2 :             .await?;
    6011            2 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6012            2 :         match tenant
    6013            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6014            2 :             .await
    6015            2 :         {
    6016            2 :             Ok(_) => panic!("branching should have failed"),
    6017            2 :             Err(err) => {
    6018            2 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6019            2 :                     panic!("wrong error type");
    6020            2 :                 };
    6021            2 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6022            2 :                 assert!(&err
    6023            2 :                     .source()
    6024            2 :                     .unwrap()
    6025            2 :                     .to_string()
    6026            2 :                     .contains("is earlier than latest GC cutoff"));
    6027            2 :             }
    6028            2 :         }
    6029            2 : 
    6030            2 :         Ok(())
    6031            2 :     }
    6032              : 
    6033              :     /*
    6034              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6035              :     // remove the old value, we'd need to work a little harder
    6036              :     #[tokio::test]
    6037              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6038              :         let repo =
    6039              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6040              :             .load();
    6041              : 
    6042              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6043              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6044              : 
    6045              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6046              :         let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
    6047              :         assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
    6048              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6049              :             Ok(_) => panic!("request for page should have failed"),
    6050              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6051              :         }
    6052              :         Ok(())
    6053              :     }
    6054              :      */
    6055              : 
    6056              :     #[tokio::test]
    6057            2 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6058            2 :         let (tenant, ctx) =
    6059            2 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6060            2 :                 .await?
    6061            2 :                 .load()
    6062            2 :                 .await;
    6063            2 :         let tline = tenant
    6064            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6065            2 :             .await?;
    6066            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6067            2 : 
    6068            2 :         tenant
    6069            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6070            2 :             .await?;
    6071            2 :         let newtline = tenant
    6072            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6073            2 :             .expect("Should have a local timeline");
    6074            2 : 
    6075            2 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6076            2 : 
    6077            2 :         tline.set_broken("test".to_owned());
    6078            2 : 
    6079            2 :         tenant
    6080            2 :             .gc_iteration(
    6081            2 :                 Some(TIMELINE_ID),
    6082            2 :                 0x10,
    6083            2 :                 Duration::ZERO,
    6084            2 :                 &CancellationToken::new(),
    6085            2 :                 &ctx,
    6086            2 :             )
    6087            2 :             .await?;
    6088            2 : 
    6089            2 :         // The branchpoints should contain all timelines, even ones marked
    6090            2 :         // as Broken.
    6091            2 :         {
    6092            2 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6093            2 :             assert_eq!(branchpoints.len(), 1);
    6094            2 :             assert_eq!(
    6095            2 :                 branchpoints[0],
    6096            2 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6097            2 :             );
    6098            2 :         }
    6099            2 : 
    6100            2 :         // You can read the key from the child branch even though the parent is
    6101            2 :         // Broken, as long as you don't need to access data from the parent.
    6102            2 :         assert_eq!(
    6103            2 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6104            2 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6105            2 :         );
    6106            2 : 
    6107            2 :         // This needs to traverse to the parent, and fails.
    6108            2 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6109            2 :         assert!(
    6110            2 :             err.to_string().starts_with(&format!(
    6111            2 :                 "bad state on timeline {}: Broken",
    6112            2 :                 tline.timeline_id
    6113            2 :             )),
    6114            2 :             "{err}"
    6115            2 :         );
    6116            2 : 
    6117            2 :         Ok(())
    6118            2 :     }
    6119              : 
    6120              :     #[tokio::test]
    6121            2 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6122            2 :         let (tenant, ctx) =
    6123            2 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6124            2 :                 .await?
    6125            2 :                 .load()
    6126            2 :                 .await;
    6127            2 :         let tline = tenant
    6128            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6129            2 :             .await?;
    6130            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6131            2 : 
    6132            2 :         tenant
    6133            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6134            2 :             .await?;
    6135            2 :         let newtline = tenant
    6136            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6137            2 :             .expect("Should have a local timeline");
    6138            2 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6139            2 :         tenant
    6140            2 :             .gc_iteration(
    6141            2 :                 Some(TIMELINE_ID),
    6142            2 :                 0x10,
    6143            2 :                 Duration::ZERO,
    6144            2 :                 &CancellationToken::new(),
    6145            2 :                 &ctx,
    6146            2 :             )
    6147            2 :             .await?;
    6148            2 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6149            2 : 
    6150            2 :         Ok(())
    6151            2 :     }
    6152              :     #[tokio::test]
    6153            2 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6154            2 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6155            2 :             .await?
    6156            2 :             .load()
    6157            2 :             .await;
    6158            2 :         let tline = tenant
    6159            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6160            2 :             .await?;
    6161            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6162            2 : 
    6163            2 :         tenant
    6164            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6165            2 :             .await?;
    6166            2 :         let newtline = tenant
    6167            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6168            2 :             .expect("Should have a local timeline");
    6169            2 : 
    6170            2 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6171            2 : 
    6172            2 :         // run gc on parent
    6173            2 :         tenant
    6174            2 :             .gc_iteration(
    6175            2 :                 Some(TIMELINE_ID),
    6176            2 :                 0x10,
    6177            2 :                 Duration::ZERO,
    6178            2 :                 &CancellationToken::new(),
    6179            2 :                 &ctx,
    6180            2 :             )
    6181            2 :             .await?;
    6182            2 : 
    6183            2 :         // Check that the data is still accessible on the branch.
    6184            2 :         assert_eq!(
    6185            2 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6186            2 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6187            2 :         );
    6188            2 : 
    6189            2 :         Ok(())
    6190            2 :     }
    6191              : 
    6192              :     #[tokio::test]
    6193            2 :     async fn timeline_load() -> anyhow::Result<()> {
    6194            2 :         const TEST_NAME: &str = "timeline_load";
    6195            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6196            2 :         {
    6197            2 :             let (tenant, ctx) = harness.load().await;
    6198            2 :             let tline = tenant
    6199            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6200            2 :                 .await?;
    6201            2 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6202            2 :             // so that all uploads finish & we can call harness.load() below again
    6203            2 :             tenant
    6204            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6205            2 :                 .instrument(harness.span())
    6206            2 :                 .await
    6207            2 :                 .ok()
    6208            2 :                 .unwrap();
    6209            2 :         }
    6210            2 : 
    6211            2 :         let (tenant, _ctx) = harness.load().await;
    6212            2 :         tenant
    6213            2 :             .get_timeline(TIMELINE_ID, true)
    6214            2 :             .expect("cannot load timeline");
    6215            2 : 
    6216            2 :         Ok(())
    6217            2 :     }
    6218              : 
    6219              :     #[tokio::test]
    6220            2 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6221            2 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6222            2 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6223            2 :         // create two timelines
    6224            2 :         {
    6225            2 :             let (tenant, ctx) = harness.load().await;
    6226            2 :             let tline = tenant
    6227            2 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6228            2 :                 .await?;
    6229            2 : 
    6230            2 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6231            2 : 
    6232            2 :             let child_tline = tenant
    6233            2 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6234            2 :                 .await?;
    6235            2 :             child_tline.set_state(TimelineState::Active);
    6236            2 : 
    6237            2 :             let newtline = tenant
    6238            2 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6239            2 :                 .expect("Should have a local timeline");
    6240            2 : 
    6241            2 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6242            2 : 
    6243            2 :             // so that all uploads finish & we can call harness.load() below again
    6244            2 :             tenant
    6245            2 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6246            2 :                 .instrument(harness.span())
    6247            2 :                 .await
    6248            2 :                 .ok()
    6249            2 :                 .unwrap();
    6250            2 :         }
    6251            2 : 
    6252            2 :         // check that both of them are initially unloaded
    6253            2 :         let (tenant, _ctx) = harness.load().await;
    6254            2 : 
    6255            2 :         // check that both, child and ancestor are loaded
    6256            2 :         let _child_tline = tenant
    6257            2 :             .get_timeline(NEW_TIMELINE_ID, true)
    6258            2 :             .expect("cannot get child timeline loaded");
    6259            2 : 
    6260            2 :         let _ancestor_tline = tenant
    6261            2 :             .get_timeline(TIMELINE_ID, true)
    6262            2 :             .expect("cannot get ancestor timeline loaded");
    6263            2 : 
    6264            2 :         Ok(())
    6265            2 :     }
    6266              : 
    6267              :     #[tokio::test]
    6268            2 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6269            2 :         use storage_layer::AsLayerDesc;
    6270            2 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6271            2 :             .await?
    6272            2 :             .load()
    6273            2 :             .await;
    6274            2 :         let tline = tenant
    6275            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6276            2 :             .await?;
    6277            2 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6278            2 : 
    6279            2 :         let layer_map = tline.layers.read().await;
    6280            2 :         let level0_deltas = layer_map
    6281            2 :             .layer_map()?
    6282            2 :             .level0_deltas()
    6283            2 :             .iter()
    6284            4 :             .map(|desc| layer_map.get_from_desc(desc))
    6285            2 :             .collect::<Vec<_>>();
    6286            2 : 
    6287            2 :         assert!(!level0_deltas.is_empty());
    6288            2 : 
    6289            6 :         for delta in level0_deltas {
    6290            2 :             // Ensure we are dumping a delta layer here
    6291            4 :             assert!(delta.layer_desc().is_delta);
    6292            4 :             delta.dump(true, &ctx).await.unwrap();
    6293            2 :         }
    6294            2 : 
    6295            2 :         Ok(())
    6296            2 :     }
    6297              : 
    6298              :     #[tokio::test]
    6299            2 :     async fn test_images() -> anyhow::Result<()> {
    6300            2 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6301            2 :         let tline = tenant
    6302            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6303            2 :             .await?;
    6304            2 : 
    6305            2 :         let mut writer = tline.writer().await;
    6306            2 :         writer
    6307            2 :             .put(
    6308            2 :                 *TEST_KEY,
    6309            2 :                 Lsn(0x10),
    6310            2 :                 &Value::Image(test_img("foo at 0x10")),
    6311            2 :                 &ctx,
    6312            2 :             )
    6313            2 :             .await?;
    6314            2 :         writer.finish_write(Lsn(0x10));
    6315            2 :         drop(writer);
    6316            2 : 
    6317            2 :         tline.freeze_and_flush().await?;
    6318            2 :         tline
    6319            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6320            2 :             .await?;
    6321            2 : 
    6322            2 :         let mut writer = tline.writer().await;
    6323            2 :         writer
    6324            2 :             .put(
    6325            2 :                 *TEST_KEY,
    6326            2 :                 Lsn(0x20),
    6327            2 :                 &Value::Image(test_img("foo at 0x20")),
    6328            2 :                 &ctx,
    6329            2 :             )
    6330            2 :             .await?;
    6331            2 :         writer.finish_write(Lsn(0x20));
    6332            2 :         drop(writer);
    6333            2 : 
    6334            2 :         tline.freeze_and_flush().await?;
    6335            2 :         tline
    6336            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6337            2 :             .await?;
    6338            2 : 
    6339            2 :         let mut writer = tline.writer().await;
    6340            2 :         writer
    6341            2 :             .put(
    6342            2 :                 *TEST_KEY,
    6343            2 :                 Lsn(0x30),
    6344            2 :                 &Value::Image(test_img("foo at 0x30")),
    6345            2 :                 &ctx,
    6346            2 :             )
    6347            2 :             .await?;
    6348            2 :         writer.finish_write(Lsn(0x30));
    6349            2 :         drop(writer);
    6350            2 : 
    6351            2 :         tline.freeze_and_flush().await?;
    6352            2 :         tline
    6353            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6354            2 :             .await?;
    6355            2 : 
    6356            2 :         let mut writer = tline.writer().await;
    6357            2 :         writer
    6358            2 :             .put(
    6359            2 :                 *TEST_KEY,
    6360            2 :                 Lsn(0x40),
    6361            2 :                 &Value::Image(test_img("foo at 0x40")),
    6362            2 :                 &ctx,
    6363            2 :             )
    6364            2 :             .await?;
    6365            2 :         writer.finish_write(Lsn(0x40));
    6366            2 :         drop(writer);
    6367            2 : 
    6368            2 :         tline.freeze_and_flush().await?;
    6369            2 :         tline
    6370            2 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6371            2 :             .await?;
    6372            2 : 
    6373            2 :         assert_eq!(
    6374            2 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6375            2 :             test_img("foo at 0x10")
    6376            2 :         );
    6377            2 :         assert_eq!(
    6378            2 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6379            2 :             test_img("foo at 0x10")
    6380            2 :         );
    6381            2 :         assert_eq!(
    6382            2 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6383            2 :             test_img("foo at 0x20")
    6384            2 :         );
    6385            2 :         assert_eq!(
    6386            2 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6387            2 :             test_img("foo at 0x30")
    6388            2 :         );
    6389            2 :         assert_eq!(
    6390            2 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6391            2 :             test_img("foo at 0x40")
    6392            2 :         );
    6393            2 : 
    6394            2 :         Ok(())
    6395            2 :     }
    6396              : 
    6397            4 :     async fn bulk_insert_compact_gc(
    6398            4 :         tenant: &Tenant,
    6399            4 :         timeline: &Arc<Timeline>,
    6400            4 :         ctx: &RequestContext,
    6401            4 :         lsn: Lsn,
    6402            4 :         repeat: usize,
    6403            4 :         key_count: usize,
    6404            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6405            4 :         let compact = true;
    6406            4 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6407            4 :     }
    6408              : 
    6409            8 :     async fn bulk_insert_maybe_compact_gc(
    6410            8 :         tenant: &Tenant,
    6411            8 :         timeline: &Arc<Timeline>,
    6412            8 :         ctx: &RequestContext,
    6413            8 :         mut lsn: Lsn,
    6414            8 :         repeat: usize,
    6415            8 :         key_count: usize,
    6416            8 :         compact: bool,
    6417            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6418            8 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6419            8 : 
    6420            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6421            8 :         let mut blknum = 0;
    6422            8 : 
    6423            8 :         // Enforce that key range is monotonously increasing
    6424            8 :         let mut keyspace = KeySpaceAccum::new();
    6425            8 : 
    6426            8 :         let cancel = CancellationToken::new();
    6427            8 : 
    6428            8 :         for _ in 0..repeat {
    6429          400 :             for _ in 0..key_count {
    6430      4000000 :                 test_key.field6 = blknum;
    6431      4000000 :                 let mut writer = timeline.writer().await;
    6432      4000000 :                 writer
    6433      4000000 :                     .put(
    6434      4000000 :                         test_key,
    6435      4000000 :                         lsn,
    6436      4000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6437      4000000 :                         ctx,
    6438      4000000 :                     )
    6439      4000000 :                     .await?;
    6440      4000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6441      4000000 :                 writer.finish_write(lsn);
    6442      4000000 :                 drop(writer);
    6443      4000000 : 
    6444      4000000 :                 keyspace.add_key(test_key);
    6445      4000000 : 
    6446      4000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6447      4000000 :                 blknum += 1;
    6448              :             }
    6449              : 
    6450          400 :             timeline.freeze_and_flush().await?;
    6451          400 :             if compact {
    6452              :                 // this requires timeline to be &Arc<Timeline>
    6453          200 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6454          200 :             }
    6455              : 
    6456              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6457              :             // originally was.
    6458          400 :             let res = tenant
    6459          400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6460          400 :                 .await?;
    6461              : 
    6462          400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6463              :         }
    6464              : 
    6465            8 :         Ok(inserted)
    6466            8 :     }
    6467              : 
    6468              :     //
    6469              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6470              :     // Repeat 50 times.
    6471              :     //
    6472              :     #[tokio::test]
    6473            2 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6474            2 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6475            2 :         let (tenant, ctx) = harness.load().await;
    6476            2 :         let tline = tenant
    6477            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6478            2 :             .await?;
    6479            2 : 
    6480            2 :         let lsn = Lsn(0x10);
    6481            2 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6482            2 : 
    6483            2 :         Ok(())
    6484            2 :     }
    6485              : 
    6486              :     // Test the vectored get real implementation against a simple sequential implementation.
    6487              :     //
    6488              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6489              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6490              :     // grow to the right on the X axis.
    6491              :     //                       [Delta]
    6492              :     //                 [Delta]
    6493              :     //           [Delta]
    6494              :     //    [Delta]
    6495              :     // ------------ Image ---------------
    6496              :     //
    6497              :     // After layer generation we pick the ranges to query as follows:
    6498              :     // 1. The beginning of each delta layer
    6499              :     // 2. At the seam between two adjacent delta layers
    6500              :     //
    6501              :     // There's one major downside to this test: delta layers only contains images,
    6502              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6503              :     #[tokio::test]
    6504            2 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6505            2 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6506            2 :         let (tenant, ctx) = harness.load().await;
    6507            2 :         let tline = tenant
    6508            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6509            2 :             .await?;
    6510            2 : 
    6511            2 :         let lsn = Lsn(0x10);
    6512            2 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6513            2 : 
    6514            2 :         let guard = tline.layers.read().await;
    6515            2 :         let lm = guard.layer_map()?;
    6516            2 : 
    6517            2 :         lm.dump(true, &ctx).await?;
    6518            2 : 
    6519            2 :         let mut reads = Vec::new();
    6520            2 :         let mut prev = None;
    6521           12 :         lm.iter_historic_layers().for_each(|desc| {
    6522           12 :             if !desc.is_delta() {
    6523            2 :                 prev = Some(desc.clone());
    6524            2 :                 return;
    6525           10 :             }
    6526           10 : 
    6527           10 :             let start = desc.key_range.start;
    6528           10 :             let end = desc
    6529           10 :                 .key_range
    6530           10 :                 .start
    6531           10 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6532           10 :             reads.push(KeySpace {
    6533           10 :                 ranges: vec![start..end],
    6534           10 :             });
    6535            2 : 
    6536           10 :             if let Some(prev) = &prev {
    6537           10 :                 if !prev.is_delta() {
    6538           10 :                     return;
    6539            2 :                 }
    6540            0 : 
    6541            0 :                 let first_range = Key {
    6542            0 :                     field6: prev.key_range.end.field6 - 4,
    6543            0 :                     ..prev.key_range.end
    6544            0 :                 }..prev.key_range.end;
    6545            0 : 
    6546            0 :                 let second_range = desc.key_range.start..Key {
    6547            0 :                     field6: desc.key_range.start.field6 + 4,
    6548            0 :                     ..desc.key_range.start
    6549            0 :                 };
    6550            0 : 
    6551            0 :                 reads.push(KeySpace {
    6552            0 :                     ranges: vec![first_range, second_range],
    6553            0 :                 });
    6554            2 :             };
    6555            2 : 
    6556            2 :             prev = Some(desc.clone());
    6557           12 :         });
    6558            2 : 
    6559            2 :         drop(guard);
    6560            2 : 
    6561            2 :         // Pick a big LSN such that we query over all the changes.
    6562            2 :         let reads_lsn = Lsn(u64::MAX - 1);
    6563            2 : 
    6564           12 :         for read in reads {
    6565           10 :             info!("Doing vectored read on {:?}", read);
    6566            2 : 
    6567           10 :             let vectored_res = tline
    6568           10 :                 .get_vectored_impl(
    6569           10 :                     read.clone(),
    6570           10 :                     reads_lsn,
    6571           10 :                     &mut ValuesReconstructState::new(),
    6572           10 :                     &ctx,
    6573           10 :                 )
    6574           10 :                 .await;
    6575            2 : 
    6576           10 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6577           10 :             let mut expect_missing = false;
    6578           10 :             let mut key = read.start().unwrap();
    6579          330 :             while key != read.end().unwrap() {
    6580          320 :                 if let Some(lsns) = inserted.get(&key) {
    6581          320 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6582          320 :                     match expected_lsn {
    6583          320 :                         Some(lsn) => {
    6584          320 :                             expected_lsns.insert(key, *lsn);
    6585          320 :                         }
    6586            2 :                         None => {
    6587            2 :                             expect_missing = true;
    6588            0 :                             break;
    6589            2 :                         }
    6590            2 :                     }
    6591            2 :                 } else {
    6592            2 :                     expect_missing = true;
    6593            0 :                     break;
    6594            2 :                 }
    6595            2 : 
    6596          320 :                 key = key.next();
    6597            2 :             }
    6598            2 : 
    6599           10 :             if expect_missing {
    6600            2 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6601            2 :             } else {
    6602          320 :                 for (key, image) in vectored_res? {
    6603          320 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6604          320 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6605          320 :                     assert_eq!(image?, expected_image);
    6606            2 :                 }
    6607            2 :             }
    6608            2 :         }
    6609            2 : 
    6610            2 :         Ok(())
    6611            2 :     }
    6612              : 
    6613              :     #[tokio::test]
    6614            2 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6615            2 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6616            2 : 
    6617            2 :         let (tenant, ctx) = harness.load().await;
    6618            2 :         let tline = tenant
    6619            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6620            2 :             .await?;
    6621            2 :         let tline = tline.raw_timeline().unwrap();
    6622            2 : 
    6623            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6624            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6625            2 :         modification.set_lsn(Lsn(0x1008))?;
    6626            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6627            2 :         modification.commit(&ctx).await?;
    6628            2 : 
    6629            2 :         let child_timeline_id = TimelineId::generate();
    6630            2 :         tenant
    6631            2 :             .branch_timeline_test(
    6632            2 :                 tline,
    6633            2 :                 child_timeline_id,
    6634            2 :                 Some(tline.get_last_record_lsn()),
    6635            2 :                 &ctx,
    6636            2 :             )
    6637            2 :             .await?;
    6638            2 : 
    6639            2 :         let child_timeline = tenant
    6640            2 :             .get_timeline(child_timeline_id, true)
    6641            2 :             .expect("Should have the branched timeline");
    6642            2 : 
    6643            2 :         let aux_keyspace = KeySpace {
    6644            2 :             ranges: vec![NON_INHERITED_RANGE],
    6645            2 :         };
    6646            2 :         let read_lsn = child_timeline.get_last_record_lsn();
    6647            2 : 
    6648            2 :         let vectored_res = child_timeline
    6649            2 :             .get_vectored_impl(
    6650            2 :                 aux_keyspace.clone(),
    6651            2 :                 read_lsn,
    6652            2 :                 &mut ValuesReconstructState::new(),
    6653            2 :                 &ctx,
    6654            2 :             )
    6655            2 :             .await;
    6656            2 : 
    6657            2 :         let images = vectored_res?;
    6658            2 :         assert!(images.is_empty());
    6659            2 :         Ok(())
    6660            2 :     }
    6661              : 
    6662              :     // Test that vectored get handles layer gaps correctly
    6663              :     // by advancing into the next ancestor timeline if required.
    6664              :     //
    6665              :     // The test generates timelines that look like the diagram below.
    6666              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6667              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6668              :     //
    6669              :     // ```
    6670              :     //-------------------------------+
    6671              :     //                          ...  |
    6672              :     //               [   L1   ]      |
    6673              :     //     [ / L1   ]                | Child Timeline
    6674              :     // ...                           |
    6675              :     // ------------------------------+
    6676              :     //     [ X L1   ]                | Parent Timeline
    6677              :     // ------------------------------+
    6678              :     // ```
    6679              :     #[tokio::test]
    6680            2 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6681            2 :         let tenant_conf = TenantConf {
    6682            2 :             // Make compaction deterministic
    6683            2 :             gc_period: Duration::ZERO,
    6684            2 :             compaction_period: Duration::ZERO,
    6685            2 :             // Encourage creation of L1 layers
    6686            2 :             checkpoint_distance: 16 * 1024,
    6687            2 :             compaction_target_size: 8 * 1024,
    6688            2 :             ..TenantConf::default()
    6689            2 :         };
    6690            2 : 
    6691            2 :         let harness = TenantHarness::create_custom(
    6692            2 :             "test_get_vectored_key_gap",
    6693            2 :             tenant_conf,
    6694            2 :             TenantId::generate(),
    6695            2 :             ShardIdentity::unsharded(),
    6696            2 :             Generation::new(0xdeadbeef),
    6697            2 :         )
    6698            2 :         .await?;
    6699            2 :         let (tenant, ctx) = harness.load().await;
    6700            2 : 
    6701            2 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6702            2 :         let gap_at_key = current_key.add(100);
    6703            2 :         let mut current_lsn = Lsn(0x10);
    6704            2 : 
    6705            2 :         const KEY_COUNT: usize = 10_000;
    6706            2 : 
    6707            2 :         let timeline_id = TimelineId::generate();
    6708            2 :         let current_timeline = tenant
    6709            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6710            2 :             .await?;
    6711            2 : 
    6712            2 :         current_lsn += 0x100;
    6713            2 : 
    6714            2 :         let mut writer = current_timeline.writer().await;
    6715            2 :         writer
    6716            2 :             .put(
    6717            2 :                 gap_at_key,
    6718            2 :                 current_lsn,
    6719            2 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6720            2 :                 &ctx,
    6721            2 :             )
    6722            2 :             .await?;
    6723            2 :         writer.finish_write(current_lsn);
    6724            2 :         drop(writer);
    6725            2 : 
    6726            2 :         let mut latest_lsns = HashMap::new();
    6727            2 :         latest_lsns.insert(gap_at_key, current_lsn);
    6728            2 : 
    6729            2 :         current_timeline.freeze_and_flush().await?;
    6730            2 : 
    6731            2 :         let child_timeline_id = TimelineId::generate();
    6732            2 : 
    6733            2 :         tenant
    6734            2 :             .branch_timeline_test(
    6735            2 :                 &current_timeline,
    6736            2 :                 child_timeline_id,
    6737            2 :                 Some(current_lsn),
    6738            2 :                 &ctx,
    6739            2 :             )
    6740            2 :             .await?;
    6741            2 :         let child_timeline = tenant
    6742            2 :             .get_timeline(child_timeline_id, true)
    6743            2 :             .expect("Should have the branched timeline");
    6744            2 : 
    6745        20002 :         for i in 0..KEY_COUNT {
    6746        20000 :             if current_key == gap_at_key {
    6747            2 :                 current_key = current_key.next();
    6748            2 :                 continue;
    6749        19998 :             }
    6750        19998 : 
    6751        19998 :             current_lsn += 0x10;
    6752            2 : 
    6753        19998 :             let mut writer = child_timeline.writer().await;
    6754        19998 :             writer
    6755        19998 :                 .put(
    6756        19998 :                     current_key,
    6757        19998 :                     current_lsn,
    6758        19998 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6759        19998 :                     &ctx,
    6760        19998 :                 )
    6761        19998 :                 .await?;
    6762        19998 :             writer.finish_write(current_lsn);
    6763        19998 :             drop(writer);
    6764        19998 : 
    6765        19998 :             latest_lsns.insert(current_key, current_lsn);
    6766        19998 :             current_key = current_key.next();
    6767        19998 : 
    6768        19998 :             // Flush every now and then to encourage layer file creation.
    6769        19998 :             if i % 500 == 0 {
    6770           40 :                 child_timeline.freeze_and_flush().await?;
    6771        19958 :             }
    6772            2 :         }
    6773            2 : 
    6774            2 :         child_timeline.freeze_and_flush().await?;
    6775            2 :         let mut flags = EnumSet::new();
    6776            2 :         flags.insert(CompactFlags::ForceRepartition);
    6777            2 :         child_timeline
    6778            2 :             .compact(&CancellationToken::new(), flags, &ctx)
    6779            2 :             .await?;
    6780            2 : 
    6781            2 :         let key_near_end = {
    6782            2 :             let mut tmp = current_key;
    6783            2 :             tmp.field6 -= 10;
    6784            2 :             tmp
    6785            2 :         };
    6786            2 : 
    6787            2 :         let key_near_gap = {
    6788            2 :             let mut tmp = gap_at_key;
    6789            2 :             tmp.field6 -= 10;
    6790            2 :             tmp
    6791            2 :         };
    6792            2 : 
    6793            2 :         let read = KeySpace {
    6794            2 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6795            2 :         };
    6796            2 :         let results = child_timeline
    6797            2 :             .get_vectored_impl(
    6798            2 :                 read.clone(),
    6799            2 :                 current_lsn,
    6800            2 :                 &mut ValuesReconstructState::new(),
    6801            2 :                 &ctx,
    6802            2 :             )
    6803            2 :             .await?;
    6804            2 : 
    6805           44 :         for (key, img_res) in results {
    6806           42 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6807           42 :             assert_eq!(img_res?, expected);
    6808            2 :         }
    6809            2 : 
    6810            2 :         Ok(())
    6811            2 :     }
    6812              : 
    6813              :     // Test that vectored get descends into ancestor timelines correctly and
    6814              :     // does not return an image that's newer than requested.
    6815              :     //
    6816              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    6817              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    6818              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    6819              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    6820              :     // order to avoid returning an image that's too new. The test below constructs such
    6821              :     // a timeline setup and does a few queries around the Lsn of each page image.
    6822              :     // ```
    6823              :     //    LSN
    6824              :     //     ^
    6825              :     //     |
    6826              :     //     |
    6827              :     // 500 | --------------------------------------> branch point
    6828              :     // 400 |        X
    6829              :     // 300 |        X
    6830              :     // 200 | --------------------------------------> requested lsn
    6831              :     // 100 |        X
    6832              :     //     |---------------------------------------> Key
    6833              :     //              |
    6834              :     //              ------> requested key
    6835              :     //
    6836              :     // Legend:
    6837              :     // * X - page images
    6838              :     // ```
    6839              :     #[tokio::test]
    6840            2 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    6841            2 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    6842            2 :         let (tenant, ctx) = harness.load().await;
    6843            2 : 
    6844            2 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6845            2 :         let end_key = start_key.add(1000);
    6846            2 :         let child_gap_at_key = start_key.add(500);
    6847            2 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    6848            2 : 
    6849            2 :         let mut current_lsn = Lsn(0x10);
    6850            2 : 
    6851            2 :         let timeline_id = TimelineId::generate();
    6852            2 :         let parent_timeline = tenant
    6853            2 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6854            2 :             .await?;
    6855            2 : 
    6856            2 :         current_lsn += 0x100;
    6857            2 : 
    6858            8 :         for _ in 0..3 {
    6859            6 :             let mut key = start_key;
    6860         6006 :             while key < end_key {
    6861         6000 :                 current_lsn += 0x10;
    6862         6000 : 
    6863         6000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    6864            2 : 
    6865         6000 :                 let mut writer = parent_timeline.writer().await;
    6866         6000 :                 writer
    6867         6000 :                     .put(
    6868         6000 :                         key,
    6869         6000 :                         current_lsn,
    6870         6000 :                         &Value::Image(test_img(&image_value)),
    6871         6000 :                         &ctx,
    6872         6000 :                     )
    6873         6000 :                     .await?;
    6874         6000 :                 writer.finish_write(current_lsn);
    6875         6000 : 
    6876         6000 :                 if key == child_gap_at_key {
    6877            6 :                     parent_gap_lsns.insert(current_lsn, image_value);
    6878         5994 :                 }
    6879            2 : 
    6880         6000 :                 key = key.next();
    6881            2 :             }
    6882            2 : 
    6883            6 :             parent_timeline.freeze_and_flush().await?;
    6884            2 :         }
    6885            2 : 
    6886            2 :         let child_timeline_id = TimelineId::generate();
    6887            2 : 
    6888            2 :         let child_timeline = tenant
    6889            2 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    6890            2 :             .await?;
    6891            2 : 
    6892            2 :         let mut key = start_key;
    6893         2002 :         while key < end_key {
    6894         2000 :             if key == child_gap_at_key {
    6895            2 :                 key = key.next();
    6896            2 :                 continue;
    6897         1998 :             }
    6898         1998 : 
    6899         1998 :             current_lsn += 0x10;
    6900            2 : 
    6901         1998 :             let mut writer = child_timeline.writer().await;
    6902         1998 :             writer
    6903         1998 :                 .put(
    6904         1998 :                     key,
    6905         1998 :                     current_lsn,
    6906         1998 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    6907         1998 :                     &ctx,
    6908         1998 :                 )
    6909         1998 :                 .await?;
    6910         1998 :             writer.finish_write(current_lsn);
    6911         1998 : 
    6912         1998 :             key = key.next();
    6913            2 :         }
    6914            2 : 
    6915            2 :         child_timeline.freeze_and_flush().await?;
    6916            2 : 
    6917            2 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    6918            2 :         let mut query_lsns = Vec::new();
    6919            6 :         for image_lsn in parent_gap_lsns.keys().rev() {
    6920           36 :             for offset in lsn_offsets {
    6921           30 :                 query_lsns.push(Lsn(image_lsn
    6922           30 :                     .0
    6923           30 :                     .checked_add_signed(offset)
    6924           30 :                     .expect("Shouldn't overflow")));
    6925           30 :             }
    6926            2 :         }
    6927            2 : 
    6928           32 :         for query_lsn in query_lsns {
    6929           30 :             let results = child_timeline
    6930           30 :                 .get_vectored_impl(
    6931           30 :                     KeySpace {
    6932           30 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    6933           30 :                     },
    6934           30 :                     query_lsn,
    6935           30 :                     &mut ValuesReconstructState::new(),
    6936           30 :                     &ctx,
    6937           30 :                 )
    6938           30 :                 .await;
    6939            2 : 
    6940           30 :             let expected_item = parent_gap_lsns
    6941           30 :                 .iter()
    6942           30 :                 .rev()
    6943           68 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    6944           30 : 
    6945           30 :             info!(
    6946            2 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    6947            2 :                 query_lsn, expected_item
    6948            2 :             );
    6949            2 : 
    6950           30 :             match expected_item {
    6951           26 :                 Some((_, img_value)) => {
    6952           26 :                     let key_results = results.expect("No vectored get error expected");
    6953           26 :                     let key_result = &key_results[&child_gap_at_key];
    6954           26 :                     let returned_img = key_result
    6955           26 :                         .as_ref()
    6956           26 :                         .expect("No page reconstruct error expected");
    6957           26 : 
    6958           26 :                     info!(
    6959            2 :                         "Vectored read at LSN {} returned image {}",
    6960            0 :                         query_lsn,
    6961            0 :                         std::str::from_utf8(returned_img)?
    6962            2 :                     );
    6963           26 :                     assert_eq!(*returned_img, test_img(img_value));
    6964            2 :                 }
    6965            2 :                 None => {
    6966            4 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    6967            2 :                 }
    6968            2 :             }
    6969            2 :         }
    6970            2 : 
    6971            2 :         Ok(())
    6972            2 :     }
    6973              : 
    6974              :     #[tokio::test]
    6975            2 :     async fn test_random_updates() -> anyhow::Result<()> {
    6976            2 :         let names_algorithms = [
    6977            2 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    6978            2 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    6979            2 :         ];
    6980            6 :         for (name, algorithm) in names_algorithms {
    6981            4 :             test_random_updates_algorithm(name, algorithm).await?;
    6982            2 :         }
    6983            2 :         Ok(())
    6984            2 :     }
    6985              : 
    6986            4 :     async fn test_random_updates_algorithm(
    6987            4 :         name: &'static str,
    6988            4 :         compaction_algorithm: CompactionAlgorithm,
    6989            4 :     ) -> anyhow::Result<()> {
    6990            4 :         let mut harness = TenantHarness::create(name).await?;
    6991            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    6992            4 :             kind: compaction_algorithm,
    6993            4 :         };
    6994            4 :         let (tenant, ctx) = harness.load().await;
    6995            4 :         let tline = tenant
    6996            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6997            4 :             .await?;
    6998              : 
    6999              :         const NUM_KEYS: usize = 1000;
    7000            4 :         let cancel = CancellationToken::new();
    7001            4 : 
    7002            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7003            4 :         let mut test_key_end = test_key;
    7004            4 :         test_key_end.field6 = NUM_KEYS as u32;
    7005            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7006            4 : 
    7007            4 :         let mut keyspace = KeySpaceAccum::new();
    7008            4 : 
    7009            4 :         // Track when each page was last modified. Used to assert that
    7010            4 :         // a read sees the latest page version.
    7011            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7012            4 : 
    7013            4 :         let mut lsn = Lsn(0x10);
    7014              :         #[allow(clippy::needless_range_loop)]
    7015         4004 :         for blknum in 0..NUM_KEYS {
    7016         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7017         4000 :             test_key.field6 = blknum as u32;
    7018         4000 :             let mut writer = tline.writer().await;
    7019         4000 :             writer
    7020         4000 :                 .put(
    7021         4000 :                     test_key,
    7022         4000 :                     lsn,
    7023         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7024         4000 :                     &ctx,
    7025         4000 :                 )
    7026         4000 :                 .await?;
    7027         4000 :             writer.finish_write(lsn);
    7028         4000 :             updated[blknum] = lsn;
    7029         4000 :             drop(writer);
    7030         4000 : 
    7031         4000 :             keyspace.add_key(test_key);
    7032              :         }
    7033              : 
    7034          204 :         for _ in 0..50 {
    7035       200200 :             for _ in 0..NUM_KEYS {
    7036       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7037       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7038       200000 :                 test_key.field6 = blknum as u32;
    7039       200000 :                 let mut writer = tline.writer().await;
    7040       200000 :                 writer
    7041       200000 :                     .put(
    7042       200000 :                         test_key,
    7043       200000 :                         lsn,
    7044       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7045       200000 :                         &ctx,
    7046       200000 :                     )
    7047       200000 :                     .await?;
    7048       200000 :                 writer.finish_write(lsn);
    7049       200000 :                 drop(writer);
    7050       200000 :                 updated[blknum] = lsn;
    7051              :             }
    7052              : 
    7053              :             // Read all the blocks
    7054       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7055       200000 :                 test_key.field6 = blknum as u32;
    7056       200000 :                 assert_eq!(
    7057       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7058       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7059              :                 );
    7060              :             }
    7061              : 
    7062              :             // Perform a cycle of flush, and GC
    7063          200 :             tline.freeze_and_flush().await?;
    7064          200 :             tenant
    7065          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7066          200 :                 .await?;
    7067              :         }
    7068              : 
    7069            4 :         Ok(())
    7070            4 :     }
    7071              : 
    7072              :     #[tokio::test]
    7073            2 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7074            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7075            2 :             .await?
    7076            2 :             .load()
    7077            2 :             .await;
    7078            2 :         let mut tline = tenant
    7079            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7080            2 :             .await?;
    7081            2 : 
    7082            2 :         const NUM_KEYS: usize = 1000;
    7083            2 : 
    7084            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7085            2 : 
    7086            2 :         let mut keyspace = KeySpaceAccum::new();
    7087            2 : 
    7088            2 :         let cancel = CancellationToken::new();
    7089            2 : 
    7090            2 :         // Track when each page was last modified. Used to assert that
    7091            2 :         // a read sees the latest page version.
    7092            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7093            2 : 
    7094            2 :         let mut lsn = Lsn(0x10);
    7095            2 :         #[allow(clippy::needless_range_loop)]
    7096         2002 :         for blknum in 0..NUM_KEYS {
    7097         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7098         2000 :             test_key.field6 = blknum as u32;
    7099         2000 :             let mut writer = tline.writer().await;
    7100         2000 :             writer
    7101         2000 :                 .put(
    7102         2000 :                     test_key,
    7103         2000 :                     lsn,
    7104         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7105         2000 :                     &ctx,
    7106         2000 :                 )
    7107         2000 :                 .await?;
    7108         2000 :             writer.finish_write(lsn);
    7109         2000 :             updated[blknum] = lsn;
    7110         2000 :             drop(writer);
    7111         2000 : 
    7112         2000 :             keyspace.add_key(test_key);
    7113            2 :         }
    7114            2 : 
    7115          102 :         for _ in 0..50 {
    7116          100 :             let new_tline_id = TimelineId::generate();
    7117          100 :             tenant
    7118          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7119          100 :                 .await?;
    7120          100 :             tline = tenant
    7121          100 :                 .get_timeline(new_tline_id, true)
    7122          100 :                 .expect("Should have the branched timeline");
    7123            2 : 
    7124       100100 :             for _ in 0..NUM_KEYS {
    7125       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7126       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7127       100000 :                 test_key.field6 = blknum as u32;
    7128       100000 :                 let mut writer = tline.writer().await;
    7129       100000 :                 writer
    7130       100000 :                     .put(
    7131       100000 :                         test_key,
    7132       100000 :                         lsn,
    7133       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7134       100000 :                         &ctx,
    7135       100000 :                     )
    7136       100000 :                     .await?;
    7137       100000 :                 println!("updating {} at {}", blknum, lsn);
    7138       100000 :                 writer.finish_write(lsn);
    7139       100000 :                 drop(writer);
    7140       100000 :                 updated[blknum] = lsn;
    7141            2 :             }
    7142            2 : 
    7143            2 :             // Read all the blocks
    7144       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7145       100000 :                 test_key.field6 = blknum as u32;
    7146       100000 :                 assert_eq!(
    7147       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7148       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7149            2 :                 );
    7150            2 :             }
    7151            2 : 
    7152            2 :             // Perform a cycle of flush, compact, and GC
    7153          100 :             tline.freeze_and_flush().await?;
    7154          100 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7155          100 :             tenant
    7156          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7157          100 :                 .await?;
    7158            2 :         }
    7159            2 : 
    7160            2 :         Ok(())
    7161            2 :     }
    7162              : 
    7163              :     #[tokio::test]
    7164            2 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7165            2 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7166            2 :             .await?
    7167            2 :             .load()
    7168            2 :             .await;
    7169            2 :         let mut tline = tenant
    7170            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7171            2 :             .await?;
    7172            2 : 
    7173            2 :         const NUM_KEYS: usize = 100;
    7174            2 :         const NUM_TLINES: usize = 50;
    7175            2 : 
    7176            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7177            2 :         // Track page mutation lsns across different timelines.
    7178            2 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7179            2 : 
    7180            2 :         let mut lsn = Lsn(0x10);
    7181            2 : 
    7182            2 :         #[allow(clippy::needless_range_loop)]
    7183          102 :         for idx in 0..NUM_TLINES {
    7184          100 :             let new_tline_id = TimelineId::generate();
    7185          100 :             tenant
    7186          100 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7187          100 :                 .await?;
    7188          100 :             tline = tenant
    7189          100 :                 .get_timeline(new_tline_id, true)
    7190          100 :                 .expect("Should have the branched timeline");
    7191            2 : 
    7192        10100 :             for _ in 0..NUM_KEYS {
    7193        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    7194        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7195        10000 :                 test_key.field6 = blknum as u32;
    7196        10000 :                 let mut writer = tline.writer().await;
    7197        10000 :                 writer
    7198        10000 :                     .put(
    7199        10000 :                         test_key,
    7200        10000 :                         lsn,
    7201        10000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7202        10000 :                         &ctx,
    7203        10000 :                     )
    7204        10000 :                     .await?;
    7205        10000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7206        10000 :                 writer.finish_write(lsn);
    7207        10000 :                 drop(writer);
    7208        10000 :                 updated[idx][blknum] = lsn;
    7209            2 :             }
    7210            2 :         }
    7211            2 : 
    7212            2 :         // Read pages from leaf timeline across all ancestors.
    7213          100 :         for (idx, lsns) in updated.iter().enumerate() {
    7214        10000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7215            2 :                 // Skip empty mutations.
    7216        10000 :                 if lsn.0 == 0 {
    7217         3680 :                     continue;
    7218         6320 :                 }
    7219         6320 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7220         6320 :                 test_key.field6 = blknum as u32;
    7221         6320 :                 assert_eq!(
    7222         6320 :                     tline.get(test_key, *lsn, &ctx).await?,
    7223         6320 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7224            2 :                 );
    7225            2 :             }
    7226            2 :         }
    7227            2 :         Ok(())
    7228            2 :     }
    7229              : 
    7230              :     #[tokio::test]
    7231            2 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7232            2 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7233            2 :             .await?
    7234            2 :             .load()
    7235            2 :             .await;
    7236            2 : 
    7237            2 :         let initdb_lsn = Lsn(0x20);
    7238            2 :         let utline = tenant
    7239            2 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7240            2 :             .await?;
    7241            2 :         let tline = utline.raw_timeline().unwrap();
    7242            2 : 
    7243            2 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7244            2 :         tline.maybe_spawn_flush_loop();
    7245            2 : 
    7246            2 :         // Make sure the timeline has the minimum set of required keys for operation.
    7247            2 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7248            2 :         // Except if you `put` at `initdb_lsn`.
    7249            2 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7250            2 :         // It uses `repartition()`, which assumes some keys to be present.
    7251            2 :         // Let's make sure the test timeline can handle that case.
    7252            2 :         {
    7253            2 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7254            2 :             assert_eq!(
    7255            2 :                 timeline::FlushLoopState::Running {
    7256            2 :                     expect_initdb_optimization: false,
    7257            2 :                     initdb_optimization_count: 0,
    7258            2 :                 },
    7259            2 :                 *state
    7260            2 :             );
    7261            2 :             *state = timeline::FlushLoopState::Running {
    7262            2 :                 expect_initdb_optimization: true,
    7263            2 :                 initdb_optimization_count: 0,
    7264            2 :             };
    7265            2 :         }
    7266            2 : 
    7267            2 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7268            2 :         // As explained above, the optimization requires some keys to be present.
    7269            2 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7270            2 :         // This is what `create_test_timeline` does, by the way.
    7271            2 :         let mut modification = tline.begin_modification(initdb_lsn);
    7272            2 :         modification
    7273            2 :             .init_empty_test_timeline()
    7274            2 :             .context("init_empty_test_timeline")?;
    7275            2 :         modification
    7276            2 :             .commit(&ctx)
    7277            2 :             .await
    7278            2 :             .context("commit init_empty_test_timeline modification")?;
    7279            2 : 
    7280            2 :         // Do the flush. The flush code will check the expectations that we set above.
    7281            2 :         tline.freeze_and_flush().await?;
    7282            2 : 
    7283            2 :         // assert freeze_and_flush exercised the initdb optimization
    7284            2 :         {
    7285            2 :             let state = tline.flush_loop_state.lock().unwrap();
    7286            2 :             let timeline::FlushLoopState::Running {
    7287            2 :                 expect_initdb_optimization,
    7288            2 :                 initdb_optimization_count,
    7289            2 :             } = *state
    7290            2 :             else {
    7291            2 :                 panic!("unexpected state: {:?}", *state);
    7292            2 :             };
    7293            2 :             assert!(expect_initdb_optimization);
    7294            2 :             assert!(initdb_optimization_count > 0);
    7295            2 :         }
    7296            2 :         Ok(())
    7297            2 :     }
    7298              : 
    7299              :     #[tokio::test]
    7300            2 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7301            2 :         let name = "test_create_guard_crash";
    7302            2 :         let harness = TenantHarness::create(name).await?;
    7303            2 :         {
    7304            2 :             let (tenant, ctx) = harness.load().await;
    7305            2 :             let tline = tenant
    7306            2 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7307            2 :                 .await?;
    7308            2 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7309            2 :             let raw_tline = tline.raw_timeline().unwrap();
    7310            2 :             raw_tline
    7311            2 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7312            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))
    7313            2 :                 .await;
    7314            2 :             std::mem::forget(tline);
    7315            2 :         }
    7316            2 : 
    7317            2 :         let (tenant, _) = harness.load().await;
    7318            2 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7319            2 :             Ok(_) => panic!("timeline should've been removed during load"),
    7320            2 :             Err(e) => {
    7321            2 :                 assert_eq!(
    7322            2 :                     e,
    7323            2 :                     GetTimelineError::NotFound {
    7324            2 :                         tenant_id: tenant.tenant_shard_id,
    7325            2 :                         timeline_id: TIMELINE_ID,
    7326            2 :                     }
    7327            2 :                 )
    7328            2 :             }
    7329            2 :         }
    7330            2 : 
    7331            2 :         assert!(!harness
    7332            2 :             .conf
    7333            2 :             .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7334            2 :             .exists());
    7335            2 : 
    7336            2 :         Ok(())
    7337            2 :     }
    7338              : 
    7339              :     #[tokio::test]
    7340            2 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7341            2 :         let names_algorithms = [
    7342            2 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7343            2 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7344            2 :         ];
    7345            6 :         for (name, algorithm) in names_algorithms {
    7346            4 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7347            2 :         }
    7348            2 :         Ok(())
    7349            2 :     }
    7350              : 
    7351            4 :     async fn test_read_at_max_lsn_algorithm(
    7352            4 :         name: &'static str,
    7353            4 :         compaction_algorithm: CompactionAlgorithm,
    7354            4 :     ) -> anyhow::Result<()> {
    7355            4 :         let mut harness = TenantHarness::create(name).await?;
    7356            4 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7357            4 :             kind: compaction_algorithm,
    7358            4 :         };
    7359            4 :         let (tenant, ctx) = harness.load().await;
    7360            4 :         let tline = tenant
    7361            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7362            4 :             .await?;
    7363              : 
    7364            4 :         let lsn = Lsn(0x10);
    7365            4 :         let compact = false;
    7366            4 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7367              : 
    7368            4 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7369            4 :         let read_lsn = Lsn(u64::MAX - 1);
    7370              : 
    7371            4 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7372            4 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7373              : 
    7374            4 :         Ok(())
    7375            4 :     }
    7376              : 
    7377              :     #[tokio::test]
    7378            2 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7379            2 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7380            2 :         let (tenant, ctx) = harness.load().await;
    7381            2 :         let tline = tenant
    7382            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7383            2 :             .await?;
    7384            2 : 
    7385            2 :         const NUM_KEYS: usize = 1000;
    7386            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7387            2 : 
    7388            2 :         let cancel = CancellationToken::new();
    7389            2 : 
    7390            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7391            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7392            2 :         let mut test_key = base_key;
    7393            2 : 
    7394            2 :         // Track when each page was last modified. Used to assert that
    7395            2 :         // a read sees the latest page version.
    7396            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7397            2 : 
    7398            2 :         let mut lsn = Lsn(0x10);
    7399            2 :         #[allow(clippy::needless_range_loop)]
    7400         2002 :         for blknum in 0..NUM_KEYS {
    7401         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7402         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7403         2000 :             let mut writer = tline.writer().await;
    7404         2000 :             writer
    7405         2000 :                 .put(
    7406         2000 :                     test_key,
    7407         2000 :                     lsn,
    7408         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7409         2000 :                     &ctx,
    7410         2000 :                 )
    7411         2000 :                 .await?;
    7412         2000 :             writer.finish_write(lsn);
    7413         2000 :             updated[blknum] = lsn;
    7414         2000 :             drop(writer);
    7415            2 :         }
    7416            2 : 
    7417            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7418            2 : 
    7419           24 :         for iter in 0..=10 {
    7420            2 :             // Read all the blocks
    7421        22000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7422        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7423        22000 :                 assert_eq!(
    7424        22000 :                     tline.get(test_key, lsn, &ctx).await?,
    7425        22000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7426            2 :                 );
    7427            2 :             }
    7428            2 : 
    7429           22 :             let mut cnt = 0;
    7430        22000 :             for (key, value) in tline
    7431           22 :                 .get_vectored_impl(
    7432           22 :                     keyspace.clone(),
    7433           22 :                     lsn,
    7434           22 :                     &mut ValuesReconstructState::default(),
    7435           22 :                     &ctx,
    7436           22 :                 )
    7437           22 :                 .await?
    7438            2 :             {
    7439        22000 :                 let blknum = key.field6 as usize;
    7440        22000 :                 let value = value?;
    7441        22000 :                 assert!(blknum % STEP == 0);
    7442        22000 :                 let blknum = blknum / STEP;
    7443        22000 :                 assert_eq!(
    7444        22000 :                     value,
    7445        22000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7446        22000 :                 );
    7447        22000 :                 cnt += 1;
    7448            2 :             }
    7449            2 : 
    7450           22 :             assert_eq!(cnt, NUM_KEYS);
    7451            2 : 
    7452        22022 :             for _ in 0..NUM_KEYS {
    7453        22000 :                 lsn = Lsn(lsn.0 + 0x10);
    7454        22000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7455        22000 :                 test_key.field6 = (blknum * STEP) as u32;
    7456        22000 :                 let mut writer = tline.writer().await;
    7457        22000 :                 writer
    7458        22000 :                     .put(
    7459        22000 :                         test_key,
    7460        22000 :                         lsn,
    7461        22000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7462        22000 :                         &ctx,
    7463        22000 :                     )
    7464        22000 :                     .await?;
    7465        22000 :                 writer.finish_write(lsn);
    7466        22000 :                 drop(writer);
    7467        22000 :                 updated[blknum] = lsn;
    7468            2 :             }
    7469            2 : 
    7470            2 :             // Perform two cycles of flush, compact, and GC
    7471           66 :             for round in 0..2 {
    7472           44 :                 tline.freeze_and_flush().await?;
    7473           44 :                 tline
    7474           44 :                     .compact(
    7475           44 :                         &cancel,
    7476           44 :                         if iter % 5 == 0 && round == 0 {
    7477            6 :                             let mut flags = EnumSet::new();
    7478            6 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7479            6 :                             flags.insert(CompactFlags::ForceRepartition);
    7480            6 :                             flags
    7481            2 :                         } else {
    7482           38 :                             EnumSet::empty()
    7483            2 :                         },
    7484           44 :                         &ctx,
    7485           44 :                     )
    7486           44 :                     .await?;
    7487           44 :                 tenant
    7488           44 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7489           44 :                     .await?;
    7490            2 :             }
    7491            2 :         }
    7492            2 : 
    7493            2 :         Ok(())
    7494            2 :     }
    7495              : 
    7496              :     #[tokio::test]
    7497            2 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7498            2 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7499            2 :         let (tenant, ctx) = harness.load().await;
    7500            2 :         let tline = tenant
    7501            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7502            2 :             .await?;
    7503            2 : 
    7504            2 :         let cancel = CancellationToken::new();
    7505            2 : 
    7506            2 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7507            2 :         base_key.field1 = AUX_KEY_PREFIX;
    7508            2 :         let test_key = base_key;
    7509            2 :         let mut lsn = Lsn(0x10);
    7510            2 : 
    7511           42 :         for _ in 0..20 {
    7512           40 :             lsn = Lsn(lsn.0 + 0x10);
    7513           40 :             let mut writer = tline.writer().await;
    7514           40 :             writer
    7515           40 :                 .put(
    7516           40 :                     test_key,
    7517           40 :                     lsn,
    7518           40 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7519           40 :                     &ctx,
    7520           40 :                 )
    7521           40 :                 .await?;
    7522           40 :             writer.finish_write(lsn);
    7523           40 :             drop(writer);
    7524           40 :             tline.freeze_and_flush().await?; // force create a delta layer
    7525            2 :         }
    7526            2 : 
    7527            2 :         let before_num_l0_delta_files =
    7528            2 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7529            2 : 
    7530            2 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7531            2 : 
    7532            2 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7533            2 : 
    7534            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}");
    7535            2 : 
    7536            2 :         assert_eq!(
    7537            2 :             tline.get(test_key, lsn, &ctx).await?,
    7538            2 :             test_img(&format!("{} at {}", 0, lsn))
    7539            2 :         );
    7540            2 : 
    7541            2 :         Ok(())
    7542            2 :     }
    7543              : 
    7544              :     #[tokio::test]
    7545            2 :     async fn test_aux_file_e2e() {
    7546            2 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7547            2 : 
    7548            2 :         let (tenant, ctx) = harness.load().await;
    7549            2 : 
    7550            2 :         let mut lsn = Lsn(0x08);
    7551            2 : 
    7552            2 :         let tline: Arc<Timeline> = tenant
    7553            2 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7554            2 :             .await
    7555            2 :             .unwrap();
    7556            2 : 
    7557            2 :         {
    7558            2 :             lsn += 8;
    7559            2 :             let mut modification = tline.begin_modification(lsn);
    7560            2 :             modification
    7561            2 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7562            2 :                 .await
    7563            2 :                 .unwrap();
    7564            2 :             modification.commit(&ctx).await.unwrap();
    7565            2 :         }
    7566            2 : 
    7567            2 :         // we can read everything from the storage
    7568            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7569            2 :         assert_eq!(
    7570            2 :             files.get("pg_logical/mappings/test1"),
    7571            2 :             Some(&bytes::Bytes::from_static(b"first"))
    7572            2 :         );
    7573            2 : 
    7574            2 :         {
    7575            2 :             lsn += 8;
    7576            2 :             let mut modification = tline.begin_modification(lsn);
    7577            2 :             modification
    7578            2 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7579            2 :                 .await
    7580            2 :                 .unwrap();
    7581            2 :             modification.commit(&ctx).await.unwrap();
    7582            2 :         }
    7583            2 : 
    7584            2 :         let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
    7585            2 :         assert_eq!(
    7586            2 :             files.get("pg_logical/mappings/test2"),
    7587            2 :             Some(&bytes::Bytes::from_static(b"second"))
    7588            2 :         );
    7589            2 : 
    7590            2 :         let child = tenant
    7591            2 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7592            2 :             .await
    7593            2 :             .unwrap();
    7594            2 : 
    7595            2 :         let files = child.list_aux_files(lsn, &ctx).await.unwrap();
    7596            2 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7597            2 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7598            2 :     }
    7599              : 
    7600              :     #[tokio::test]
    7601            2 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7602            2 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7603            2 :         let (tenant, ctx) = harness.load().await;
    7604            2 :         let tline = tenant
    7605            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7606            2 :             .await?;
    7607            2 : 
    7608            2 :         const NUM_KEYS: usize = 1000;
    7609            2 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7610            2 : 
    7611            2 :         let cancel = CancellationToken::new();
    7612            2 : 
    7613            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7614            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7615            2 :         let mut test_key = base_key;
    7616            2 :         let mut lsn = Lsn(0x10);
    7617            2 : 
    7618            8 :         async fn scan_with_statistics(
    7619            8 :             tline: &Timeline,
    7620            8 :             keyspace: &KeySpace,
    7621            8 :             lsn: Lsn,
    7622            8 :             ctx: &RequestContext,
    7623            8 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7624            8 :             let mut reconstruct_state = ValuesReconstructState::default();
    7625            8 :             let res = tline
    7626            8 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7627            8 :                 .await?;
    7628            8 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7629            8 :         }
    7630            2 : 
    7631            2 :         #[allow(clippy::needless_range_loop)]
    7632         2002 :         for blknum in 0..NUM_KEYS {
    7633         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7634         2000 :             test_key.field6 = (blknum * STEP) as u32;
    7635         2000 :             let mut writer = tline.writer().await;
    7636         2000 :             writer
    7637         2000 :                 .put(
    7638         2000 :                     test_key,
    7639         2000 :                     lsn,
    7640         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7641         2000 :                     &ctx,
    7642         2000 :                 )
    7643         2000 :                 .await?;
    7644         2000 :             writer.finish_write(lsn);
    7645         2000 :             drop(writer);
    7646            2 :         }
    7647            2 : 
    7648            2 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7649            2 : 
    7650           22 :         for iter in 1..=10 {
    7651        20020 :             for _ in 0..NUM_KEYS {
    7652        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7653        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7654        20000 :                 test_key.field6 = (blknum * STEP) as u32;
    7655        20000 :                 let mut writer = tline.writer().await;
    7656        20000 :                 writer
    7657        20000 :                     .put(
    7658        20000 :                         test_key,
    7659        20000 :                         lsn,
    7660        20000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7661        20000 :                         &ctx,
    7662        20000 :                     )
    7663        20000 :                     .await?;
    7664        20000 :                 writer.finish_write(lsn);
    7665        20000 :                 drop(writer);
    7666            2 :             }
    7667            2 : 
    7668           20 :             tline.freeze_and_flush().await?;
    7669            2 : 
    7670           20 :             if iter % 5 == 0 {
    7671            4 :                 let (_, before_delta_file_accessed) =
    7672            4 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7673            4 :                 tline
    7674            4 :                     .compact(
    7675            4 :                         &cancel,
    7676            4 :                         {
    7677            4 :                             let mut flags = EnumSet::new();
    7678            4 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7679            4 :                             flags.insert(CompactFlags::ForceRepartition);
    7680            4 :                             flags
    7681            4 :                         },
    7682            4 :                         &ctx,
    7683            4 :                     )
    7684            4 :                     .await?;
    7685            4 :                 let (_, after_delta_file_accessed) =
    7686            4 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
    7687            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}");
    7688            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.
    7689            4 :                 assert!(
    7690            4 :                     after_delta_file_accessed <= 2,
    7691            2 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7692            2 :                 );
    7693           16 :             }
    7694            2 :         }
    7695            2 : 
    7696            2 :         Ok(())
    7697            2 :     }
    7698              : 
    7699              :     #[tokio::test]
    7700            2 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7701            2 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7702            2 :         let (tenant, ctx) = harness.load().await;
    7703            2 : 
    7704            2 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7705            2 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7706            2 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7707            2 : 
    7708            2 :         let tline = tenant
    7709            2 :             .create_test_timeline_with_layers(
    7710            2 :                 TIMELINE_ID,
    7711            2 :                 Lsn(0x10),
    7712            2 :                 DEFAULT_PG_VERSION,
    7713            2 :                 &ctx,
    7714            2 :                 Vec::new(), // delta layers
    7715            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7716            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
    7717            2 :             )
    7718            2 :             .await?;
    7719            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7720            2 : 
    7721            2 :         let child = tenant
    7722            2 :             .branch_timeline_test_with_layers(
    7723            2 :                 &tline,
    7724            2 :                 NEW_TIMELINE_ID,
    7725            2 :                 Some(Lsn(0x20)),
    7726            2 :                 &ctx,
    7727            2 :                 Vec::new(), // delta layers
    7728            2 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7729            2 :                 Lsn(0x30),
    7730            2 :             )
    7731            2 :             .await
    7732            2 :             .unwrap();
    7733            2 : 
    7734            2 :         let lsn = Lsn(0x30);
    7735            2 : 
    7736            2 :         // test vectored get on parent timeline
    7737            2 :         assert_eq!(
    7738            2 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7739            2 :             Some(test_img("data key 1"))
    7740            2 :         );
    7741            2 :         assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7742            2 :             .await
    7743            2 :             .unwrap_err()
    7744            2 :             .is_missing_key_error());
    7745            2 :         assert!(
    7746            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7747            2 :                 .await
    7748            2 :                 .unwrap_err()
    7749            2 :                 .is_missing_key_error()
    7750            2 :         );
    7751            2 : 
    7752            2 :         // test vectored get on child timeline
    7753            2 :         assert_eq!(
    7754            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7755            2 :             Some(test_img("data key 1"))
    7756            2 :         );
    7757            2 :         assert_eq!(
    7758            2 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7759            2 :             Some(test_img("data key 2"))
    7760            2 :         );
    7761            2 :         assert!(
    7762            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7763            2 :                 .await
    7764            2 :                 .unwrap_err()
    7765            2 :                 .is_missing_key_error()
    7766            2 :         );
    7767            2 : 
    7768            2 :         Ok(())
    7769            2 :     }
    7770              : 
    7771              :     #[tokio::test]
    7772            2 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7773            2 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7774            2 :         let (tenant, ctx) = harness.load().await;
    7775            2 : 
    7776            2 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7777            2 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7778            2 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7779            2 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7780            2 : 
    7781            2 :         let tline = tenant
    7782            2 :             .create_test_timeline_with_layers(
    7783            2 :                 TIMELINE_ID,
    7784            2 :                 Lsn(0x10),
    7785            2 :                 DEFAULT_PG_VERSION,
    7786            2 :                 &ctx,
    7787            2 :                 Vec::new(), // delta layers
    7788            2 :                 vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
    7789            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
    7790            2 :             )
    7791            2 :             .await?;
    7792            2 : 
    7793            2 :         let child = tenant
    7794            2 :             .branch_timeline_test_with_layers(
    7795            2 :                 &tline,
    7796            2 :                 NEW_TIMELINE_ID,
    7797            2 :                 Some(Lsn(0x20)),
    7798            2 :                 &ctx,
    7799            2 :                 Vec::new(), // delta layers
    7800            2 :                 vec![(
    7801            2 :                     Lsn(0x30),
    7802            2 :                     vec![(base_key_child, test_img("metadata key 2"))],
    7803            2 :                 )], // image layers
    7804            2 :                 Lsn(0x30),
    7805            2 :             )
    7806            2 :             .await
    7807            2 :             .unwrap();
    7808            2 : 
    7809            2 :         let lsn = Lsn(0x30);
    7810            2 : 
    7811            2 :         // test vectored get on parent timeline
    7812            2 :         assert_eq!(
    7813            2 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7814            2 :             Some(test_img("metadata key 1"))
    7815            2 :         );
    7816            2 :         assert_eq!(
    7817            2 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    7818            2 :             None
    7819            2 :         );
    7820            2 :         assert_eq!(
    7821            2 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    7822            2 :             None
    7823            2 :         );
    7824            2 : 
    7825            2 :         // test vectored get on child timeline
    7826            2 :         assert_eq!(
    7827            2 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7828            2 :             None
    7829            2 :         );
    7830            2 :         assert_eq!(
    7831            2 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7832            2 :             Some(test_img("metadata key 2"))
    7833            2 :         );
    7834            2 :         assert_eq!(
    7835            2 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    7836            2 :             None
    7837            2 :         );
    7838            2 : 
    7839            2 :         Ok(())
    7840            2 :     }
    7841              : 
    7842           36 :     async fn get_vectored_impl_wrapper(
    7843           36 :         tline: &Arc<Timeline>,
    7844           36 :         key: Key,
    7845           36 :         lsn: Lsn,
    7846           36 :         ctx: &RequestContext,
    7847           36 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    7848           36 :         let mut reconstruct_state = ValuesReconstructState::new();
    7849           36 :         let mut res = tline
    7850           36 :             .get_vectored_impl(
    7851           36 :                 KeySpace::single(key..key.next()),
    7852           36 :                 lsn,
    7853           36 :                 &mut reconstruct_state,
    7854           36 :                 ctx,
    7855           36 :             )
    7856           36 :             .await?;
    7857           30 :         Ok(res.pop_last().map(|(k, v)| {
    7858           18 :             assert_eq!(k, key);
    7859           18 :             v.unwrap()
    7860           30 :         }))
    7861           36 :     }
    7862              : 
    7863              :     #[tokio::test]
    7864            2 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    7865            2 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    7866            2 :         let (tenant, ctx) = harness.load().await;
    7867            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7868            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7869            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7870            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7871            2 : 
    7872            2 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    7873            2 :         // Lsn 0x30 key0, key3, no key1+key2
    7874            2 :         // Lsn 0x20 key1+key2 tomestones
    7875            2 :         // Lsn 0x10 key1 in image, key2 in delta
    7876            2 :         let tline = tenant
    7877            2 :             .create_test_timeline_with_layers(
    7878            2 :                 TIMELINE_ID,
    7879            2 :                 Lsn(0x10),
    7880            2 :                 DEFAULT_PG_VERSION,
    7881            2 :                 &ctx,
    7882            2 :                 // delta layers
    7883            2 :                 vec![
    7884            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7885            2 :                         Lsn(0x10)..Lsn(0x20),
    7886            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7887            2 :                     ),
    7888            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7889            2 :                         Lsn(0x20)..Lsn(0x30),
    7890            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7891            2 :                     ),
    7892            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7893            2 :                         Lsn(0x20)..Lsn(0x30),
    7894            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7895            2 :                     ),
    7896            2 :                 ],
    7897            2 :                 // image layers
    7898            2 :                 vec![
    7899            2 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    7900            2 :                     (
    7901            2 :                         Lsn(0x30),
    7902            2 :                         vec![
    7903            2 :                             (key0, test_img("metadata key 0")),
    7904            2 :                             (key3, test_img("metadata key 3")),
    7905            2 :                         ],
    7906            2 :                     ),
    7907            2 :                 ],
    7908            2 :                 Lsn(0x30),
    7909            2 :             )
    7910            2 :             .await?;
    7911            2 : 
    7912            2 :         let lsn = Lsn(0x30);
    7913            2 :         let old_lsn = Lsn(0x20);
    7914            2 : 
    7915            2 :         assert_eq!(
    7916            2 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    7917            2 :             Some(test_img("metadata key 0"))
    7918            2 :         );
    7919            2 :         assert_eq!(
    7920            2 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    7921            2 :             None,
    7922            2 :         );
    7923            2 :         assert_eq!(
    7924            2 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    7925            2 :             None,
    7926            2 :         );
    7927            2 :         assert_eq!(
    7928            2 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    7929            2 :             Some(Bytes::new()),
    7930            2 :         );
    7931            2 :         assert_eq!(
    7932            2 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    7933            2 :             Some(Bytes::new()),
    7934            2 :         );
    7935            2 :         assert_eq!(
    7936            2 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    7937            2 :             Some(test_img("metadata key 3"))
    7938            2 :         );
    7939            2 : 
    7940            2 :         Ok(())
    7941            2 :     }
    7942              : 
    7943              :     #[tokio::test]
    7944            2 :     async fn test_metadata_tombstone_image_creation() {
    7945            2 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    7946            2 :             .await
    7947            2 :             .unwrap();
    7948            2 :         let (tenant, ctx) = harness.load().await;
    7949            2 : 
    7950            2 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7951            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7952            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7953            2 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7954            2 : 
    7955            2 :         let tline = tenant
    7956            2 :             .create_test_timeline_with_layers(
    7957            2 :                 TIMELINE_ID,
    7958            2 :                 Lsn(0x10),
    7959            2 :                 DEFAULT_PG_VERSION,
    7960            2 :                 &ctx,
    7961            2 :                 // delta layers
    7962            2 :                 vec![
    7963            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7964            2 :                         Lsn(0x10)..Lsn(0x20),
    7965            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    7966            2 :                     ),
    7967            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7968            2 :                         Lsn(0x20)..Lsn(0x30),
    7969            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    7970            2 :                     ),
    7971            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7972            2 :                         Lsn(0x20)..Lsn(0x30),
    7973            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    7974            2 :                     ),
    7975            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    7976            2 :                         Lsn(0x30)..Lsn(0x40),
    7977            2 :                         vec![
    7978            2 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    7979            2 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    7980            2 :                         ],
    7981            2 :                     ),
    7982            2 :                 ],
    7983            2 :                 // image layers
    7984            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    7985            2 :                 Lsn(0x40),
    7986            2 :             )
    7987            2 :             .await
    7988            2 :             .unwrap();
    7989            2 : 
    7990            2 :         let cancel = CancellationToken::new();
    7991            2 : 
    7992            2 :         tline
    7993            2 :             .compact(
    7994            2 :                 &cancel,
    7995            2 :                 {
    7996            2 :                     let mut flags = EnumSet::new();
    7997            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    7998            2 :                     flags.insert(CompactFlags::ForceRepartition);
    7999            2 :                     flags
    8000            2 :                 },
    8001            2 :                 &ctx,
    8002            2 :             )
    8003            2 :             .await
    8004            2 :             .unwrap();
    8005            2 : 
    8006            2 :         // Image layers are created at last_record_lsn
    8007            2 :         let images = tline
    8008            2 :             .inspect_image_layers(Lsn(0x40), &ctx)
    8009            2 :             .await
    8010            2 :             .unwrap()
    8011            2 :             .into_iter()
    8012           18 :             .filter(|(k, _)| k.is_metadata_key())
    8013            2 :             .collect::<Vec<_>>();
    8014            2 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8015            2 :     }
    8016              : 
    8017              :     #[tokio::test]
    8018            2 :     async fn test_metadata_tombstone_empty_image_creation() {
    8019            2 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8020            2 :             .await
    8021            2 :             .unwrap();
    8022            2 :         let (tenant, ctx) = harness.load().await;
    8023            2 : 
    8024            2 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8025            2 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8026            2 : 
    8027            2 :         let tline = tenant
    8028            2 :             .create_test_timeline_with_layers(
    8029            2 :                 TIMELINE_ID,
    8030            2 :                 Lsn(0x10),
    8031            2 :                 DEFAULT_PG_VERSION,
    8032            2 :                 &ctx,
    8033            2 :                 // delta layers
    8034            2 :                 vec![
    8035            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8036            2 :                         Lsn(0x10)..Lsn(0x20),
    8037            2 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8038            2 :                     ),
    8039            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8040            2 :                         Lsn(0x20)..Lsn(0x30),
    8041            2 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8042            2 :                     ),
    8043            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8044            2 :                         Lsn(0x20)..Lsn(0x30),
    8045            2 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8046            2 :                     ),
    8047            2 :                 ],
    8048            2 :                 // image layers
    8049            2 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8050            2 :                 Lsn(0x30),
    8051            2 :             )
    8052            2 :             .await
    8053            2 :             .unwrap();
    8054            2 : 
    8055            2 :         let cancel = CancellationToken::new();
    8056            2 : 
    8057            2 :         tline
    8058            2 :             .compact(
    8059            2 :                 &cancel,
    8060            2 :                 {
    8061            2 :                     let mut flags = EnumSet::new();
    8062            2 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8063            2 :                     flags.insert(CompactFlags::ForceRepartition);
    8064            2 :                     flags
    8065            2 :                 },
    8066            2 :                 &ctx,
    8067            2 :             )
    8068            2 :             .await
    8069            2 :             .unwrap();
    8070            2 : 
    8071            2 :         // Image layers are created at last_record_lsn
    8072            2 :         let images = tline
    8073            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8074            2 :             .await
    8075            2 :             .unwrap()
    8076            2 :             .into_iter()
    8077           14 :             .filter(|(k, _)| k.is_metadata_key())
    8078            2 :             .collect::<Vec<_>>();
    8079            2 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8080            2 :     }
    8081              : 
    8082              :     #[tokio::test]
    8083            2 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8084            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8085            2 :         let (tenant, ctx) = harness.load().await;
    8086            2 : 
    8087          102 :         fn get_key(id: u32) -> Key {
    8088          102 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8089          102 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8090          102 :             key.field6 = id;
    8091          102 :             key
    8092          102 :         }
    8093            2 : 
    8094            2 :         // We create
    8095            2 :         // - one bottom-most image layer,
    8096            2 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8097            2 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8098            2 :         // - a delta layer D3 above the horizon.
    8099            2 :         //
    8100            2 :         //                             | D3 |
    8101            2 :         //  | D1 |
    8102            2 :         // -|    |-- gc horizon -----------------
    8103            2 :         //  |    |                | D2 |
    8104            2 :         // --------- img layer ------------------
    8105            2 :         //
    8106            2 :         // What we should expact from this compaction is:
    8107            2 :         //                             | D3 |
    8108            2 :         //  | Part of D1 |
    8109            2 :         // --------- img layer with D1+D2 at GC horizon------------------
    8110            2 : 
    8111            2 :         // img layer at 0x10
    8112            2 :         let img_layer = (0..10)
    8113           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8114            2 :             .collect_vec();
    8115            2 : 
    8116            2 :         let delta1 = vec![
    8117            2 :             (
    8118            2 :                 get_key(1),
    8119            2 :                 Lsn(0x20),
    8120            2 :                 Value::Image(Bytes::from("value 1@0x20")),
    8121            2 :             ),
    8122            2 :             (
    8123            2 :                 get_key(2),
    8124            2 :                 Lsn(0x30),
    8125            2 :                 Value::Image(Bytes::from("value 2@0x30")),
    8126            2 :             ),
    8127            2 :             (
    8128            2 :                 get_key(3),
    8129            2 :                 Lsn(0x40),
    8130            2 :                 Value::Image(Bytes::from("value 3@0x40")),
    8131            2 :             ),
    8132            2 :         ];
    8133            2 :         let delta2 = vec![
    8134            2 :             (
    8135            2 :                 get_key(5),
    8136            2 :                 Lsn(0x20),
    8137            2 :                 Value::Image(Bytes::from("value 5@0x20")),
    8138            2 :             ),
    8139            2 :             (
    8140            2 :                 get_key(6),
    8141            2 :                 Lsn(0x20),
    8142            2 :                 Value::Image(Bytes::from("value 6@0x20")),
    8143            2 :             ),
    8144            2 :         ];
    8145            2 :         let delta3 = vec![
    8146            2 :             (
    8147            2 :                 get_key(8),
    8148            2 :                 Lsn(0x48),
    8149            2 :                 Value::Image(Bytes::from("value 8@0x48")),
    8150            2 :             ),
    8151            2 :             (
    8152            2 :                 get_key(9),
    8153            2 :                 Lsn(0x48),
    8154            2 :                 Value::Image(Bytes::from("value 9@0x48")),
    8155            2 :             ),
    8156            2 :         ];
    8157            2 : 
    8158            2 :         let tline = tenant
    8159            2 :             .create_test_timeline_with_layers(
    8160            2 :                 TIMELINE_ID,
    8161            2 :                 Lsn(0x10),
    8162            2 :                 DEFAULT_PG_VERSION,
    8163            2 :                 &ctx,
    8164            2 :                 vec![
    8165            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8166            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8167            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8168            2 :                 ], // delta layers
    8169            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8170            2 :                 Lsn(0x50),
    8171            2 :             )
    8172            2 :             .await?;
    8173            2 :         {
    8174            2 :             tline
    8175            2 :                 .latest_gc_cutoff_lsn
    8176            2 :                 .lock_for_write()
    8177            2 :                 .store_and_unlock(Lsn(0x30))
    8178            2 :                 .wait()
    8179            2 :                 .await;
    8180            2 :             // Update GC info
    8181            2 :             let mut guard = tline.gc_info.write().unwrap();
    8182            2 :             guard.cutoffs.time = Lsn(0x30);
    8183            2 :             guard.cutoffs.space = Lsn(0x30);
    8184            2 :         }
    8185            2 : 
    8186            2 :         let expected_result = [
    8187            2 :             Bytes::from_static(b"value 0@0x10"),
    8188            2 :             Bytes::from_static(b"value 1@0x20"),
    8189            2 :             Bytes::from_static(b"value 2@0x30"),
    8190            2 :             Bytes::from_static(b"value 3@0x40"),
    8191            2 :             Bytes::from_static(b"value 4@0x10"),
    8192            2 :             Bytes::from_static(b"value 5@0x20"),
    8193            2 :             Bytes::from_static(b"value 6@0x20"),
    8194            2 :             Bytes::from_static(b"value 7@0x10"),
    8195            2 :             Bytes::from_static(b"value 8@0x48"),
    8196            2 :             Bytes::from_static(b"value 9@0x48"),
    8197            2 :         ];
    8198            2 : 
    8199           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8200           20 :             assert_eq!(
    8201           20 :                 tline
    8202           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8203           20 :                     .await
    8204           20 :                     .unwrap(),
    8205            2 :                 expected
    8206            2 :             );
    8207            2 :         }
    8208            2 : 
    8209            2 :         let cancel = CancellationToken::new();
    8210            2 :         tline
    8211            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8212            2 :             .await
    8213            2 :             .unwrap();
    8214            2 : 
    8215           20 :         for (idx, expected) in expected_result.iter().enumerate() {
    8216           20 :             assert_eq!(
    8217           20 :                 tline
    8218           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8219           20 :                     .await
    8220           20 :                     .unwrap(),
    8221            2 :                 expected
    8222            2 :             );
    8223            2 :         }
    8224            2 : 
    8225            2 :         // Check if the image layer at the GC horizon contains exactly what we want
    8226            2 :         let image_at_gc_horizon = tline
    8227            2 :             .inspect_image_layers(Lsn(0x30), &ctx)
    8228            2 :             .await
    8229            2 :             .unwrap()
    8230            2 :             .into_iter()
    8231           34 :             .filter(|(k, _)| k.is_metadata_key())
    8232            2 :             .collect::<Vec<_>>();
    8233            2 : 
    8234            2 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8235            2 :         let expected_result = [
    8236            2 :             Bytes::from_static(b"value 0@0x10"),
    8237            2 :             Bytes::from_static(b"value 1@0x20"),
    8238            2 :             Bytes::from_static(b"value 2@0x30"),
    8239            2 :             Bytes::from_static(b"value 3@0x10"),
    8240            2 :             Bytes::from_static(b"value 4@0x10"),
    8241            2 :             Bytes::from_static(b"value 5@0x20"),
    8242            2 :             Bytes::from_static(b"value 6@0x20"),
    8243            2 :             Bytes::from_static(b"value 7@0x10"),
    8244            2 :             Bytes::from_static(b"value 8@0x10"),
    8245            2 :             Bytes::from_static(b"value 9@0x10"),
    8246            2 :         ];
    8247           22 :         for idx in 0..10 {
    8248           20 :             assert_eq!(
    8249           20 :                 image_at_gc_horizon[idx],
    8250           20 :                 (get_key(idx as u32), expected_result[idx].clone())
    8251           20 :             );
    8252            2 :         }
    8253            2 : 
    8254            2 :         // Check if old layers are removed / new layers have the expected LSN
    8255            2 :         let all_layers = inspect_and_sort(&tline, None).await;
    8256            2 :         assert_eq!(
    8257            2 :             all_layers,
    8258            2 :             vec![
    8259            2 :                 // Image layer at GC horizon
    8260            2 :                 PersistentLayerKey {
    8261            2 :                     key_range: Key::MIN..Key::MAX,
    8262            2 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8263            2 :                     is_delta: false
    8264            2 :                 },
    8265            2 :                 // The delta layer below the horizon
    8266            2 :                 PersistentLayerKey {
    8267            2 :                     key_range: get_key(3)..get_key(4),
    8268            2 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8269            2 :                     is_delta: true
    8270            2 :                 },
    8271            2 :                 // The delta3 layer that should not be picked for the compaction
    8272            2 :                 PersistentLayerKey {
    8273            2 :                     key_range: get_key(8)..get_key(10),
    8274            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8275            2 :                     is_delta: true
    8276            2 :                 }
    8277            2 :             ]
    8278            2 :         );
    8279            2 : 
    8280            2 :         // increase GC horizon and compact again
    8281            2 :         {
    8282            2 :             tline
    8283            2 :                 .latest_gc_cutoff_lsn
    8284            2 :                 .lock_for_write()
    8285            2 :                 .store_and_unlock(Lsn(0x40))
    8286            2 :                 .wait()
    8287            2 :                 .await;
    8288            2 :             // Update GC info
    8289            2 :             let mut guard = tline.gc_info.write().unwrap();
    8290            2 :             guard.cutoffs.time = Lsn(0x40);
    8291            2 :             guard.cutoffs.space = Lsn(0x40);
    8292            2 :         }
    8293            2 :         tline
    8294            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8295            2 :             .await
    8296            2 :             .unwrap();
    8297            2 : 
    8298            2 :         Ok(())
    8299            2 :     }
    8300              : 
    8301              :     #[cfg(feature = "testing")]
    8302              :     #[tokio::test]
    8303            2 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8304            2 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8305            2 :         let (tenant, ctx) = harness.load().await;
    8306            2 : 
    8307           24 :         fn get_key(id: u32) -> Key {
    8308           24 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8309           24 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8310           24 :             key.field6 = id;
    8311           24 :             key
    8312           24 :         }
    8313            2 : 
    8314            2 :         let delta1 = vec![
    8315            2 :             (
    8316            2 :                 get_key(1),
    8317            2 :                 Lsn(0x20),
    8318            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8319            2 :             ),
    8320            2 :             (
    8321            2 :                 get_key(1),
    8322            2 :                 Lsn(0x30),
    8323            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8324            2 :             ),
    8325            2 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8326            2 :             (
    8327            2 :                 get_key(2),
    8328            2 :                 Lsn(0x20),
    8329            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8330            2 :             ),
    8331            2 :             (
    8332            2 :                 get_key(2),
    8333            2 :                 Lsn(0x30),
    8334            2 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8335            2 :             ),
    8336            2 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8337            2 :             (
    8338            2 :                 get_key(3),
    8339            2 :                 Lsn(0x20),
    8340            2 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8341            2 :             ),
    8342            2 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8343            2 :             (
    8344            2 :                 get_key(4),
    8345            2 :                 Lsn(0x20),
    8346            2 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8347            2 :             ),
    8348            2 :         ];
    8349            2 :         let image1 = vec![(get_key(1), "0x10".into())];
    8350            2 : 
    8351            2 :         let tline = tenant
    8352            2 :             .create_test_timeline_with_layers(
    8353            2 :                 TIMELINE_ID,
    8354            2 :                 Lsn(0x10),
    8355            2 :                 DEFAULT_PG_VERSION,
    8356            2 :                 &ctx,
    8357            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8358            2 :                     Lsn(0x10)..Lsn(0x40),
    8359            2 :                     delta1,
    8360            2 :                 )], // delta layers
    8361            2 :                 vec![(Lsn(0x10), image1)], // image layers
    8362            2 :                 Lsn(0x50),
    8363            2 :             )
    8364            2 :             .await?;
    8365            2 : 
    8366            2 :         assert_eq!(
    8367            2 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8368            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8369            2 :         );
    8370            2 :         assert_eq!(
    8371            2 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8372            2 :             Bytes::from_static(b"0x10,0x20,0x30")
    8373            2 :         );
    8374            2 : 
    8375            2 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8376            2 : 
    8377            2 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8378            2 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8379            2 : 
    8380            2 :         Ok(())
    8381            2 :     }
    8382              : 
    8383              :     #[tokio::test(start_paused = true)]
    8384            2 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8385            2 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8386            2 :             .await
    8387            2 :             .unwrap()
    8388            2 :             .load()
    8389            2 :             .await;
    8390            2 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8391            2 :         // initial transition into AttachedSingle.
    8392            2 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8393            2 :         tokio::time::resume();
    8394            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8395            2 : 
    8396            2 :         let end_lsn = Lsn(0x100);
    8397            2 :         let image_layers = (0x20..=0x90)
    8398            2 :             .step_by(0x10)
    8399           16 :             .map(|n| {
    8400           16 :                 (
    8401           16 :                     Lsn(n),
    8402           16 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8403           16 :                 )
    8404           16 :             })
    8405            2 :             .collect();
    8406            2 : 
    8407            2 :         let timeline = tenant
    8408            2 :             .create_test_timeline_with_layers(
    8409            2 :                 TIMELINE_ID,
    8410            2 :                 Lsn(0x10),
    8411            2 :                 DEFAULT_PG_VERSION,
    8412            2 :                 &ctx,
    8413            2 :                 Vec::new(),
    8414            2 :                 image_layers,
    8415            2 :                 end_lsn,
    8416            2 :             )
    8417            2 :             .await?;
    8418            2 : 
    8419            2 :         let leased_lsns = [0x30, 0x50, 0x70];
    8420            2 :         let mut leases = Vec::new();
    8421            6 :         leased_lsns.iter().for_each(|n| {
    8422            6 :             leases.push(
    8423            6 :                 timeline
    8424            6 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8425            6 :                     .expect("lease request should succeed"),
    8426            6 :             );
    8427            6 :         });
    8428            2 : 
    8429            2 :         let updated_lease_0 = timeline
    8430            2 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8431            2 :             .expect("lease renewal should succeed");
    8432            2 :         assert_eq!(
    8433            2 :             updated_lease_0.valid_until, leases[0].valid_until,
    8434            2 :             " Renewing with shorter lease should not change the lease."
    8435            2 :         );
    8436            2 : 
    8437            2 :         let updated_lease_1 = timeline
    8438            2 :             .renew_lsn_lease(
    8439            2 :                 Lsn(leased_lsns[1]),
    8440            2 :                 timeline.get_lsn_lease_length() * 2,
    8441            2 :                 &ctx,
    8442            2 :             )
    8443            2 :             .expect("lease renewal should succeed");
    8444            2 :         assert!(
    8445            2 :             updated_lease_1.valid_until > leases[1].valid_until,
    8446            2 :             "Renewing with a long lease should renew lease with later expiration time."
    8447            2 :         );
    8448            2 : 
    8449            2 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8450            2 :         info!(
    8451            2 :             "latest_gc_cutoff_lsn: {}",
    8452            0 :             *timeline.get_latest_gc_cutoff_lsn()
    8453            2 :         );
    8454            2 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8455            2 : 
    8456            2 :         let res = tenant
    8457            2 :             .gc_iteration(
    8458            2 :                 Some(TIMELINE_ID),
    8459            2 :                 0,
    8460            2 :                 Duration::ZERO,
    8461            2 :                 &CancellationToken::new(),
    8462            2 :                 &ctx,
    8463            2 :             )
    8464            2 :             .await
    8465            2 :             .unwrap();
    8466            2 : 
    8467            2 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8468            2 :         // 0/10: initdb layer
    8469            2 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8470            2 :         assert_eq!(res.layers_needed_by_leases, 7);
    8471            2 :         // Keeping 0/90 b/c it is the latest layer.
    8472            2 :         assert_eq!(res.layers_not_updated, 1);
    8473            2 :         // Removed 0/80.
    8474            2 :         assert_eq!(res.layers_removed, 1);
    8475            2 : 
    8476            2 :         // Make lease on a already GC-ed LSN.
    8477            2 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8478            2 :         assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
    8479            2 :         timeline
    8480            2 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8481            2 :             .expect_err("lease request on GC-ed LSN should fail");
    8482            2 : 
    8483            2 :         // Should still be able to renew a currently valid lease
    8484            2 :         // Assumption: original lease to is still valid for 0/50.
    8485            2 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8486            2 :         timeline
    8487            2 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8488            2 :             .expect("lease renewal with validation should succeed");
    8489            2 : 
    8490            2 :         Ok(())
    8491            2 :     }
    8492              : 
    8493              :     #[cfg(feature = "testing")]
    8494              :     #[tokio::test]
    8495            2 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8496            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8497            2 :             "test_simple_bottom_most_compaction_deltas_1",
    8498            2 :             false,
    8499            2 :         )
    8500            2 :         .await
    8501            2 :     }
    8502              : 
    8503              :     #[cfg(feature = "testing")]
    8504              :     #[tokio::test]
    8505            2 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8506            2 :         test_simple_bottom_most_compaction_deltas_helper(
    8507            2 :             "test_simple_bottom_most_compaction_deltas_2",
    8508            2 :             true,
    8509            2 :         )
    8510            2 :         .await
    8511            2 :     }
    8512              : 
    8513              :     #[cfg(feature = "testing")]
    8514            4 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8515            4 :         test_name: &'static str,
    8516            4 :         use_delta_bottom_layer: bool,
    8517            4 :     ) -> anyhow::Result<()> {
    8518            4 :         let harness = TenantHarness::create(test_name).await?;
    8519            4 :         let (tenant, ctx) = harness.load().await;
    8520              : 
    8521          276 :         fn get_key(id: u32) -> Key {
    8522          276 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8523          276 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8524          276 :             key.field6 = id;
    8525          276 :             key
    8526          276 :         }
    8527              : 
    8528              :         // We create
    8529              :         // - one bottom-most image layer,
    8530              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8531              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8532              :         // - a delta layer D3 above the horizon.
    8533              :         //
    8534              :         //                             | D3 |
    8535              :         //  | D1 |
    8536              :         // -|    |-- gc horizon -----------------
    8537              :         //  |    |                | D2 |
    8538              :         // --------- img layer ------------------
    8539              :         //
    8540              :         // What we should expact from this compaction is:
    8541              :         //                             | D3 |
    8542              :         //  | Part of D1 |
    8543              :         // --------- img layer with D1+D2 at GC horizon------------------
    8544              : 
    8545              :         // img layer at 0x10
    8546            4 :         let img_layer = (0..10)
    8547           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8548            4 :             .collect_vec();
    8549            4 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8550            4 :         let delta4 = (0..10)
    8551           40 :             .map(|id| {
    8552           40 :                 (
    8553           40 :                     get_key(id),
    8554           40 :                     Lsn(0x08),
    8555           40 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8556           40 :                 )
    8557           40 :             })
    8558            4 :             .collect_vec();
    8559            4 : 
    8560            4 :         let delta1 = vec![
    8561            4 :             (
    8562            4 :                 get_key(1),
    8563            4 :                 Lsn(0x20),
    8564            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8565            4 :             ),
    8566            4 :             (
    8567            4 :                 get_key(2),
    8568            4 :                 Lsn(0x30),
    8569            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8570            4 :             ),
    8571            4 :             (
    8572            4 :                 get_key(3),
    8573            4 :                 Lsn(0x28),
    8574            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8575            4 :             ),
    8576            4 :             (
    8577            4 :                 get_key(3),
    8578            4 :                 Lsn(0x30),
    8579            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8580            4 :             ),
    8581            4 :             (
    8582            4 :                 get_key(3),
    8583            4 :                 Lsn(0x40),
    8584            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8585            4 :             ),
    8586            4 :         ];
    8587            4 :         let delta2 = vec![
    8588            4 :             (
    8589            4 :                 get_key(5),
    8590            4 :                 Lsn(0x20),
    8591            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8592            4 :             ),
    8593            4 :             (
    8594            4 :                 get_key(6),
    8595            4 :                 Lsn(0x20),
    8596            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8597            4 :             ),
    8598            4 :         ];
    8599            4 :         let delta3 = vec![
    8600            4 :             (
    8601            4 :                 get_key(8),
    8602            4 :                 Lsn(0x48),
    8603            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8604            4 :             ),
    8605            4 :             (
    8606            4 :                 get_key(9),
    8607            4 :                 Lsn(0x48),
    8608            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8609            4 :             ),
    8610            4 :         ];
    8611              : 
    8612            4 :         let tline = if use_delta_bottom_layer {
    8613            2 :             tenant
    8614            2 :                 .create_test_timeline_with_layers(
    8615            2 :                     TIMELINE_ID,
    8616            2 :                     Lsn(0x08),
    8617            2 :                     DEFAULT_PG_VERSION,
    8618            2 :                     &ctx,
    8619            2 :                     vec![
    8620            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8621            2 :                             Lsn(0x08)..Lsn(0x10),
    8622            2 :                             delta4,
    8623            2 :                         ),
    8624            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8625            2 :                             Lsn(0x20)..Lsn(0x48),
    8626            2 :                             delta1,
    8627            2 :                         ),
    8628            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8629            2 :                             Lsn(0x20)..Lsn(0x48),
    8630            2 :                             delta2,
    8631            2 :                         ),
    8632            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8633            2 :                             Lsn(0x48)..Lsn(0x50),
    8634            2 :                             delta3,
    8635            2 :                         ),
    8636            2 :                     ], // delta layers
    8637            2 :                     vec![], // image layers
    8638            2 :                     Lsn(0x50),
    8639            2 :                 )
    8640            2 :                 .await?
    8641              :         } else {
    8642            2 :             tenant
    8643            2 :                 .create_test_timeline_with_layers(
    8644            2 :                     TIMELINE_ID,
    8645            2 :                     Lsn(0x10),
    8646            2 :                     DEFAULT_PG_VERSION,
    8647            2 :                     &ctx,
    8648            2 :                     vec![
    8649            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8650            2 :                             Lsn(0x10)..Lsn(0x48),
    8651            2 :                             delta1,
    8652            2 :                         ),
    8653            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8654            2 :                             Lsn(0x10)..Lsn(0x48),
    8655            2 :                             delta2,
    8656            2 :                         ),
    8657            2 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8658            2 :                             Lsn(0x48)..Lsn(0x50),
    8659            2 :                             delta3,
    8660            2 :                         ),
    8661            2 :                     ], // delta layers
    8662            2 :                     vec![(Lsn(0x10), img_layer)], // image layers
    8663            2 :                     Lsn(0x50),
    8664            2 :                 )
    8665            2 :                 .await?
    8666              :         };
    8667              :         {
    8668            4 :             tline
    8669            4 :                 .latest_gc_cutoff_lsn
    8670            4 :                 .lock_for_write()
    8671            4 :                 .store_and_unlock(Lsn(0x30))
    8672            4 :                 .wait()
    8673            4 :                 .await;
    8674              :             // Update GC info
    8675            4 :             let mut guard = tline.gc_info.write().unwrap();
    8676            4 :             *guard = GcInfo {
    8677            4 :                 retain_lsns: vec![],
    8678            4 :                 cutoffs: GcCutoffs {
    8679            4 :                     time: Lsn(0x30),
    8680            4 :                     space: Lsn(0x30),
    8681            4 :                 },
    8682            4 :                 leases: Default::default(),
    8683            4 :                 within_ancestor_pitr: false,
    8684            4 :             };
    8685            4 :         }
    8686            4 : 
    8687            4 :         let expected_result = [
    8688            4 :             Bytes::from_static(b"value 0@0x10"),
    8689            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8690            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8691            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    8692            4 :             Bytes::from_static(b"value 4@0x10"),
    8693            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8694            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8695            4 :             Bytes::from_static(b"value 7@0x10"),
    8696            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    8697            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    8698            4 :         ];
    8699            4 : 
    8700            4 :         let expected_result_at_gc_horizon = [
    8701            4 :             Bytes::from_static(b"value 0@0x10"),
    8702            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    8703            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    8704            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    8705            4 :             Bytes::from_static(b"value 4@0x10"),
    8706            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    8707            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    8708            4 :             Bytes::from_static(b"value 7@0x10"),
    8709            4 :             Bytes::from_static(b"value 8@0x10"),
    8710            4 :             Bytes::from_static(b"value 9@0x10"),
    8711            4 :         ];
    8712              : 
    8713           44 :         for idx in 0..10 {
    8714           40 :             assert_eq!(
    8715           40 :                 tline
    8716           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8717           40 :                     .await
    8718           40 :                     .unwrap(),
    8719           40 :                 &expected_result[idx]
    8720              :             );
    8721           40 :             assert_eq!(
    8722           40 :                 tline
    8723           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8724           40 :                     .await
    8725           40 :                     .unwrap(),
    8726           40 :                 &expected_result_at_gc_horizon[idx]
    8727              :             );
    8728              :         }
    8729              : 
    8730            4 :         let cancel = CancellationToken::new();
    8731            4 :         tline
    8732            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8733            4 :             .await
    8734            4 :             .unwrap();
    8735              : 
    8736           44 :         for idx in 0..10 {
    8737           40 :             assert_eq!(
    8738           40 :                 tline
    8739           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8740           40 :                     .await
    8741           40 :                     .unwrap(),
    8742           40 :                 &expected_result[idx]
    8743              :             );
    8744           40 :             assert_eq!(
    8745           40 :                 tline
    8746           40 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    8747           40 :                     .await
    8748           40 :                     .unwrap(),
    8749           40 :                 &expected_result_at_gc_horizon[idx]
    8750              :             );
    8751              :         }
    8752              : 
    8753              :         // increase GC horizon and compact again
    8754              :         {
    8755            4 :             tline
    8756            4 :                 .latest_gc_cutoff_lsn
    8757            4 :                 .lock_for_write()
    8758            4 :                 .store_and_unlock(Lsn(0x40))
    8759            4 :                 .wait()
    8760            4 :                 .await;
    8761              :             // Update GC info
    8762            4 :             let mut guard = tline.gc_info.write().unwrap();
    8763            4 :             guard.cutoffs.time = Lsn(0x40);
    8764            4 :             guard.cutoffs.space = Lsn(0x40);
    8765            4 :         }
    8766            4 :         tline
    8767            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8768            4 :             .await
    8769            4 :             .unwrap();
    8770            4 : 
    8771            4 :         Ok(())
    8772            4 :     }
    8773              : 
    8774              :     #[cfg(feature = "testing")]
    8775              :     #[tokio::test]
    8776            2 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    8777            2 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    8778            2 :         let (tenant, ctx) = harness.load().await;
    8779            2 :         let tline = tenant
    8780            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8781            2 :             .await?;
    8782            2 :         tline.force_advance_lsn(Lsn(0x70));
    8783            2 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8784            2 :         let history = vec![
    8785            2 :             (
    8786            2 :                 key,
    8787            2 :                 Lsn(0x10),
    8788            2 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    8789            2 :             ),
    8790            2 :             (
    8791            2 :                 key,
    8792            2 :                 Lsn(0x20),
    8793            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8794            2 :             ),
    8795            2 :             (
    8796            2 :                 key,
    8797            2 :                 Lsn(0x30),
    8798            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8799            2 :             ),
    8800            2 :             (
    8801            2 :                 key,
    8802            2 :                 Lsn(0x40),
    8803            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8804            2 :             ),
    8805            2 :             (
    8806            2 :                 key,
    8807            2 :                 Lsn(0x50),
    8808            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8809            2 :             ),
    8810            2 :             (
    8811            2 :                 key,
    8812            2 :                 Lsn(0x60),
    8813            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8814            2 :             ),
    8815            2 :             (
    8816            2 :                 key,
    8817            2 :                 Lsn(0x70),
    8818            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8819            2 :             ),
    8820            2 :             (
    8821            2 :                 key,
    8822            2 :                 Lsn(0x80),
    8823            2 :                 Value::Image(Bytes::copy_from_slice(
    8824            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8825            2 :                 )),
    8826            2 :             ),
    8827            2 :             (
    8828            2 :                 key,
    8829            2 :                 Lsn(0x90),
    8830            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8831            2 :             ),
    8832            2 :         ];
    8833            2 :         let res = tline
    8834            2 :             .generate_key_retention(
    8835            2 :                 key,
    8836            2 :                 &history,
    8837            2 :                 Lsn(0x60),
    8838            2 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    8839            2 :                 3,
    8840            2 :                 None,
    8841            2 :             )
    8842            2 :             .await
    8843            2 :             .unwrap();
    8844            2 :         let expected_res = KeyHistoryRetention {
    8845            2 :             below_horizon: vec![
    8846            2 :                 (
    8847            2 :                     Lsn(0x20),
    8848            2 :                     KeyLogAtLsn(vec![(
    8849            2 :                         Lsn(0x20),
    8850            2 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    8851            2 :                     )]),
    8852            2 :                 ),
    8853            2 :                 (
    8854            2 :                     Lsn(0x40),
    8855            2 :                     KeyLogAtLsn(vec![
    8856            2 :                         (
    8857            2 :                             Lsn(0x30),
    8858            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8859            2 :                         ),
    8860            2 :                         (
    8861            2 :                             Lsn(0x40),
    8862            2 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    8863            2 :                         ),
    8864            2 :                     ]),
    8865            2 :                 ),
    8866            2 :                 (
    8867            2 :                     Lsn(0x50),
    8868            2 :                     KeyLogAtLsn(vec![(
    8869            2 :                         Lsn(0x50),
    8870            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    8871            2 :                     )]),
    8872            2 :                 ),
    8873            2 :                 (
    8874            2 :                     Lsn(0x60),
    8875            2 :                     KeyLogAtLsn(vec![(
    8876            2 :                         Lsn(0x60),
    8877            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8878            2 :                     )]),
    8879            2 :                 ),
    8880            2 :             ],
    8881            2 :             above_horizon: KeyLogAtLsn(vec![
    8882            2 :                 (
    8883            2 :                     Lsn(0x70),
    8884            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8885            2 :                 ),
    8886            2 :                 (
    8887            2 :                     Lsn(0x80),
    8888            2 :                     Value::Image(Bytes::copy_from_slice(
    8889            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8890            2 :                     )),
    8891            2 :                 ),
    8892            2 :                 (
    8893            2 :                     Lsn(0x90),
    8894            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8895            2 :                 ),
    8896            2 :             ]),
    8897            2 :         };
    8898            2 :         assert_eq!(res, expected_res);
    8899            2 : 
    8900            2 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    8901            2 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    8902            2 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    8903            2 :         // For example, we have
    8904            2 :         // ```plain
    8905            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    8906            2 :         // ```
    8907            2 :         // Now the GC horizon moves up, and we have
    8908            2 :         // ```plain
    8909            2 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    8910            2 :         // ```
    8911            2 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    8912            2 :         // We will end up with
    8913            2 :         // ```plain
    8914            2 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    8915            2 :         // ```
    8916            2 :         // Now we run the GC-compaction, and this key does not have a full history.
    8917            2 :         // We should be able to handle this partial history and drop everything before the
    8918            2 :         // gc_horizon image.
    8919            2 : 
    8920            2 :         let history = vec![
    8921            2 :             (
    8922            2 :                 key,
    8923            2 :                 Lsn(0x20),
    8924            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    8925            2 :             ),
    8926            2 :             (
    8927            2 :                 key,
    8928            2 :                 Lsn(0x30),
    8929            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    8930            2 :             ),
    8931            2 :             (
    8932            2 :                 key,
    8933            2 :                 Lsn(0x40),
    8934            2 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8935            2 :             ),
    8936            2 :             (
    8937            2 :                 key,
    8938            2 :                 Lsn(0x50),
    8939            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8940            2 :             ),
    8941            2 :             (
    8942            2 :                 key,
    8943            2 :                 Lsn(0x60),
    8944            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8945            2 :             ),
    8946            2 :             (
    8947            2 :                 key,
    8948            2 :                 Lsn(0x70),
    8949            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8950            2 :             ),
    8951            2 :             (
    8952            2 :                 key,
    8953            2 :                 Lsn(0x80),
    8954            2 :                 Value::Image(Bytes::copy_from_slice(
    8955            2 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    8956            2 :                 )),
    8957            2 :             ),
    8958            2 :             (
    8959            2 :                 key,
    8960            2 :                 Lsn(0x90),
    8961            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    8962            2 :             ),
    8963            2 :         ];
    8964            2 :         let res = tline
    8965            2 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    8966            2 :             .await
    8967            2 :             .unwrap();
    8968            2 :         let expected_res = KeyHistoryRetention {
    8969            2 :             below_horizon: vec![
    8970            2 :                 (
    8971            2 :                     Lsn(0x40),
    8972            2 :                     KeyLogAtLsn(vec![(
    8973            2 :                         Lsn(0x40),
    8974            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    8975            2 :                     )]),
    8976            2 :                 ),
    8977            2 :                 (
    8978            2 :                     Lsn(0x50),
    8979            2 :                     KeyLogAtLsn(vec![(
    8980            2 :                         Lsn(0x50),
    8981            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    8982            2 :                     )]),
    8983            2 :                 ),
    8984            2 :                 (
    8985            2 :                     Lsn(0x60),
    8986            2 :                     KeyLogAtLsn(vec![(
    8987            2 :                         Lsn(0x60),
    8988            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    8989            2 :                     )]),
    8990            2 :                 ),
    8991            2 :             ],
    8992            2 :             above_horizon: KeyLogAtLsn(vec![
    8993            2 :                 (
    8994            2 :                     Lsn(0x70),
    8995            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    8996            2 :                 ),
    8997            2 :                 (
    8998            2 :                     Lsn(0x80),
    8999            2 :                     Value::Image(Bytes::copy_from_slice(
    9000            2 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9001            2 :                     )),
    9002            2 :                 ),
    9003            2 :                 (
    9004            2 :                     Lsn(0x90),
    9005            2 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9006            2 :                 ),
    9007            2 :             ]),
    9008            2 :         };
    9009            2 :         assert_eq!(res, expected_res);
    9010            2 : 
    9011            2 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9012            2 :         // the ancestor image in the test case.
    9013            2 : 
    9014            2 :         let history = vec![
    9015            2 :             (
    9016            2 :                 key,
    9017            2 :                 Lsn(0x20),
    9018            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9019            2 :             ),
    9020            2 :             (
    9021            2 :                 key,
    9022            2 :                 Lsn(0x30),
    9023            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9024            2 :             ),
    9025            2 :             (
    9026            2 :                 key,
    9027            2 :                 Lsn(0x40),
    9028            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9029            2 :             ),
    9030            2 :             (
    9031            2 :                 key,
    9032            2 :                 Lsn(0x70),
    9033            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9034            2 :             ),
    9035            2 :         ];
    9036            2 :         let res = tline
    9037            2 :             .generate_key_retention(
    9038            2 :                 key,
    9039            2 :                 &history,
    9040            2 :                 Lsn(0x60),
    9041            2 :                 &[],
    9042            2 :                 3,
    9043            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9044            2 :             )
    9045            2 :             .await
    9046            2 :             .unwrap();
    9047            2 :         let expected_res = KeyHistoryRetention {
    9048            2 :             below_horizon: vec![(
    9049            2 :                 Lsn(0x60),
    9050            2 :                 KeyLogAtLsn(vec![(
    9051            2 :                     Lsn(0x60),
    9052            2 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9053            2 :                 )]),
    9054            2 :             )],
    9055            2 :             above_horizon: KeyLogAtLsn(vec![(
    9056            2 :                 Lsn(0x70),
    9057            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9058            2 :             )]),
    9059            2 :         };
    9060            2 :         assert_eq!(res, expected_res);
    9061            2 : 
    9062            2 :         let history = vec![
    9063            2 :             (
    9064            2 :                 key,
    9065            2 :                 Lsn(0x20),
    9066            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9067            2 :             ),
    9068            2 :             (
    9069            2 :                 key,
    9070            2 :                 Lsn(0x40),
    9071            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9072            2 :             ),
    9073            2 :             (
    9074            2 :                 key,
    9075            2 :                 Lsn(0x60),
    9076            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9077            2 :             ),
    9078            2 :             (
    9079            2 :                 key,
    9080            2 :                 Lsn(0x70),
    9081            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9082            2 :             ),
    9083            2 :         ];
    9084            2 :         let res = tline
    9085            2 :             .generate_key_retention(
    9086            2 :                 key,
    9087            2 :                 &history,
    9088            2 :                 Lsn(0x60),
    9089            2 :                 &[Lsn(0x30)],
    9090            2 :                 3,
    9091            2 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9092            2 :             )
    9093            2 :             .await
    9094            2 :             .unwrap();
    9095            2 :         let expected_res = KeyHistoryRetention {
    9096            2 :             below_horizon: vec![
    9097            2 :                 (
    9098            2 :                     Lsn(0x30),
    9099            2 :                     KeyLogAtLsn(vec![(
    9100            2 :                         Lsn(0x20),
    9101            2 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9102            2 :                     )]),
    9103            2 :                 ),
    9104            2 :                 (
    9105            2 :                     Lsn(0x60),
    9106            2 :                     KeyLogAtLsn(vec![(
    9107            2 :                         Lsn(0x60),
    9108            2 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9109            2 :                     )]),
    9110            2 :                 ),
    9111            2 :             ],
    9112            2 :             above_horizon: KeyLogAtLsn(vec![(
    9113            2 :                 Lsn(0x70),
    9114            2 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9115            2 :             )]),
    9116            2 :         };
    9117            2 :         assert_eq!(res, expected_res);
    9118            2 : 
    9119            2 :         Ok(())
    9120            2 :     }
    9121              : 
    9122              :     #[cfg(feature = "testing")]
    9123              :     #[tokio::test]
    9124            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9125            2 :         let harness =
    9126            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9127            2 :         let (tenant, ctx) = harness.load().await;
    9128            2 : 
    9129          518 :         fn get_key(id: u32) -> Key {
    9130          518 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9131          518 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9132          518 :             key.field6 = id;
    9133          518 :             key
    9134          518 :         }
    9135            2 : 
    9136            2 :         let img_layer = (0..10)
    9137           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9138            2 :             .collect_vec();
    9139            2 : 
    9140            2 :         let delta1 = vec![
    9141            2 :             (
    9142            2 :                 get_key(1),
    9143            2 :                 Lsn(0x20),
    9144            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9145            2 :             ),
    9146            2 :             (
    9147            2 :                 get_key(2),
    9148            2 :                 Lsn(0x30),
    9149            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9150            2 :             ),
    9151            2 :             (
    9152            2 :                 get_key(3),
    9153            2 :                 Lsn(0x28),
    9154            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9155            2 :             ),
    9156            2 :             (
    9157            2 :                 get_key(3),
    9158            2 :                 Lsn(0x30),
    9159            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9160            2 :             ),
    9161            2 :             (
    9162            2 :                 get_key(3),
    9163            2 :                 Lsn(0x40),
    9164            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9165            2 :             ),
    9166            2 :         ];
    9167            2 :         let delta2 = vec![
    9168            2 :             (
    9169            2 :                 get_key(5),
    9170            2 :                 Lsn(0x20),
    9171            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9172            2 :             ),
    9173            2 :             (
    9174            2 :                 get_key(6),
    9175            2 :                 Lsn(0x20),
    9176            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9177            2 :             ),
    9178            2 :         ];
    9179            2 :         let delta3 = vec![
    9180            2 :             (
    9181            2 :                 get_key(8),
    9182            2 :                 Lsn(0x48),
    9183            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9184            2 :             ),
    9185            2 :             (
    9186            2 :                 get_key(9),
    9187            2 :                 Lsn(0x48),
    9188            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9189            2 :             ),
    9190            2 :         ];
    9191            2 : 
    9192            2 :         let tline = tenant
    9193            2 :             .create_test_timeline_with_layers(
    9194            2 :                 TIMELINE_ID,
    9195            2 :                 Lsn(0x10),
    9196            2 :                 DEFAULT_PG_VERSION,
    9197            2 :                 &ctx,
    9198            2 :                 vec![
    9199            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9200            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9201            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9202            2 :                 ], // delta layers
    9203            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9204            2 :                 Lsn(0x50),
    9205            2 :             )
    9206            2 :             .await?;
    9207            2 :         {
    9208            2 :             tline
    9209            2 :                 .latest_gc_cutoff_lsn
    9210            2 :                 .lock_for_write()
    9211            2 :                 .store_and_unlock(Lsn(0x30))
    9212            2 :                 .wait()
    9213            2 :                 .await;
    9214            2 :             // Update GC info
    9215            2 :             let mut guard = tline.gc_info.write().unwrap();
    9216            2 :             *guard = GcInfo {
    9217            2 :                 retain_lsns: vec![
    9218            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9219            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9220            2 :                 ],
    9221            2 :                 cutoffs: GcCutoffs {
    9222            2 :                     time: Lsn(0x30),
    9223            2 :                     space: Lsn(0x30),
    9224            2 :                 },
    9225            2 :                 leases: Default::default(),
    9226            2 :                 within_ancestor_pitr: false,
    9227            2 :             };
    9228            2 :         }
    9229            2 : 
    9230            2 :         let expected_result = [
    9231            2 :             Bytes::from_static(b"value 0@0x10"),
    9232            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9233            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9234            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9235            2 :             Bytes::from_static(b"value 4@0x10"),
    9236            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9237            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9238            2 :             Bytes::from_static(b"value 7@0x10"),
    9239            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9240            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9241            2 :         ];
    9242            2 : 
    9243            2 :         let expected_result_at_gc_horizon = [
    9244            2 :             Bytes::from_static(b"value 0@0x10"),
    9245            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9246            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9247            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9248            2 :             Bytes::from_static(b"value 4@0x10"),
    9249            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9250            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9251            2 :             Bytes::from_static(b"value 7@0x10"),
    9252            2 :             Bytes::from_static(b"value 8@0x10"),
    9253            2 :             Bytes::from_static(b"value 9@0x10"),
    9254            2 :         ];
    9255            2 : 
    9256            2 :         let expected_result_at_lsn_20 = [
    9257            2 :             Bytes::from_static(b"value 0@0x10"),
    9258            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9259            2 :             Bytes::from_static(b"value 2@0x10"),
    9260            2 :             Bytes::from_static(b"value 3@0x10"),
    9261            2 :             Bytes::from_static(b"value 4@0x10"),
    9262            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9263            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9264            2 :             Bytes::from_static(b"value 7@0x10"),
    9265            2 :             Bytes::from_static(b"value 8@0x10"),
    9266            2 :             Bytes::from_static(b"value 9@0x10"),
    9267            2 :         ];
    9268            2 : 
    9269            2 :         let expected_result_at_lsn_10 = [
    9270            2 :             Bytes::from_static(b"value 0@0x10"),
    9271            2 :             Bytes::from_static(b"value 1@0x10"),
    9272            2 :             Bytes::from_static(b"value 2@0x10"),
    9273            2 :             Bytes::from_static(b"value 3@0x10"),
    9274            2 :             Bytes::from_static(b"value 4@0x10"),
    9275            2 :             Bytes::from_static(b"value 5@0x10"),
    9276            2 :             Bytes::from_static(b"value 6@0x10"),
    9277            2 :             Bytes::from_static(b"value 7@0x10"),
    9278            2 :             Bytes::from_static(b"value 8@0x10"),
    9279            2 :             Bytes::from_static(b"value 9@0x10"),
    9280            2 :         ];
    9281            2 : 
    9282           12 :         let verify_result = || async {
    9283           12 :             let gc_horizon = {
    9284           12 :                 let gc_info = tline.gc_info.read().unwrap();
    9285           12 :                 gc_info.cutoffs.time
    9286            2 :             };
    9287          132 :             for idx in 0..10 {
    9288          120 :                 assert_eq!(
    9289          120 :                     tline
    9290          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9291          120 :                         .await
    9292          120 :                         .unwrap(),
    9293          120 :                     &expected_result[idx]
    9294            2 :                 );
    9295          120 :                 assert_eq!(
    9296          120 :                     tline
    9297          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9298          120 :                         .await
    9299          120 :                         .unwrap(),
    9300          120 :                     &expected_result_at_gc_horizon[idx]
    9301            2 :                 );
    9302          120 :                 assert_eq!(
    9303          120 :                     tline
    9304          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9305          120 :                         .await
    9306          120 :                         .unwrap(),
    9307          120 :                     &expected_result_at_lsn_20[idx]
    9308            2 :                 );
    9309          120 :                 assert_eq!(
    9310          120 :                     tline
    9311          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9312          120 :                         .await
    9313          120 :                         .unwrap(),
    9314          120 :                     &expected_result_at_lsn_10[idx]
    9315            2 :                 );
    9316            2 :             }
    9317           24 :         };
    9318            2 : 
    9319            2 :         verify_result().await;
    9320            2 : 
    9321            2 :         let cancel = CancellationToken::new();
    9322            2 :         let mut dryrun_flags = EnumSet::new();
    9323            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9324            2 : 
    9325            2 :         tline
    9326            2 :             .compact_with_gc(
    9327            2 :                 &cancel,
    9328            2 :                 CompactOptions {
    9329            2 :                     flags: dryrun_flags,
    9330            2 :                     compact_range: None,
    9331            2 :                     ..Default::default()
    9332            2 :                 },
    9333            2 :                 &ctx,
    9334            2 :             )
    9335            2 :             .await
    9336            2 :             .unwrap();
    9337            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
    9338            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9339            2 :         verify_result().await;
    9340            2 : 
    9341            2 :         tline
    9342            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9343            2 :             .await
    9344            2 :             .unwrap();
    9345            2 :         verify_result().await;
    9346            2 : 
    9347            2 :         // compact again
    9348            2 :         tline
    9349            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9350            2 :             .await
    9351            2 :             .unwrap();
    9352            2 :         verify_result().await;
    9353            2 : 
    9354            2 :         // increase GC horizon and compact again
    9355            2 :         {
    9356            2 :             tline
    9357            2 :                 .latest_gc_cutoff_lsn
    9358            2 :                 .lock_for_write()
    9359            2 :                 .store_and_unlock(Lsn(0x38))
    9360            2 :                 .wait()
    9361            2 :                 .await;
    9362            2 :             // Update GC info
    9363            2 :             let mut guard = tline.gc_info.write().unwrap();
    9364            2 :             guard.cutoffs.time = Lsn(0x38);
    9365            2 :             guard.cutoffs.space = Lsn(0x38);
    9366            2 :         }
    9367            2 :         tline
    9368            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9369            2 :             .await
    9370            2 :             .unwrap();
    9371            2 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9372            2 : 
    9373            2 :         // not increasing the GC horizon and compact again
    9374            2 :         tline
    9375            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9376            2 :             .await
    9377            2 :             .unwrap();
    9378            2 :         verify_result().await;
    9379            2 : 
    9380            2 :         Ok(())
    9381            2 :     }
    9382              : 
    9383              :     #[cfg(feature = "testing")]
    9384              :     #[tokio::test]
    9385            2 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9386            2 :     {
    9387            2 :         let harness =
    9388            2 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9389            2 :                 .await?;
    9390            2 :         let (tenant, ctx) = harness.load().await;
    9391            2 : 
    9392          352 :         fn get_key(id: u32) -> Key {
    9393          352 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9394          352 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9395          352 :             key.field6 = id;
    9396          352 :             key
    9397          352 :         }
    9398            2 : 
    9399            2 :         let img_layer = (0..10)
    9400           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9401            2 :             .collect_vec();
    9402            2 : 
    9403            2 :         let delta1 = vec![
    9404            2 :             (
    9405            2 :                 get_key(1),
    9406            2 :                 Lsn(0x20),
    9407            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9408            2 :             ),
    9409            2 :             (
    9410            2 :                 get_key(1),
    9411            2 :                 Lsn(0x28),
    9412            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9413            2 :             ),
    9414            2 :         ];
    9415            2 :         let delta2 = vec![
    9416            2 :             (
    9417            2 :                 get_key(1),
    9418            2 :                 Lsn(0x30),
    9419            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9420            2 :             ),
    9421            2 :             (
    9422            2 :                 get_key(1),
    9423            2 :                 Lsn(0x38),
    9424            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9425            2 :             ),
    9426            2 :         ];
    9427            2 :         let delta3 = vec![
    9428            2 :             (
    9429            2 :                 get_key(8),
    9430            2 :                 Lsn(0x48),
    9431            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9432            2 :             ),
    9433            2 :             (
    9434            2 :                 get_key(9),
    9435            2 :                 Lsn(0x48),
    9436            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9437            2 :             ),
    9438            2 :         ];
    9439            2 : 
    9440            2 :         let tline = tenant
    9441            2 :             .create_test_timeline_with_layers(
    9442            2 :                 TIMELINE_ID,
    9443            2 :                 Lsn(0x10),
    9444            2 :                 DEFAULT_PG_VERSION,
    9445            2 :                 &ctx,
    9446            2 :                 vec![
    9447            2 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9448            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9449            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9450            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9451            2 :                 ], // delta layers
    9452            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9453            2 :                 Lsn(0x50),
    9454            2 :             )
    9455            2 :             .await?;
    9456            2 :         {
    9457            2 :             tline
    9458            2 :                 .latest_gc_cutoff_lsn
    9459            2 :                 .lock_for_write()
    9460            2 :                 .store_and_unlock(Lsn(0x30))
    9461            2 :                 .wait()
    9462            2 :                 .await;
    9463            2 :             // Update GC info
    9464            2 :             let mut guard = tline.gc_info.write().unwrap();
    9465            2 :             *guard = GcInfo {
    9466            2 :                 retain_lsns: vec![
    9467            2 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9468            2 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9469            2 :                 ],
    9470            2 :                 cutoffs: GcCutoffs {
    9471            2 :                     time: Lsn(0x30),
    9472            2 :                     space: Lsn(0x30),
    9473            2 :                 },
    9474            2 :                 leases: Default::default(),
    9475            2 :                 within_ancestor_pitr: false,
    9476            2 :             };
    9477            2 :         }
    9478            2 : 
    9479            2 :         let expected_result = [
    9480            2 :             Bytes::from_static(b"value 0@0x10"),
    9481            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9482            2 :             Bytes::from_static(b"value 2@0x10"),
    9483            2 :             Bytes::from_static(b"value 3@0x10"),
    9484            2 :             Bytes::from_static(b"value 4@0x10"),
    9485            2 :             Bytes::from_static(b"value 5@0x10"),
    9486            2 :             Bytes::from_static(b"value 6@0x10"),
    9487            2 :             Bytes::from_static(b"value 7@0x10"),
    9488            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9489            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9490            2 :         ];
    9491            2 : 
    9492            2 :         let expected_result_at_gc_horizon = [
    9493            2 :             Bytes::from_static(b"value 0@0x10"),
    9494            2 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9495            2 :             Bytes::from_static(b"value 2@0x10"),
    9496            2 :             Bytes::from_static(b"value 3@0x10"),
    9497            2 :             Bytes::from_static(b"value 4@0x10"),
    9498            2 :             Bytes::from_static(b"value 5@0x10"),
    9499            2 :             Bytes::from_static(b"value 6@0x10"),
    9500            2 :             Bytes::from_static(b"value 7@0x10"),
    9501            2 :             Bytes::from_static(b"value 8@0x10"),
    9502            2 :             Bytes::from_static(b"value 9@0x10"),
    9503            2 :         ];
    9504            2 : 
    9505            2 :         let expected_result_at_lsn_20 = [
    9506            2 :             Bytes::from_static(b"value 0@0x10"),
    9507            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9508            2 :             Bytes::from_static(b"value 2@0x10"),
    9509            2 :             Bytes::from_static(b"value 3@0x10"),
    9510            2 :             Bytes::from_static(b"value 4@0x10"),
    9511            2 :             Bytes::from_static(b"value 5@0x10"),
    9512            2 :             Bytes::from_static(b"value 6@0x10"),
    9513            2 :             Bytes::from_static(b"value 7@0x10"),
    9514            2 :             Bytes::from_static(b"value 8@0x10"),
    9515            2 :             Bytes::from_static(b"value 9@0x10"),
    9516            2 :         ];
    9517            2 : 
    9518            2 :         let expected_result_at_lsn_10 = [
    9519            2 :             Bytes::from_static(b"value 0@0x10"),
    9520            2 :             Bytes::from_static(b"value 1@0x10"),
    9521            2 :             Bytes::from_static(b"value 2@0x10"),
    9522            2 :             Bytes::from_static(b"value 3@0x10"),
    9523            2 :             Bytes::from_static(b"value 4@0x10"),
    9524            2 :             Bytes::from_static(b"value 5@0x10"),
    9525            2 :             Bytes::from_static(b"value 6@0x10"),
    9526            2 :             Bytes::from_static(b"value 7@0x10"),
    9527            2 :             Bytes::from_static(b"value 8@0x10"),
    9528            2 :             Bytes::from_static(b"value 9@0x10"),
    9529            2 :         ];
    9530            2 : 
    9531            8 :         let verify_result = || async {
    9532            8 :             let gc_horizon = {
    9533            8 :                 let gc_info = tline.gc_info.read().unwrap();
    9534            8 :                 gc_info.cutoffs.time
    9535            2 :             };
    9536           88 :             for idx in 0..10 {
    9537           80 :                 assert_eq!(
    9538           80 :                     tline
    9539           80 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9540           80 :                         .await
    9541           80 :                         .unwrap(),
    9542           80 :                     &expected_result[idx]
    9543            2 :                 );
    9544           80 :                 assert_eq!(
    9545           80 :                     tline
    9546           80 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9547           80 :                         .await
    9548           80 :                         .unwrap(),
    9549           80 :                     &expected_result_at_gc_horizon[idx]
    9550            2 :                 );
    9551           80 :                 assert_eq!(
    9552           80 :                     tline
    9553           80 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9554           80 :                         .await
    9555           80 :                         .unwrap(),
    9556           80 :                     &expected_result_at_lsn_20[idx]
    9557            2 :                 );
    9558           80 :                 assert_eq!(
    9559           80 :                     tline
    9560           80 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9561           80 :                         .await
    9562           80 :                         .unwrap(),
    9563           80 :                     &expected_result_at_lsn_10[idx]
    9564            2 :                 );
    9565            2 :             }
    9566           16 :         };
    9567            2 : 
    9568            2 :         verify_result().await;
    9569            2 : 
    9570            2 :         let cancel = CancellationToken::new();
    9571            2 :         let mut dryrun_flags = EnumSet::new();
    9572            2 :         dryrun_flags.insert(CompactFlags::DryRun);
    9573            2 : 
    9574            2 :         tline
    9575            2 :             .compact_with_gc(
    9576            2 :                 &cancel,
    9577            2 :                 CompactOptions {
    9578            2 :                     flags: dryrun_flags,
    9579            2 :                     compact_range: None,
    9580            2 :                     ..Default::default()
    9581            2 :                 },
    9582            2 :                 &ctx,
    9583            2 :             )
    9584            2 :             .await
    9585            2 :             .unwrap();
    9586            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
    9587            2 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9588            2 :         verify_result().await;
    9589            2 : 
    9590            2 :         tline
    9591            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9592            2 :             .await
    9593            2 :             .unwrap();
    9594            2 :         verify_result().await;
    9595            2 : 
    9596            2 :         // compact again
    9597            2 :         tline
    9598            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9599            2 :             .await
    9600            2 :             .unwrap();
    9601            2 :         verify_result().await;
    9602            2 : 
    9603            2 :         Ok(())
    9604            2 :     }
    9605              : 
    9606              :     #[cfg(feature = "testing")]
    9607              :     #[tokio::test]
    9608            2 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9609            2 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9610            2 :         let (tenant, ctx) = harness.load().await;
    9611            2 : 
    9612          126 :         fn get_key(id: u32) -> Key {
    9613          126 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9614          126 :             key.field6 = id;
    9615          126 :             key
    9616          126 :         }
    9617            2 : 
    9618            2 :         let img_layer = (0..10)
    9619           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9620            2 :             .collect_vec();
    9621            2 : 
    9622            2 :         let delta1 = vec![
    9623            2 :             (
    9624            2 :                 get_key(1),
    9625            2 :                 Lsn(0x20),
    9626            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9627            2 :             ),
    9628            2 :             (
    9629            2 :                 get_key(2),
    9630            2 :                 Lsn(0x30),
    9631            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9632            2 :             ),
    9633            2 :             (
    9634            2 :                 get_key(3),
    9635            2 :                 Lsn(0x28),
    9636            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9637            2 :             ),
    9638            2 :             (
    9639            2 :                 get_key(3),
    9640            2 :                 Lsn(0x30),
    9641            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9642            2 :             ),
    9643            2 :             (
    9644            2 :                 get_key(3),
    9645            2 :                 Lsn(0x40),
    9646            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9647            2 :             ),
    9648            2 :         ];
    9649            2 :         let delta2 = vec![
    9650            2 :             (
    9651            2 :                 get_key(5),
    9652            2 :                 Lsn(0x20),
    9653            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9654            2 :             ),
    9655            2 :             (
    9656            2 :                 get_key(6),
    9657            2 :                 Lsn(0x20),
    9658            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9659            2 :             ),
    9660            2 :         ];
    9661            2 :         let delta3 = vec![
    9662            2 :             (
    9663            2 :                 get_key(8),
    9664            2 :                 Lsn(0x48),
    9665            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9666            2 :             ),
    9667            2 :             (
    9668            2 :                 get_key(9),
    9669            2 :                 Lsn(0x48),
    9670            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9671            2 :             ),
    9672            2 :         ];
    9673            2 : 
    9674            2 :         let parent_tline = tenant
    9675            2 :             .create_test_timeline_with_layers(
    9676            2 :                 TIMELINE_ID,
    9677            2 :                 Lsn(0x10),
    9678            2 :                 DEFAULT_PG_VERSION,
    9679            2 :                 &ctx,
    9680            2 :                 vec![],                       // delta layers
    9681            2 :                 vec![(Lsn(0x18), img_layer)], // image layers
    9682            2 :                 Lsn(0x18),
    9683            2 :             )
    9684            2 :             .await?;
    9685            2 : 
    9686            2 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9687            2 : 
    9688            2 :         let branch_tline = tenant
    9689            2 :             .branch_timeline_test_with_layers(
    9690            2 :                 &parent_tline,
    9691            2 :                 NEW_TIMELINE_ID,
    9692            2 :                 Some(Lsn(0x18)),
    9693            2 :                 &ctx,
    9694            2 :                 vec![
    9695            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9696            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9697            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9698            2 :                 ], // delta layers
    9699            2 :                 vec![], // image layers
    9700            2 :                 Lsn(0x50),
    9701            2 :             )
    9702            2 :             .await?;
    9703            2 : 
    9704            2 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
    9705            2 : 
    9706            2 :         {
    9707            2 :             parent_tline
    9708            2 :                 .latest_gc_cutoff_lsn
    9709            2 :                 .lock_for_write()
    9710            2 :                 .store_and_unlock(Lsn(0x10))
    9711            2 :                 .wait()
    9712            2 :                 .await;
    9713            2 :             // Update GC info
    9714            2 :             let mut guard = parent_tline.gc_info.write().unwrap();
    9715            2 :             *guard = GcInfo {
    9716            2 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
    9717            2 :                 cutoffs: GcCutoffs {
    9718            2 :                     time: Lsn(0x10),
    9719            2 :                     space: Lsn(0x10),
    9720            2 :                 },
    9721            2 :                 leases: Default::default(),
    9722            2 :                 within_ancestor_pitr: false,
    9723            2 :             };
    9724            2 :         }
    9725            2 : 
    9726            2 :         {
    9727            2 :             branch_tline
    9728            2 :                 .latest_gc_cutoff_lsn
    9729            2 :                 .lock_for_write()
    9730            2 :                 .store_and_unlock(Lsn(0x50))
    9731            2 :                 .wait()
    9732            2 :                 .await;
    9733            2 :             // Update GC info
    9734            2 :             let mut guard = branch_tline.gc_info.write().unwrap();
    9735            2 :             *guard = GcInfo {
    9736            2 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
    9737            2 :                 cutoffs: GcCutoffs {
    9738            2 :                     time: Lsn(0x50),
    9739            2 :                     space: Lsn(0x50),
    9740            2 :                 },
    9741            2 :                 leases: Default::default(),
    9742            2 :                 within_ancestor_pitr: false,
    9743            2 :             };
    9744            2 :         }
    9745            2 : 
    9746            2 :         let expected_result_at_gc_horizon = [
    9747            2 :             Bytes::from_static(b"value 0@0x10"),
    9748            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9749            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9750            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9751            2 :             Bytes::from_static(b"value 4@0x10"),
    9752            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9753            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9754            2 :             Bytes::from_static(b"value 7@0x10"),
    9755            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9756            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9757            2 :         ];
    9758            2 : 
    9759            2 :         let expected_result_at_lsn_40 = [
    9760            2 :             Bytes::from_static(b"value 0@0x10"),
    9761            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9762            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9763            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9764            2 :             Bytes::from_static(b"value 4@0x10"),
    9765            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9766            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9767            2 :             Bytes::from_static(b"value 7@0x10"),
    9768            2 :             Bytes::from_static(b"value 8@0x10"),
    9769            2 :             Bytes::from_static(b"value 9@0x10"),
    9770            2 :         ];
    9771            2 : 
    9772            4 :         let verify_result = || async {
    9773           44 :             for idx in 0..10 {
    9774           40 :                 assert_eq!(
    9775           40 :                     branch_tline
    9776           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9777           40 :                         .await
    9778           40 :                         .unwrap(),
    9779           40 :                     &expected_result_at_gc_horizon[idx]
    9780            2 :                 );
    9781           40 :                 assert_eq!(
    9782           40 :                     branch_tline
    9783           40 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
    9784           40 :                         .await
    9785           40 :                         .unwrap(),
    9786           40 :                     &expected_result_at_lsn_40[idx]
    9787            2 :                 );
    9788            2 :             }
    9789            8 :         };
    9790            2 : 
    9791            2 :         verify_result().await;
    9792            2 : 
    9793            2 :         let cancel = CancellationToken::new();
    9794            2 :         branch_tline
    9795            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9796            2 :             .await
    9797            2 :             .unwrap();
    9798            2 : 
    9799            2 :         verify_result().await;
    9800            2 : 
    9801            2 :         Ok(())
    9802            2 :     }
    9803              : 
    9804              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
    9805              :     // Create an image arrangement where we have to read at different LSN ranges
    9806              :     // from a delta layer. This is achieved by overlapping an image layer on top of
    9807              :     // a delta layer. Like so:
    9808              :     //
    9809              :     //     A      B
    9810              :     // +----------------+ -> delta_layer
    9811              :     // |                |                           ^ lsn
    9812              :     // |       =========|-> nested_image_layer      |
    9813              :     // |       C        |                           |
    9814              :     // +----------------+                           |
    9815              :     // ======== -> baseline_image_layer             +-------> key
    9816              :     //
    9817              :     //
    9818              :     // When querying the key range [A, B) we need to read at different LSN ranges
    9819              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
    9820              :     #[cfg(feature = "testing")]
    9821              :     #[tokio::test]
    9822            2 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
    9823            2 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
    9824            2 :         let (tenant, ctx) = harness.load().await;
    9825            2 : 
    9826            2 :         let will_init_keys = [2, 6];
    9827           44 :         fn get_key(id: u32) -> Key {
    9828           44 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
    9829           44 :             key.field6 = id;
    9830           44 :             key
    9831           44 :         }
    9832            2 : 
    9833            2 :         let mut expected_key_values = HashMap::new();
    9834            2 : 
    9835            2 :         let baseline_image_layer_lsn = Lsn(0x10);
    9836            2 :         let mut baseline_img_layer = Vec::new();
    9837           12 :         for i in 0..5 {
    9838           10 :             let key = get_key(i);
    9839           10 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
    9840           10 : 
    9841           10 :             let removed = expected_key_values.insert(key, value.clone());
    9842           10 :             assert!(removed.is_none());
    9843            2 : 
    9844           10 :             baseline_img_layer.push((key, Bytes::from(value)));
    9845            2 :         }
    9846            2 : 
    9847            2 :         let nested_image_layer_lsn = Lsn(0x50);
    9848            2 :         let mut nested_img_layer = Vec::new();
    9849           12 :         for i in 5..10 {
    9850           10 :             let key = get_key(i);
    9851           10 :             let value = format!("value {i}@{nested_image_layer_lsn}");
    9852           10 : 
    9853           10 :             let removed = expected_key_values.insert(key, value.clone());
    9854           10 :             assert!(removed.is_none());
    9855            2 : 
    9856           10 :             nested_img_layer.push((key, Bytes::from(value)));
    9857            2 :         }
    9858            2 : 
    9859            2 :         let mut delta_layer_spec = Vec::default();
    9860            2 :         let delta_layer_start_lsn = Lsn(0x20);
    9861            2 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
    9862            2 : 
    9863           22 :         for i in 0..10 {
    9864           20 :             let key = get_key(i);
    9865           20 :             let key_in_nested = nested_img_layer
    9866           20 :                 .iter()
    9867           80 :                 .any(|(key_with_img, _)| *key_with_img == key);
    9868           20 :             let lsn = {
    9869           20 :                 if key_in_nested {
    9870           10 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
    9871            2 :                 } else {
    9872           10 :                     delta_layer_start_lsn
    9873            2 :                 }
    9874            2 :             };
    9875            2 : 
    9876           20 :             let will_init = will_init_keys.contains(&i);
    9877           20 :             if will_init {
    9878            4 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
    9879            4 : 
    9880            4 :                 expected_key_values.insert(key, "".to_string());
    9881           16 :             } else {
    9882           16 :                 let delta = format!("@{lsn}");
    9883           16 :                 delta_layer_spec.push((
    9884           16 :                     key,
    9885           16 :                     lsn,
    9886           16 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
    9887           16 :                 ));
    9888           16 : 
    9889           16 :                 expected_key_values
    9890           16 :                     .get_mut(&key)
    9891           16 :                     .expect("An image exists for each key")
    9892           16 :                     .push_str(delta.as_str());
    9893           16 :             }
    9894           20 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
    9895            2 :         }
    9896            2 : 
    9897            2 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
    9898            2 : 
    9899            2 :         assert!(
    9900            2 :             nested_image_layer_lsn > delta_layer_start_lsn
    9901            2 :                 && nested_image_layer_lsn < delta_layer_end_lsn
    9902            2 :         );
    9903            2 : 
    9904            2 :         let tline = tenant
    9905            2 :             .create_test_timeline_with_layers(
    9906            2 :                 TIMELINE_ID,
    9907            2 :                 baseline_image_layer_lsn,
    9908            2 :                 DEFAULT_PG_VERSION,
    9909            2 :                 &ctx,
    9910            2 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9911            2 :                     delta_layer_start_lsn..delta_layer_end_lsn,
    9912            2 :                     delta_layer_spec,
    9913            2 :                 )], // delta layers
    9914            2 :                 vec![
    9915            2 :                     (baseline_image_layer_lsn, baseline_img_layer),
    9916            2 :                     (nested_image_layer_lsn, nested_img_layer),
    9917            2 :                 ], // image layers
    9918            2 :                 delta_layer_end_lsn,
    9919            2 :             )
    9920            2 :             .await?;
    9921            2 : 
    9922            2 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
    9923            2 :         let results = tline
    9924            2 :             .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
    9925            2 :             .await
    9926            2 :             .expect("No vectored errors");
    9927           22 :         for (key, res) in results {
    9928           20 :             let value = res.expect("No key errors");
    9929           20 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
    9930           20 :             assert_eq!(value, Bytes::from(expected_value));
    9931            2 :         }
    9932            2 : 
    9933            2 :         Ok(())
    9934            2 :     }
    9935              : 
    9936          142 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
    9937          142 :         (
    9938          142 :             k1.is_delta,
    9939          142 :             k1.key_range.start,
    9940          142 :             k1.key_range.end,
    9941          142 :             k1.lsn_range.start,
    9942          142 :             k1.lsn_range.end,
    9943          142 :         )
    9944          142 :             .cmp(&(
    9945          142 :                 k2.is_delta,
    9946          142 :                 k2.key_range.start,
    9947          142 :                 k2.key_range.end,
    9948          142 :                 k2.lsn_range.start,
    9949          142 :                 k2.lsn_range.end,
    9950          142 :             ))
    9951          142 :     }
    9952              : 
    9953           12 :     async fn inspect_and_sort(
    9954           12 :         tline: &Arc<Timeline>,
    9955           12 :         filter: Option<std::ops::Range<Key>>,
    9956           12 :     ) -> Vec<PersistentLayerKey> {
    9957           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
    9958           12 :         if let Some(filter) = filter {
    9959           64 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
    9960           10 :         }
    9961           12 :         all_layers.sort_by(sort_layer_key);
    9962           12 :         all_layers
    9963           12 :     }
    9964              : 
    9965              :     #[cfg(feature = "testing")]
    9966           10 :     fn check_layer_map_key_eq(
    9967           10 :         mut left: Vec<PersistentLayerKey>,
    9968           10 :         mut right: Vec<PersistentLayerKey>,
    9969           10 :     ) {
    9970           10 :         left.sort_by(sort_layer_key);
    9971           10 :         right.sort_by(sort_layer_key);
    9972           10 :         if left != right {
    9973            0 :             eprintln!("---LEFT---");
    9974            0 :             for left in left.iter() {
    9975            0 :                 eprintln!("{}", left);
    9976            0 :             }
    9977            0 :             eprintln!("---RIGHT---");
    9978            0 :             for right in right.iter() {
    9979            0 :                 eprintln!("{}", right);
    9980            0 :             }
    9981            0 :             assert_eq!(left, right);
    9982           10 :         }
    9983           10 :     }
    9984              : 
    9985              :     #[cfg(feature = "testing")]
    9986              :     #[tokio::test]
    9987            2 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
    9988            2 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
    9989            2 :         let (tenant, ctx) = harness.load().await;
    9990            2 : 
    9991          182 :         fn get_key(id: u32) -> Key {
    9992          182 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9993          182 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9994          182 :             key.field6 = id;
    9995          182 :             key
    9996          182 :         }
    9997            2 : 
    9998            2 :         // img layer at 0x10
    9999            2 :         let img_layer = (0..10)
   10000           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10001            2 :             .collect_vec();
   10002            2 : 
   10003            2 :         let delta1 = vec![
   10004            2 :             (
   10005            2 :                 get_key(1),
   10006            2 :                 Lsn(0x20),
   10007            2 :                 Value::Image(Bytes::from("value 1@0x20")),
   10008            2 :             ),
   10009            2 :             (
   10010            2 :                 get_key(2),
   10011            2 :                 Lsn(0x30),
   10012            2 :                 Value::Image(Bytes::from("value 2@0x30")),
   10013            2 :             ),
   10014            2 :             (
   10015            2 :                 get_key(3),
   10016            2 :                 Lsn(0x40),
   10017            2 :                 Value::Image(Bytes::from("value 3@0x40")),
   10018            2 :             ),
   10019            2 :         ];
   10020            2 :         let delta2 = vec![
   10021            2 :             (
   10022            2 :                 get_key(5),
   10023            2 :                 Lsn(0x20),
   10024            2 :                 Value::Image(Bytes::from("value 5@0x20")),
   10025            2 :             ),
   10026            2 :             (
   10027            2 :                 get_key(6),
   10028            2 :                 Lsn(0x20),
   10029            2 :                 Value::Image(Bytes::from("value 6@0x20")),
   10030            2 :             ),
   10031            2 :         ];
   10032            2 :         let delta3 = vec![
   10033            2 :             (
   10034            2 :                 get_key(8),
   10035            2 :                 Lsn(0x48),
   10036            2 :                 Value::Image(Bytes::from("value 8@0x48")),
   10037            2 :             ),
   10038            2 :             (
   10039            2 :                 get_key(9),
   10040            2 :                 Lsn(0x48),
   10041            2 :                 Value::Image(Bytes::from("value 9@0x48")),
   10042            2 :             ),
   10043            2 :         ];
   10044            2 : 
   10045            2 :         let tline = tenant
   10046            2 :             .create_test_timeline_with_layers(
   10047            2 :                 TIMELINE_ID,
   10048            2 :                 Lsn(0x10),
   10049            2 :                 DEFAULT_PG_VERSION,
   10050            2 :                 &ctx,
   10051            2 :                 vec![
   10052            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10053            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10054            2 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10055            2 :                 ], // delta layers
   10056            2 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10057            2 :                 Lsn(0x50),
   10058            2 :             )
   10059            2 :             .await?;
   10060            2 : 
   10061            2 :         {
   10062            2 :             tline
   10063            2 :                 .latest_gc_cutoff_lsn
   10064            2 :                 .lock_for_write()
   10065            2 :                 .store_and_unlock(Lsn(0x30))
   10066            2 :                 .wait()
   10067            2 :                 .await;
   10068            2 :             // Update GC info
   10069            2 :             let mut guard = tline.gc_info.write().unwrap();
   10070            2 :             *guard = GcInfo {
   10071            2 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10072            2 :                 cutoffs: GcCutoffs {
   10073            2 :                     time: Lsn(0x30),
   10074            2 :                     space: Lsn(0x30),
   10075            2 :                 },
   10076            2 :                 leases: Default::default(),
   10077            2 :                 within_ancestor_pitr: false,
   10078            2 :             };
   10079            2 :         }
   10080            2 : 
   10081            2 :         let cancel = CancellationToken::new();
   10082            2 : 
   10083            2 :         // Do a partial compaction on key range 0..2
   10084            2 :         tline
   10085            2 :             .compact_with_gc(
   10086            2 :                 &cancel,
   10087            2 :                 CompactOptions {
   10088            2 :                     flags: EnumSet::new(),
   10089            2 :                     compact_range: Some((get_key(0)..get_key(2)).into()),
   10090            2 :                     ..Default::default()
   10091            2 :                 },
   10092            2 :                 &ctx,
   10093            2 :             )
   10094            2 :             .await
   10095            2 :             .unwrap();
   10096            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10097            2 :         check_layer_map_key_eq(
   10098            2 :             all_layers,
   10099            2 :             vec![
   10100            2 :                 // newly-generated image layer for the partial compaction range 0-2
   10101            2 :                 PersistentLayerKey {
   10102            2 :                     key_range: get_key(0)..get_key(2),
   10103            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10104            2 :                     is_delta: false,
   10105            2 :                 },
   10106            2 :                 PersistentLayerKey {
   10107            2 :                     key_range: get_key(0)..get_key(10),
   10108            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10109            2 :                     is_delta: false,
   10110            2 :                 },
   10111            2 :                 // delta1 is split and the second part is rewritten
   10112            2 :                 PersistentLayerKey {
   10113            2 :                     key_range: get_key(2)..get_key(4),
   10114            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10115            2 :                     is_delta: true,
   10116            2 :                 },
   10117            2 :                 PersistentLayerKey {
   10118            2 :                     key_range: get_key(5)..get_key(7),
   10119            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10120            2 :                     is_delta: true,
   10121            2 :                 },
   10122            2 :                 PersistentLayerKey {
   10123            2 :                     key_range: get_key(8)..get_key(10),
   10124            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10125            2 :                     is_delta: true,
   10126            2 :                 },
   10127            2 :             ],
   10128            2 :         );
   10129            2 : 
   10130            2 :         // Do a partial compaction on key range 2..4
   10131            2 :         tline
   10132            2 :             .compact_with_gc(
   10133            2 :                 &cancel,
   10134            2 :                 CompactOptions {
   10135            2 :                     flags: EnumSet::new(),
   10136            2 :                     compact_range: Some((get_key(2)..get_key(4)).into()),
   10137            2 :                     ..Default::default()
   10138            2 :                 },
   10139            2 :                 &ctx,
   10140            2 :             )
   10141            2 :             .await
   10142            2 :             .unwrap();
   10143            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10144            2 :         check_layer_map_key_eq(
   10145            2 :             all_layers,
   10146            2 :             vec![
   10147            2 :                 PersistentLayerKey {
   10148            2 :                     key_range: get_key(0)..get_key(2),
   10149            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10150            2 :                     is_delta: false,
   10151            2 :                 },
   10152            2 :                 PersistentLayerKey {
   10153            2 :                     key_range: get_key(0)..get_key(10),
   10154            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10155            2 :                     is_delta: false,
   10156            2 :                 },
   10157            2 :                 // image layer generated for the compaction range 2-4
   10158            2 :                 PersistentLayerKey {
   10159            2 :                     key_range: get_key(2)..get_key(4),
   10160            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10161            2 :                     is_delta: false,
   10162            2 :                 },
   10163            2 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10164            2 :                 PersistentLayerKey {
   10165            2 :                     key_range: get_key(2)..get_key(4),
   10166            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10167            2 :                     is_delta: true,
   10168            2 :                 },
   10169            2 :                 PersistentLayerKey {
   10170            2 :                     key_range: get_key(5)..get_key(7),
   10171            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10172            2 :                     is_delta: true,
   10173            2 :                 },
   10174            2 :                 PersistentLayerKey {
   10175            2 :                     key_range: get_key(8)..get_key(10),
   10176            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10177            2 :                     is_delta: true,
   10178            2 :                 },
   10179            2 :             ],
   10180            2 :         );
   10181            2 : 
   10182            2 :         // Do a partial compaction on key range 4..9
   10183            2 :         tline
   10184            2 :             .compact_with_gc(
   10185            2 :                 &cancel,
   10186            2 :                 CompactOptions {
   10187            2 :                     flags: EnumSet::new(),
   10188            2 :                     compact_range: Some((get_key(4)..get_key(9)).into()),
   10189            2 :                     ..Default::default()
   10190            2 :                 },
   10191            2 :                 &ctx,
   10192            2 :             )
   10193            2 :             .await
   10194            2 :             .unwrap();
   10195            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10196            2 :         check_layer_map_key_eq(
   10197            2 :             all_layers,
   10198            2 :             vec![
   10199            2 :                 PersistentLayerKey {
   10200            2 :                     key_range: get_key(0)..get_key(2),
   10201            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10202            2 :                     is_delta: false,
   10203            2 :                 },
   10204            2 :                 PersistentLayerKey {
   10205            2 :                     key_range: get_key(0)..get_key(10),
   10206            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10207            2 :                     is_delta: false,
   10208            2 :                 },
   10209            2 :                 PersistentLayerKey {
   10210            2 :                     key_range: get_key(2)..get_key(4),
   10211            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10212            2 :                     is_delta: false,
   10213            2 :                 },
   10214            2 :                 PersistentLayerKey {
   10215            2 :                     key_range: get_key(2)..get_key(4),
   10216            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10217            2 :                     is_delta: true,
   10218            2 :                 },
   10219            2 :                 // image layer generated for this compaction range
   10220            2 :                 PersistentLayerKey {
   10221            2 :                     key_range: get_key(4)..get_key(9),
   10222            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10223            2 :                     is_delta: false,
   10224            2 :                 },
   10225            2 :                 PersistentLayerKey {
   10226            2 :                     key_range: get_key(8)..get_key(10),
   10227            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10228            2 :                     is_delta: true,
   10229            2 :                 },
   10230            2 :             ],
   10231            2 :         );
   10232            2 : 
   10233            2 :         // Do a partial compaction on key range 9..10
   10234            2 :         tline
   10235            2 :             .compact_with_gc(
   10236            2 :                 &cancel,
   10237            2 :                 CompactOptions {
   10238            2 :                     flags: EnumSet::new(),
   10239            2 :                     compact_range: Some((get_key(9)..get_key(10)).into()),
   10240            2 :                     ..Default::default()
   10241            2 :                 },
   10242            2 :                 &ctx,
   10243            2 :             )
   10244            2 :             .await
   10245            2 :             .unwrap();
   10246            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10247            2 :         check_layer_map_key_eq(
   10248            2 :             all_layers,
   10249            2 :             vec![
   10250            2 :                 PersistentLayerKey {
   10251            2 :                     key_range: get_key(0)..get_key(2),
   10252            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10253            2 :                     is_delta: false,
   10254            2 :                 },
   10255            2 :                 PersistentLayerKey {
   10256            2 :                     key_range: get_key(0)..get_key(10),
   10257            2 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10258            2 :                     is_delta: false,
   10259            2 :                 },
   10260            2 :                 PersistentLayerKey {
   10261            2 :                     key_range: get_key(2)..get_key(4),
   10262            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10263            2 :                     is_delta: false,
   10264            2 :                 },
   10265            2 :                 PersistentLayerKey {
   10266            2 :                     key_range: get_key(2)..get_key(4),
   10267            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10268            2 :                     is_delta: true,
   10269            2 :                 },
   10270            2 :                 PersistentLayerKey {
   10271            2 :                     key_range: get_key(4)..get_key(9),
   10272            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10273            2 :                     is_delta: false,
   10274            2 :                 },
   10275            2 :                 // image layer generated for the compaction range
   10276            2 :                 PersistentLayerKey {
   10277            2 :                     key_range: get_key(9)..get_key(10),
   10278            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10279            2 :                     is_delta: false,
   10280            2 :                 },
   10281            2 :                 PersistentLayerKey {
   10282            2 :                     key_range: get_key(8)..get_key(10),
   10283            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10284            2 :                     is_delta: true,
   10285            2 :                 },
   10286            2 :             ],
   10287            2 :         );
   10288            2 : 
   10289            2 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10290            2 :         tline
   10291            2 :             .compact_with_gc(
   10292            2 :                 &cancel,
   10293            2 :                 CompactOptions {
   10294            2 :                     flags: EnumSet::new(),
   10295            2 :                     compact_range: Some((get_key(0)..get_key(10)).into()),
   10296            2 :                     ..Default::default()
   10297            2 :                 },
   10298            2 :                 &ctx,
   10299            2 :             )
   10300            2 :             .await
   10301            2 :             .unwrap();
   10302            2 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10303            2 :         check_layer_map_key_eq(
   10304            2 :             all_layers,
   10305            2 :             vec![
   10306            2 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10307            2 :                 PersistentLayerKey {
   10308            2 :                     key_range: get_key(0)..get_key(10),
   10309            2 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10310            2 :                     is_delta: false,
   10311            2 :                 },
   10312            2 :                 PersistentLayerKey {
   10313            2 :                     key_range: get_key(2)..get_key(4),
   10314            2 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10315            2 :                     is_delta: true,
   10316            2 :                 },
   10317            2 :                 PersistentLayerKey {
   10318            2 :                     key_range: get_key(8)..get_key(10),
   10319            2 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10320            2 :                     is_delta: true,
   10321            2 :                 },
   10322            2 :             ],
   10323            2 :         );
   10324            2 : 
   10325            2 :         Ok(())
   10326            2 :     }
   10327              : 
   10328              :     #[cfg(feature = "testing")]
   10329              :     #[tokio::test]
   10330            2 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10331            2 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10332            2 :             .await
   10333            2 :             .unwrap();
   10334            2 :         let (tenant, ctx) = harness.load().await;
   10335            2 :         let tline_parent = tenant
   10336            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10337            2 :             .await
   10338            2 :             .unwrap();
   10339            2 :         let tline_child = tenant
   10340            2 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10341            2 :             .await
   10342            2 :             .unwrap();
   10343            2 :         {
   10344            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10345            2 :             assert_eq!(
   10346            2 :                 gc_info_parent.retain_lsns,
   10347            2 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10348            2 :             );
   10349            2 :         }
   10350            2 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10351            2 :         tline_child
   10352            2 :             .remote_client
   10353            2 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10354            2 :             .unwrap();
   10355            2 :         tline_child.remote_client.wait_completion().await.unwrap();
   10356            2 :         offload_timeline(&tenant, &tline_child)
   10357            2 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10358            2 :             .await.unwrap();
   10359            2 :         let child_timeline_id = tline_child.timeline_id;
   10360            2 :         Arc::try_unwrap(tline_child).unwrap();
   10361            2 : 
   10362            2 :         {
   10363            2 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10364            2 :             assert_eq!(
   10365            2 :                 gc_info_parent.retain_lsns,
   10366            2 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10367            2 :             );
   10368            2 :         }
   10369            2 : 
   10370            2 :         tenant
   10371            2 :             .get_offloaded_timeline(child_timeline_id)
   10372            2 :             .unwrap()
   10373            2 :             .defuse_for_tenant_drop();
   10374            2 : 
   10375            2 :         Ok(())
   10376            2 :     }
   10377              : }
        

Generated by: LCOV version 2.1-beta