LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 75.8 % 6563 4977
Test Date: 2024-10-22 22:13:45 Functions: 57.0 % 384 219

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

Generated by: LCOV version 2.1-beta