LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 77.7 % 8445 6560
Test Date: 2025-07-16 12:29:03 Functions: 63.0 % 487 307

            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 std::collections::hash_map::Entry;
      16              : use std::collections::{BTreeMap, HashMap, HashSet};
      17              : use std::fmt::{Debug, Display};
      18              : use std::fs::File;
      19              : use std::future::Future;
      20              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
      21              : use std::sync::{Arc, Mutex, Weak};
      22              : use std::time::{Duration, Instant, SystemTime};
      23              : use std::{fmt, fs};
      24              : 
      25              : use anyhow::{Context, bail};
      26              : use arc_swap::ArcSwap;
      27              : use camino::{Utf8Path, Utf8PathBuf};
      28              : use chrono::NaiveDateTime;
      29              : use enumset::EnumSet;
      30              : use futures::StreamExt;
      31              : use futures::stream::FuturesUnordered;
      32              : use itertools::Itertools as _;
      33              : use once_cell::sync::Lazy;
      34              : pub use pageserver_api::models::TenantState;
      35              : use pageserver_api::models::{self, RelSizeMigration};
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use postgres_ffi::PgMajorVersion;
      42              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      43              : use remote_timeline_client::index::GcCompactionState;
      44              : use remote_timeline_client::manifest::{
      45              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      46              : };
      47              : use remote_timeline_client::{
      48              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      49              :     download_tenant_manifest,
      50              : };
      51              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      52              : use storage_broker::BrokerClientChannel;
      53              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      54              : use timeline::import_pgdata::ImportingTimeline;
      55              : use timeline::layer_manager::LayerManagerLockHolder;
      56              : use timeline::offload::{OffloadError, offload_timeline};
      57              : use timeline::{
      58              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      59              : };
      60              : use tokio::io::BufReader;
      61              : use tokio::sync::{Notify, Semaphore, watch};
      62              : use tokio::task::JoinSet;
      63              : use tokio_util::sync::CancellationToken;
      64              : use tracing::*;
      65              : use upload_queue::NotInitialized;
      66              : use utils::circuit_breaker::CircuitBreaker;
      67              : use utils::crashsafe::path_with_suffix_extension;
      68              : use utils::sync::gate::{Gate, GateGuard};
      69              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      70              : use utils::try_rcu::ArcSwapExt;
      71              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      72              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      73              : 
      74              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
      75              : use self::metadata::TimelineMetadata;
      76              : use self::mgr::{GetActiveTenantError, GetTenantError};
      77              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      78              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      79              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      80              : use self::timeline::{
      81              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      82              : };
      83              : use crate::basebackup_cache::BasebackupCache;
      84              : use crate::config::PageServerConf;
      85              : use crate::context;
      86              : use crate::context::RequestContextBuilder;
      87              : use crate::context::{DownloadBehavior, RequestContext};
      88              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      89              : use crate::feature_resolver::{FeatureResolver, TenantFeatureResolver};
      90              : use crate::l0_flush::L0FlushGlobalState;
      91              : use crate::metrics::{
      92              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      93              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_OFFLOADED_TIMELINES,
      94              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC, TIMELINE_STATE_METRIC,
      95              :     remove_tenant_metrics,
      96              : };
      97              : use crate::task_mgr::TaskKind;
      98              : use crate::tenant::config::LocationMode;
      99              : use crate::tenant::gc_result::GcResult;
     100              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     101              : use crate::tenant::remote_timeline_client::{
     102              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
     103              : };
     104              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
     105              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     106              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     107              : use crate::virtual_file::VirtualFile;
     108              : use crate::walingest::WalLagCooldown;
     109              : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
     110              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     111              : 
     112            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     113              : use utils::crashsafe;
     114              : use utils::generation::Generation;
     115              : use utils::id::TimelineId;
     116              : use utils::lsn::{Lsn, RecordLsn};
     117              : 
     118              : pub mod blob_io;
     119              : pub mod block_io;
     120              : pub mod vectored_blob_io;
     121              : 
     122              : pub mod disk_btree;
     123              : pub(crate) mod ephemeral_file;
     124              : pub mod layer_map;
     125              : 
     126              : pub mod metadata;
     127              : pub mod remote_timeline_client;
     128              : pub mod storage_layer;
     129              : 
     130              : pub mod checks;
     131              : pub mod config;
     132              : pub mod mgr;
     133              : pub mod secondary;
     134              : pub mod tasks;
     135              : pub mod upload_queue;
     136              : 
     137              : pub(crate) mod timeline;
     138              : 
     139              : pub mod size;
     140              : 
     141              : mod gc_block;
     142              : mod gc_result;
     143              : pub(crate) mod throttle;
     144              : 
     145              : #[cfg(test)]
     146              : pub mod debug;
     147              : 
     148              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     149              : 
     150              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     151              : // re-export for use in walreceiver
     152              : pub use crate::tenant::timeline::WalReceiverInfo;
     153              : 
     154              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     155              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     156              : 
     157              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     158              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     159              : 
     160              : /// References to shared objects that are passed into each tenant, such
     161              : /// as the shared remote storage client and process initialization state.
     162              : #[derive(Clone)]
     163              : pub struct TenantSharedResources {
     164              :     pub broker_client: storage_broker::BrokerClientChannel,
     165              :     pub remote_storage: GenericRemoteStorage,
     166              :     pub deletion_queue_client: DeletionQueueClient,
     167              :     pub l0_flush_global_state: L0FlushGlobalState,
     168              :     pub basebackup_cache: Arc<BasebackupCache>,
     169              :     pub feature_resolver: FeatureResolver,
     170              : }
     171              : 
     172              : /// A [`TenantShard`] is really an _attached_ tenant.  The configuration
     173              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     174              : /// in this struct.
     175              : #[derive(Clone)]
     176              : pub(super) struct AttachedTenantConf {
     177              :     tenant_conf: pageserver_api::models::TenantConfig,
     178              :     location: AttachedLocationConfig,
     179              :     /// The deadline before which we are blocked from GC so that
     180              :     /// leases have a chance to be renewed.
     181              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     182              : }
     183              : 
     184              : impl AttachedTenantConf {
     185          119 :     fn new(
     186          119 :         conf: &'static PageServerConf,
     187          119 :         tenant_conf: pageserver_api::models::TenantConfig,
     188          119 :         location: AttachedLocationConfig,
     189          119 :     ) -> Self {
     190              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     191              :         //
     192              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     193              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     194              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     195          119 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     196          119 :             Some(
     197          119 :                 tokio::time::Instant::now()
     198          119 :                     + TenantShard::get_lsn_lease_length_impl(conf, &tenant_conf),
     199          119 :             )
     200              :         } else {
     201              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     202              :             // because we don't do GC in these modes.
     203            0 :             None
     204              :         };
     205              : 
     206          119 :         Self {
     207          119 :             tenant_conf,
     208          119 :             location,
     209          119 :             lsn_lease_deadline,
     210          119 :         }
     211          119 :     }
     212              : 
     213          119 :     fn try_from(
     214          119 :         conf: &'static PageServerConf,
     215          119 :         location_conf: LocationConf,
     216          119 :     ) -> anyhow::Result<Self> {
     217          119 :         match &location_conf.mode {
     218          119 :             LocationMode::Attached(attach_conf) => {
     219          119 :                 Ok(Self::new(conf, location_conf.tenant_conf, *attach_conf))
     220              :             }
     221              :             LocationMode::Secondary(_) => {
     222            0 :                 anyhow::bail!(
     223            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     224              :                 )
     225              :             }
     226              :         }
     227          119 :     }
     228              : 
     229          380 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     230          380 :         self.lsn_lease_deadline
     231          380 :             .map(|d| tokio::time::Instant::now() < d)
     232          380 :             .unwrap_or(false)
     233          380 :     }
     234              : }
     235              : struct TimelinePreload {
     236              :     timeline_id: TimelineId,
     237              :     client: RemoteTimelineClient,
     238              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     239              :     previous_heatmap: Option<PreviousHeatmap>,
     240              : }
     241              : 
     242              : pub(crate) struct TenantPreload {
     243              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     244              :     tenant_manifest: Option<TenantManifest>,
     245              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     246              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     247              : }
     248              : 
     249              : /// When we spawn a tenant, there is a special mode for tenant creation that
     250              : /// avoids trying to read anything from remote storage.
     251              : pub(crate) enum SpawnMode {
     252              :     /// Activate as soon as possible
     253              :     Eager,
     254              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     255              :     Lazy,
     256              : }
     257              : 
     258              : ///
     259              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     260              : ///
     261              : pub struct TenantShard {
     262              :     // Global pageserver config parameters
     263              :     pub conf: &'static PageServerConf,
     264              : 
     265              :     /// The value creation timestamp, used to measure activation delay, see:
     266              :     /// <https://github.com/neondatabase/neon/issues/4025>
     267              :     constructed_at: Instant,
     268              : 
     269              :     state: watch::Sender<TenantState>,
     270              : 
     271              :     // Overridden tenant-specific config parameters.
     272              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     273              :     // about parameters that are not set.
     274              :     // This is necessary to allow global config updates.
     275              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     276              : 
     277              :     tenant_shard_id: TenantShardId,
     278              : 
     279              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     280              :     shard_identity: ShardIdentity,
     281              : 
     282              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     283              :     /// Does not change over the lifetime of the [`TenantShard`] object.
     284              :     ///
     285              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     286              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     287              :     generation: Generation,
     288              : 
     289              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     290              : 
     291              :     /// During timeline creation, we first insert the TimelineId to the
     292              :     /// creating map, then `timelines`, then remove it from the creating map.
     293              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     294              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     295              : 
     296              :     /// Possibly offloaded and archived timelines
     297              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     298              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     299              : 
     300              :     /// Tracks the timelines that are currently importing into this tenant shard.
     301              :     ///
     302              :     /// Note that importing timelines are also present in [`Self::timelines_creating`].
     303              :     /// Keep this in mind when ordering lock acquisition.
     304              :     ///
     305              :     /// Lifetime:
     306              :     /// * An imported timeline is created while scanning the bucket on tenant attach
     307              :     ///   if the index part contains an `import_pgdata` entry and said field marks the import
     308              :     ///   as in progress.
     309              :     /// * Imported timelines are removed when the storage controller calls the post timeline
     310              :     ///   import activation endpoint.
     311              :     timelines_importing: std::sync::Mutex<HashMap<TimelineId, Arc<ImportingTimeline>>>,
     312              : 
     313              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     314              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     315              :     ///
     316              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     317              :     ///
     318              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     319              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     320              :     /// `maybe_upload_tenant_manifest`.
     321              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     322              : 
     323              :     // This mutex prevents creation of new timelines during GC.
     324              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     325              :     // `timelines` mutex during all GC iteration
     326              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     327              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     328              :     // timeout...
     329              :     gc_cs: tokio::sync::Mutex<()>,
     330              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     331              : 
     332              :     /// Provides access to timeline data sitting in the remote storage.
     333              :     pub(crate) remote_storage: GenericRemoteStorage,
     334              : 
     335              :     /// Access to global deletion queue for when this tenant wants to schedule a deletion.
     336              :     deletion_queue_client: DeletionQueueClient,
     337              : 
     338              :     /// A channel to send async requests to prepare a basebackup for the basebackup cache.
     339              :     basebackup_cache: Arc<BasebackupCache>,
     340              : 
     341              :     /// Cached logical sizes updated updated on each [`TenantShard::gather_size_inputs`].
     342              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     343              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     344              : 
     345              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     346              : 
     347              :     /// Track repeated failures to compact, so that we can back off.
     348              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     349              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     350              : 
     351              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     352              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     353              : 
     354              :     /// Scheduled gc-compaction tasks.
     355              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     356              : 
     357              :     /// If the tenant is in Activating state, notify this to encourage it
     358              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     359              :     /// background warmup.
     360              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     361              : 
     362              :     /// Time it took for the tenant to activate. Zero if not active yet.
     363              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     364              : 
     365              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     366              :     // Timelines' cancellation token.
     367              :     pub(crate) cancel: CancellationToken,
     368              : 
     369              :     // Users of the TenantShard such as the page service must take this Gate to avoid
     370              :     // trying to use a TenantShard which is shutting down.
     371              :     pub(crate) gate: Gate,
     372              : 
     373              :     /// Throttle applied at the top of [`Timeline::get`].
     374              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] instance share the same [`throttle::Throttle`] instance.
     375              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     376              : 
     377              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     378              : 
     379              :     /// An ongoing timeline detach concurrency limiter.
     380              :     ///
     381              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     382              :     /// to have two running at the same time. A different one can be started if an earlier one
     383              :     /// has failed for whatever reason.
     384              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     385              : 
     386              :     /// `index_part.json` based gc blocking reason tracking.
     387              :     ///
     388              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     389              :     /// proceeding.
     390              :     pub(crate) gc_block: gc_block::GcBlock,
     391              : 
     392              :     l0_flush_global_state: L0FlushGlobalState,
     393              : 
     394              :     pub(crate) feature_resolver: Arc<TenantFeatureResolver>,
     395              : }
     396              : impl std::fmt::Debug for TenantShard {
     397            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     398            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     399            0 :     }
     400              : }
     401              : 
     402              : pub(crate) enum WalRedoManager {
     403              :     Prod(WalredoManagerId, PostgresRedoManager),
     404              :     #[cfg(test)]
     405              :     Test(harness::TestRedoManager),
     406              : }
     407              : 
     408              : #[derive(thiserror::Error, Debug)]
     409              : #[error("pageserver is shutting down")]
     410              : pub(crate) struct GlobalShutDown;
     411              : 
     412              : impl WalRedoManager {
     413            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     414            0 :         let id = WalredoManagerId::next();
     415            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     416            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     417            0 :         match &mut *guard {
     418            0 :             Some(map) => {
     419            0 :                 map.insert(id, Arc::downgrade(&arc));
     420            0 :                 Ok(arc)
     421              :             }
     422            0 :             None => Err(GlobalShutDown),
     423              :         }
     424            0 :     }
     425              : }
     426              : 
     427              : impl Drop for WalRedoManager {
     428            5 :     fn drop(&mut self) {
     429            5 :         match self {
     430            0 :             Self::Prod(id, _) => {
     431            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     432            0 :                 if let Some(map) = &mut *guard {
     433            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     434            0 :                 }
     435              :             }
     436              :             #[cfg(test)]
     437            5 :             Self::Test(_) => {
     438            5 :                 // Not applicable to test redo manager
     439            5 :             }
     440              :         }
     441            5 :     }
     442              : }
     443              : 
     444              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     445              : /// the walredo processes outside of the regular order.
     446              : ///
     447              : /// This is necessary to work around a systemd bug where it freezes if there are
     448              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     449              : #[allow(clippy::type_complexity)]
     450              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     451              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     452            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     453              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     454              : pub(crate) struct WalredoManagerId(u64);
     455              : impl WalredoManagerId {
     456            0 :     pub fn next() -> Self {
     457              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     458            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     459            0 :         if id == 0 {
     460            0 :             panic!(
     461            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     462              :             );
     463            0 :         }
     464            0 :         Self(id)
     465            0 :     }
     466              : }
     467              : 
     468              : #[cfg(test)]
     469              : impl From<harness::TestRedoManager> for WalRedoManager {
     470          119 :     fn from(mgr: harness::TestRedoManager) -> Self {
     471          119 :         Self::Test(mgr)
     472          119 :     }
     473              : }
     474              : 
     475              : impl WalRedoManager {
     476            3 :     pub(crate) async fn shutdown(&self) -> bool {
     477            3 :         match self {
     478            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     479              :             #[cfg(test)]
     480              :             Self::Test(_) => {
     481              :                 // Not applicable to test redo manager
     482            3 :                 true
     483              :             }
     484              :         }
     485            3 :     }
     486              : 
     487            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     488            0 :         match self {
     489            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     490              :             #[cfg(test)]
     491            0 :             Self::Test(_) => {
     492            0 :                 // Not applicable to test redo manager
     493            0 :             }
     494              :         }
     495            0 :     }
     496              : 
     497              :     /// # Cancel-Safety
     498              :     ///
     499              :     /// This method is cancellation-safe.
     500        26774 :     pub async fn request_redo(
     501        26774 :         &self,
     502        26774 :         key: pageserver_api::key::Key,
     503        26774 :         lsn: Lsn,
     504        26774 :         base_img: Option<(Lsn, bytes::Bytes)>,
     505        26774 :         records: Vec<(Lsn, wal_decoder::models::record::NeonWalRecord)>,
     506        26774 :         pg_version: PgMajorVersion,
     507        26774 :         redo_attempt_type: RedoAttemptType,
     508        26774 :     ) -> Result<bytes::Bytes, walredo::Error> {
     509        26774 :         match self {
     510            0 :             Self::Prod(_, mgr) => {
     511            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     512            0 :                     .await
     513              :             }
     514              :             #[cfg(test)]
     515        26774 :             Self::Test(mgr) => {
     516        26774 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     517        26774 :                     .await
     518              :             }
     519              :         }
     520        26774 :     }
     521              : 
     522            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     523            0 :         match self {
     524            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     525              :             #[cfg(test)]
     526            0 :             WalRedoManager::Test(_) => None,
     527              :         }
     528            0 :     }
     529              : }
     530              : 
     531              : /// A very lightweight memory representation of an offloaded timeline.
     532              : ///
     533              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     534              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     535              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     536              : /// more offloaded timelines than we can manage ones that aren't.
     537              : pub struct OffloadedTimeline {
     538              :     pub tenant_shard_id: TenantShardId,
     539              :     pub timeline_id: TimelineId,
     540              :     pub ancestor_timeline_id: Option<TimelineId>,
     541              :     /// Whether to retain the branch lsn at the ancestor or not
     542              :     pub ancestor_retain_lsn: Option<Lsn>,
     543              : 
     544              :     /// When the timeline was archived.
     545              :     ///
     546              :     /// Present for future flattening deliberations.
     547              :     pub archived_at: NaiveDateTime,
     548              : 
     549              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     550              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     551              :     pub delete_progress: TimelineDeleteProgress,
     552              : 
     553              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     554              :     pub deleted_from_ancestor: AtomicBool,
     555              : 
     556              :     _metrics_guard: OffloadedTimelineMetricsGuard,
     557              : }
     558              : 
     559              : /// Increases the offloaded timeline count metric when created, and decreases when dropped.
     560              : struct OffloadedTimelineMetricsGuard;
     561              : 
     562              : impl OffloadedTimelineMetricsGuard {
     563            1 :     fn new() -> Self {
     564            1 :         TIMELINE_STATE_METRIC
     565            1 :             .with_label_values(&["offloaded"])
     566            1 :             .inc();
     567            1 :         Self
     568            1 :     }
     569              : }
     570              : 
     571              : impl Drop for OffloadedTimelineMetricsGuard {
     572            1 :     fn drop(&mut self) {
     573            1 :         TIMELINE_STATE_METRIC
     574            1 :             .with_label_values(&["offloaded"])
     575            1 :             .dec();
     576            1 :     }
     577              : }
     578              : 
     579              : impl OffloadedTimeline {
     580              :     /// Obtains an offloaded timeline from a given timeline object.
     581              :     ///
     582              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     583              :     /// the timeline is not in a stopped state.
     584              :     /// Panics if the timeline is not archived.
     585            1 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     586            1 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     587            1 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     588            1 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     589            1 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     590            1 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     591            1 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     592            1 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     593              :             } else {
     594            0 :                 (None, None)
     595              :             };
     596            1 :         let archived_at = timeline
     597            1 :             .remote_client
     598            1 :             .archived_at_stopped_queue()?
     599            1 :             .expect("must be called on an archived timeline");
     600            1 :         Ok(Self {
     601            1 :             tenant_shard_id: timeline.tenant_shard_id,
     602            1 :             timeline_id: timeline.timeline_id,
     603            1 :             ancestor_timeline_id,
     604            1 :             ancestor_retain_lsn,
     605            1 :             archived_at,
     606            1 : 
     607            1 :             delete_progress: timeline.delete_progress.clone(),
     608            1 :             deleted_from_ancestor: AtomicBool::new(false),
     609            1 : 
     610            1 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     611            1 :         })
     612            1 :     }
     613            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     614              :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     615              :         // by the `initialize_gc_info` function.
     616              :         let OffloadedTimelineManifest {
     617            0 :             timeline_id,
     618            0 :             ancestor_timeline_id,
     619            0 :             ancestor_retain_lsn,
     620            0 :             archived_at,
     621            0 :         } = *manifest;
     622            0 :         Self {
     623            0 :             tenant_shard_id,
     624            0 :             timeline_id,
     625            0 :             ancestor_timeline_id,
     626            0 :             ancestor_retain_lsn,
     627            0 :             archived_at,
     628            0 :             delete_progress: TimelineDeleteProgress::default(),
     629            0 :             deleted_from_ancestor: AtomicBool::new(false),
     630            0 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     631            0 :         }
     632            0 :     }
     633            1 :     fn manifest(&self) -> OffloadedTimelineManifest {
     634              :         let Self {
     635            1 :             timeline_id,
     636            1 :             ancestor_timeline_id,
     637            1 :             ancestor_retain_lsn,
     638            1 :             archived_at,
     639              :             ..
     640            1 :         } = self;
     641            1 :         OffloadedTimelineManifest {
     642            1 :             timeline_id: *timeline_id,
     643            1 :             ancestor_timeline_id: *ancestor_timeline_id,
     644            1 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     645            1 :             archived_at: *archived_at,
     646            1 :         }
     647            1 :     }
     648              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     649            0 :     fn delete_from_ancestor_with_timelines(
     650            0 :         &self,
     651            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     652            0 :     ) {
     653            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     654            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     655              :         {
     656            0 :             if let Some((_, ancestor_timeline)) = timelines
     657            0 :                 .iter()
     658            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     659              :             {
     660            0 :                 let removal_happened = ancestor_timeline
     661            0 :                     .gc_info
     662            0 :                     .write()
     663            0 :                     .unwrap()
     664            0 :                     .remove_child_offloaded(self.timeline_id);
     665            0 :                 if !removal_happened {
     666            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     667            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     668            0 :                 }
     669            0 :             }
     670            0 :         }
     671            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     672            0 :     }
     673              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     674              :     ///
     675              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     676            1 :     fn defuse_for_tenant_drop(&self) {
     677            1 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     678            1 :     }
     679              : }
     680              : 
     681              : impl fmt::Debug for OffloadedTimeline {
     682            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     683            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     684            0 :     }
     685              : }
     686              : 
     687              : impl Drop for OffloadedTimeline {
     688            1 :     fn drop(&mut self) {
     689            1 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     690            0 :             tracing::warn!(
     691            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     692              :                 self.timeline_id
     693              :             );
     694            1 :         }
     695            1 :     }
     696              : }
     697              : 
     698              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     699              : pub enum MaybeOffloaded {
     700              :     Yes,
     701              :     No,
     702              : }
     703              : 
     704              : #[derive(Clone, Debug)]
     705              : pub enum TimelineOrOffloaded {
     706              :     Timeline(Arc<Timeline>),
     707              :     Offloaded(Arc<OffloadedTimeline>),
     708              :     Importing(Arc<ImportingTimeline>),
     709              : }
     710              : 
     711              : impl TimelineOrOffloaded {
     712            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     713            0 :         match self {
     714            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     715            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     716              :             }
     717            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     718            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     719              :             }
     720            0 :             TimelineOrOffloaded::Importing(importing) => {
     721            0 :                 TimelineOrOffloadedArcRef::Importing(importing)
     722              :             }
     723              :         }
     724            0 :     }
     725            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     726            0 :         self.arc_ref().tenant_shard_id()
     727            0 :     }
     728            0 :     pub fn timeline_id(&self) -> TimelineId {
     729            0 :         self.arc_ref().timeline_id()
     730            0 :     }
     731            1 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     732            1 :         match self {
     733            1 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     734            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     735            0 :             TimelineOrOffloaded::Importing(importing) => &importing.delete_progress,
     736              :         }
     737            1 :     }
     738            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     739            0 :         match self {
     740            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     741            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     742            0 :             TimelineOrOffloaded::Importing(importing) => {
     743            0 :                 Some(importing.timeline.remote_client.clone())
     744              :             }
     745              :         }
     746            0 :     }
     747              : }
     748              : 
     749              : pub enum TimelineOrOffloadedArcRef<'a> {
     750              :     Timeline(&'a Arc<Timeline>),
     751              :     Offloaded(&'a Arc<OffloadedTimeline>),
     752              :     Importing(&'a Arc<ImportingTimeline>),
     753              : }
     754              : 
     755              : impl TimelineOrOffloadedArcRef<'_> {
     756            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     757            0 :         match self {
     758            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     759            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     760            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.tenant_shard_id,
     761              :         }
     762            0 :     }
     763            0 :     pub fn timeline_id(&self) -> TimelineId {
     764            0 :         match self {
     765            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     766            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     767            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.timeline_id,
     768              :         }
     769            0 :     }
     770              : }
     771              : 
     772              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     773            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     774            0 :         Self::Timeline(timeline)
     775            0 :     }
     776              : }
     777              : 
     778              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     779            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     780            0 :         Self::Offloaded(timeline)
     781            0 :     }
     782              : }
     783              : 
     784              : impl<'a> From<&'a Arc<ImportingTimeline>> for TimelineOrOffloadedArcRef<'a> {
     785            0 :     fn from(timeline: &'a Arc<ImportingTimeline>) -> Self {
     786            0 :         Self::Importing(timeline)
     787            0 :     }
     788              : }
     789              : 
     790              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     791              : pub enum GetTimelineError {
     792              :     #[error("Timeline is shutting down")]
     793              :     ShuttingDown,
     794              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     795              :     NotActive {
     796              :         tenant_id: TenantShardId,
     797              :         timeline_id: TimelineId,
     798              :         state: TimelineState,
     799              :     },
     800              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     801              :     NotFound {
     802              :         tenant_id: TenantShardId,
     803              :         timeline_id: TimelineId,
     804              :     },
     805              : }
     806              : 
     807              : #[derive(Debug, thiserror::Error)]
     808              : pub enum LoadLocalTimelineError {
     809              :     #[error("FailedToLoad")]
     810              :     Load(#[source] anyhow::Error),
     811              :     #[error("FailedToResumeDeletion")]
     812              :     ResumeDeletion(#[source] anyhow::Error),
     813              : }
     814              : 
     815              : #[derive(thiserror::Error)]
     816              : pub enum DeleteTimelineError {
     817              :     #[error("NotFound")]
     818              :     NotFound,
     819              : 
     820              :     #[error("HasChildren")]
     821              :     HasChildren(Vec<TimelineId>),
     822              : 
     823              :     #[error("Timeline deletion is already in progress")]
     824              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     825              : 
     826              :     #[error("Cancelled")]
     827              :     Cancelled,
     828              : 
     829              :     #[error(transparent)]
     830              :     Other(#[from] anyhow::Error),
     831              : }
     832              : 
     833              : impl Debug for DeleteTimelineError {
     834            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     835            0 :         match self {
     836            0 :             Self::NotFound => write!(f, "NotFound"),
     837            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     838            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     839            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     840            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     841              :         }
     842            0 :     }
     843              : }
     844              : 
     845              : #[derive(thiserror::Error)]
     846              : pub enum TimelineArchivalError {
     847              :     #[error("NotFound")]
     848              :     NotFound,
     849              : 
     850              :     #[error("Timeout")]
     851              :     Timeout,
     852              : 
     853              :     #[error("Cancelled")]
     854              :     Cancelled,
     855              : 
     856              :     #[error("ancestor is archived: {}", .0)]
     857              :     HasArchivedParent(TimelineId),
     858              : 
     859              :     #[error("HasUnarchivedChildren")]
     860              :     HasUnarchivedChildren(Vec<TimelineId>),
     861              : 
     862              :     #[error("Timeline archival is already in progress")]
     863              :     AlreadyInProgress,
     864              : 
     865              :     #[error(transparent)]
     866              :     Other(anyhow::Error),
     867              : }
     868              : 
     869              : #[derive(thiserror::Error, Debug)]
     870              : pub(crate) enum TenantManifestError {
     871              :     #[error("Remote storage error: {0}")]
     872              :     RemoteStorage(anyhow::Error),
     873              : 
     874              :     #[error("Cancelled")]
     875              :     Cancelled,
     876              : }
     877              : 
     878              : impl From<TenantManifestError> for TimelineArchivalError {
     879            0 :     fn from(e: TenantManifestError) -> Self {
     880            0 :         match e {
     881            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     882            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     883              :         }
     884            0 :     }
     885              : }
     886              : 
     887              : impl Debug for TimelineArchivalError {
     888            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     889            0 :         match self {
     890            0 :             Self::NotFound => write!(f, "NotFound"),
     891            0 :             Self::Timeout => write!(f, "Timeout"),
     892            0 :             Self::Cancelled => write!(f, "Cancelled"),
     893            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     894            0 :             Self::HasUnarchivedChildren(c) => {
     895            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     896              :             }
     897            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     898            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     899              :         }
     900            0 :     }
     901              : }
     902              : 
     903              : pub enum SetStoppingError {
     904              :     AlreadyStopping(completion::Barrier),
     905              :     Broken,
     906              : }
     907              : 
     908              : impl Debug for SetStoppingError {
     909            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     910            0 :         match self {
     911            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     912            0 :             Self::Broken => write!(f, "Broken"),
     913              :         }
     914            0 :     }
     915              : }
     916              : 
     917              : #[derive(thiserror::Error, Debug)]
     918              : pub(crate) enum FinalizeTimelineImportError {
     919              :     #[error("Import task not done yet")]
     920              :     ImportTaskStillRunning,
     921              :     #[error("Shutting down")]
     922              :     ShuttingDown,
     923              : }
     924              : 
     925              : /// Arguments to [`TenantShard::create_timeline`].
     926              : ///
     927              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     928              : /// is `None`, the result of the timeline create call is not deterministic.
     929              : ///
     930              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     931              : #[derive(Debug)]
     932              : pub(crate) enum CreateTimelineParams {
     933              :     Bootstrap(CreateTimelineParamsBootstrap),
     934              :     Branch(CreateTimelineParamsBranch),
     935              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     936              : }
     937              : 
     938              : #[derive(Debug)]
     939              : pub(crate) struct CreateTimelineParamsBootstrap {
     940              :     pub(crate) new_timeline_id: TimelineId,
     941              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     942              :     pub(crate) pg_version: PgMajorVersion,
     943              : }
     944              : 
     945              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     946              : #[derive(Debug)]
     947              : pub(crate) struct CreateTimelineParamsBranch {
     948              :     pub(crate) new_timeline_id: TimelineId,
     949              :     pub(crate) ancestor_timeline_id: TimelineId,
     950              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     951              : }
     952              : 
     953              : #[derive(Debug)]
     954              : pub(crate) struct CreateTimelineParamsImportPgdata {
     955              :     pub(crate) new_timeline_id: TimelineId,
     956              :     pub(crate) location: import_pgdata::index_part_format::Location,
     957              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     958              : }
     959              : 
     960              : /// What is used to determine idempotency of a [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::start_creating_timeline`].
     961              : ///
     962              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     963              : ///
     964              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     965              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     966              : ///
     967              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     968              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     969              : ///
     970              : /// Notes:
     971              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     972              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     973              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     974              : ///
     975              : #[derive(Debug, Clone, PartialEq, Eq)]
     976              : pub(crate) enum CreateTimelineIdempotency {
     977              :     /// NB: special treatment, see comment in [`Self`].
     978              :     FailWithConflict,
     979              :     Bootstrap {
     980              :         pg_version: PgMajorVersion,
     981              :     },
     982              :     /// NB: branches always have the same `pg_version` as their ancestor.
     983              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     984              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     985              :     /// determining the child branch pg_version.
     986              :     Branch {
     987              :         ancestor_timeline_id: TimelineId,
     988              :         ancestor_start_lsn: Lsn,
     989              :     },
     990              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     991              : }
     992              : 
     993              : #[derive(Debug, Clone, PartialEq, Eq)]
     994              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     995              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     996              : }
     997              : 
     998              : /// What is returned by [`TenantShard::start_creating_timeline`].
     999              : #[must_use]
    1000              : enum StartCreatingTimelineResult {
    1001              :     CreateGuard(TimelineCreateGuard),
    1002              :     Idempotent(Arc<Timeline>),
    1003              : }
    1004              : 
    1005              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1006              : enum TimelineInitAndSyncResult {
    1007              :     ReadyToActivate,
    1008              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
    1009              : }
    1010              : 
    1011              : #[must_use]
    1012              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
    1013              :     timeline: Arc<Timeline>,
    1014              :     import_pgdata: import_pgdata::index_part_format::Root,
    1015              :     guard: TimelineCreateGuard,
    1016              : }
    1017              : 
    1018              : /// What is returned by [`TenantShard::create_timeline`].
    1019              : enum CreateTimelineResult {
    1020              :     Created(Arc<Timeline>),
    1021              :     Idempotent(Arc<Timeline>),
    1022              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
    1023              :     /// we return this result, nor will this concrete object ever be added there.
    1024              :     /// Cf method comment on [`TenantShard::create_timeline_import_pgdata`].
    1025              :     ImportSpawned(Arc<Timeline>),
    1026              : }
    1027              : 
    1028              : impl CreateTimelineResult {
    1029            0 :     fn discriminant(&self) -> &'static str {
    1030            0 :         match self {
    1031            0 :             Self::Created(_) => "Created",
    1032            0 :             Self::Idempotent(_) => "Idempotent",
    1033            0 :             Self::ImportSpawned(_) => "ImportSpawned",
    1034              :         }
    1035            0 :     }
    1036            0 :     fn timeline(&self) -> &Arc<Timeline> {
    1037            0 :         match self {
    1038            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1039              :         }
    1040            0 :     }
    1041              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
    1042              :     #[cfg(test)]
    1043          118 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
    1044          118 :         match self {
    1045          118 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1046              :         }
    1047          118 :     }
    1048              : }
    1049              : 
    1050              : #[derive(thiserror::Error, Debug)]
    1051              : pub enum CreateTimelineError {
    1052              :     #[error("creation of timeline with the given ID is in progress")]
    1053              :     AlreadyCreating,
    1054              :     #[error("timeline already exists with different parameters")]
    1055              :     Conflict,
    1056              :     #[error(transparent)]
    1057              :     AncestorLsn(anyhow::Error),
    1058              :     #[error("ancestor timeline is not active")]
    1059              :     AncestorNotActive,
    1060              :     #[error("ancestor timeline is archived")]
    1061              :     AncestorArchived,
    1062              :     #[error("tenant shutting down")]
    1063              :     ShuttingDown,
    1064              :     #[error(transparent)]
    1065              :     Other(#[from] anyhow::Error),
    1066              : }
    1067              : 
    1068              : #[derive(thiserror::Error, Debug)]
    1069              : pub enum InitdbError {
    1070              :     #[error("Operation was cancelled")]
    1071              :     Cancelled,
    1072              :     #[error(transparent)]
    1073              :     Other(anyhow::Error),
    1074              :     #[error(transparent)]
    1075              :     Inner(postgres_initdb::Error),
    1076              : }
    1077              : 
    1078              : enum CreateTimelineCause {
    1079              :     Load,
    1080              :     Delete,
    1081              : }
    1082              : 
    1083              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1084              : enum LoadTimelineCause {
    1085              :     Attach,
    1086              :     Unoffload,
    1087              : }
    1088              : 
    1089              : #[derive(thiserror::Error, Debug)]
    1090              : pub(crate) enum GcError {
    1091              :     // The tenant is shutting down
    1092              :     #[error("tenant shutting down")]
    1093              :     TenantCancelled,
    1094              : 
    1095              :     // The tenant is shutting down
    1096              :     #[error("timeline shutting down")]
    1097              :     TimelineCancelled,
    1098              : 
    1099              :     // The tenant is in a state inelegible to run GC
    1100              :     #[error("not active")]
    1101              :     NotActive,
    1102              : 
    1103              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1104              :     #[error("not active")]
    1105              :     BadLsn { why: String },
    1106              : 
    1107              :     // A remote storage error while scheduling updates after compaction
    1108              :     #[error(transparent)]
    1109              :     Remote(anyhow::Error),
    1110              : 
    1111              :     // An error reading while calculating GC cutoffs
    1112              :     #[error(transparent)]
    1113              :     GcCutoffs(PageReconstructError),
    1114              : 
    1115              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1116              :     #[error("timeline not found")]
    1117              :     TimelineNotFound,
    1118              : }
    1119              : 
    1120              : impl From<PageReconstructError> for GcError {
    1121            0 :     fn from(value: PageReconstructError) -> Self {
    1122            0 :         match value {
    1123            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1124            0 :             other => Self::GcCutoffs(other),
    1125              :         }
    1126            0 :     }
    1127              : }
    1128              : 
    1129              : impl From<NotInitialized> for GcError {
    1130            0 :     fn from(value: NotInitialized) -> Self {
    1131            0 :         match value {
    1132            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1133            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1134              :         }
    1135            0 :     }
    1136              : }
    1137              : 
    1138              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1139            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1140            0 :         GcError::TimelineCancelled
    1141            0 :     }
    1142              : }
    1143              : 
    1144              : #[derive(thiserror::Error, Debug)]
    1145              : pub(crate) enum LoadConfigError {
    1146              :     #[error("TOML deserialization error: '{0}'")]
    1147              :     DeserializeToml(#[from] toml_edit::de::Error),
    1148              : 
    1149              :     #[error("Config not found at {0}")]
    1150              :     NotFound(Utf8PathBuf),
    1151              : }
    1152              : 
    1153              : impl TenantShard {
    1154              :     /// Yet another helper for timeline initialization.
    1155              :     ///
    1156              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1157              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1158              :     /// - Downloads remote index file and adds remote files to the layer map
    1159              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1160              :     ///
    1161              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1162              :     /// it is marked as Active.
    1163              :     #[allow(clippy::too_many_arguments)]
    1164            3 :     async fn timeline_init_and_sync(
    1165            3 :         self: &Arc<Self>,
    1166            3 :         timeline_id: TimelineId,
    1167            3 :         resources: TimelineResources,
    1168            3 :         index_part: IndexPart,
    1169            3 :         metadata: TimelineMetadata,
    1170            3 :         previous_heatmap: Option<PreviousHeatmap>,
    1171            3 :         ancestor: Option<Arc<Timeline>>,
    1172            3 :         cause: LoadTimelineCause,
    1173            3 :         ctx: &RequestContext,
    1174            3 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1175            3 :         let tenant_id = self.tenant_shard_id;
    1176              : 
    1177            3 :         let import_pgdata = index_part.import_pgdata.clone();
    1178            3 :         let idempotency = match &import_pgdata {
    1179            0 :             Some(import_pgdata) => {
    1180            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1181            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1182            0 :                 })
    1183              :             }
    1184              :             None => {
    1185            3 :                 if metadata.ancestor_timeline().is_none() {
    1186            2 :                     CreateTimelineIdempotency::Bootstrap {
    1187            2 :                         pg_version: metadata.pg_version(),
    1188            2 :                     }
    1189              :                 } else {
    1190            1 :                     CreateTimelineIdempotency::Branch {
    1191            1 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1192            1 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1193            1 :                     }
    1194              :                 }
    1195              :             }
    1196              :         };
    1197              : 
    1198            3 :         let (timeline, _timeline_ctx) = self.create_timeline_struct(
    1199            3 :             timeline_id,
    1200            3 :             &metadata,
    1201            3 :             previous_heatmap,
    1202            3 :             ancestor.clone(),
    1203            3 :             resources,
    1204            3 :             CreateTimelineCause::Load,
    1205            3 :             idempotency.clone(),
    1206            3 :             index_part.gc_compaction.clone(),
    1207            3 :             index_part.rel_size_migration.clone(),
    1208            3 :             ctx,
    1209            3 :         )?;
    1210            3 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1211              : 
    1212            3 :         if !disk_consistent_lsn.is_valid() {
    1213              :             // As opposed to normal timelines which get initialised with a disk consitent LSN
    1214              :             // via initdb, imported timelines start from 0. If the import task stops before
    1215              :             // it advances disk consitent LSN, allow it to resume.
    1216            0 :             let in_progress_import = import_pgdata
    1217            0 :                 .as_ref()
    1218            0 :                 .map(|import| !import.is_done())
    1219            0 :                 .unwrap_or(false);
    1220            0 :             if !in_progress_import {
    1221            0 :                 anyhow::bail!("Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn");
    1222            0 :             }
    1223            3 :         }
    1224              : 
    1225            3 :         assert_eq!(
    1226              :             disk_consistent_lsn,
    1227            3 :             metadata.disk_consistent_lsn(),
    1228            0 :             "these are used interchangeably"
    1229              :         );
    1230              : 
    1231            3 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1232              : 
    1233            3 :         timeline
    1234            3 :             .load_layer_map(disk_consistent_lsn, index_part)
    1235            3 :             .await
    1236            3 :             .with_context(|| {
    1237            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1238            0 :             })?;
    1239              : 
    1240              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1241              :         // to the archival operation. To allow warming this timeline up, generate
    1242              :         // a previous heatmap which contains all visible layers in the layer map.
    1243              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1244              :         // for the timeline.
    1245            3 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1246            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1247            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1248            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1249              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1250              :                 // If the current branch point greater than the previous one use the the heatmap
    1251              :                 // we just generated - it should include more layers.
    1252            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1253            0 :                     tline
    1254            0 :                         .previous_heatmap
    1255            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1256            0 :                 } else {
    1257            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1258              :                 }
    1259              : 
    1260            0 :                 match tline.ancestor_timeline() {
    1261            0 :                     Some(ancestor) => {
    1262            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1263              :                             // Ancestor timeline is shutting down.
    1264            0 :                             break;
    1265            0 :                         }
    1266              : 
    1267            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1268              :                     }
    1269            0 :                     None => {
    1270            0 :                         tline_ending_at = None;
    1271            0 :                     }
    1272              :                 }
    1273              :             }
    1274            3 :         }
    1275              : 
    1276            0 :         match import_pgdata {
    1277            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1278            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1279            0 :                 if !guard.insert(timeline_id) {
    1280              :                     // We should never try and load the same timeline twice during startup
    1281            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1282            0 :                 }
    1283            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1284            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1285            0 :                     owning_tenant: self.clone(),
    1286            0 :                     timeline_id,
    1287            0 :                     idempotency,
    1288              :                     // The users of this specific return value don't need the timline_path in there.
    1289            0 :                     timeline_path: timeline
    1290            0 :                         .conf
    1291            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1292              :                 };
    1293            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1294            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1295            0 :                         timeline,
    1296            0 :                         import_pgdata,
    1297            0 :                         guard: timeline_create_guard,
    1298            0 :                     },
    1299            0 :                 ))
    1300              :             }
    1301              :             Some(_) | None => {
    1302              :                 {
    1303            3 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1304            3 :                     match timelines_accessor.entry(timeline_id) {
    1305              :                         // We should never try and load the same timeline twice during startup
    1306              :                         Entry::Occupied(_) => {
    1307            0 :                             unreachable!(
    1308              :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1309              :                             );
    1310              :                         }
    1311            3 :                         Entry::Vacant(v) => {
    1312            3 :                             v.insert(Arc::clone(&timeline));
    1313            3 :                             timeline.maybe_spawn_flush_loop();
    1314            3 :                         }
    1315              :                     }
    1316              :                 }
    1317              : 
    1318            3 :                 if disk_consistent_lsn.is_valid() {
    1319              :                     // Sanity check: a timeline should have some content.
    1320              :                     // Exception: importing timelines might not yet have any
    1321            3 :                     anyhow::ensure!(
    1322            3 :                         ancestor.is_some()
    1323            2 :                             || timeline
    1324            2 :                                 .layers
    1325            2 :                                 .read(LayerManagerLockHolder::LoadLayerMap)
    1326            2 :                                 .await
    1327            2 :                                 .layer_map()
    1328            2 :                                 .expect(
    1329            2 :                                     "currently loading, layer manager cannot be shutdown already"
    1330              :                                 )
    1331            2 :                                 .iter_historic_layers()
    1332            2 :                                 .next()
    1333            2 :                                 .is_some(),
    1334            0 :                         "Timeline has no ancestor and no layer files"
    1335              :                     );
    1336            0 :                 }
    1337              : 
    1338            3 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate)
    1339              :             }
    1340              :         }
    1341            3 :     }
    1342              : 
    1343              :     /// Attach a tenant that's available in cloud storage.
    1344              :     ///
    1345              :     /// This returns quickly, after just creating the in-memory object
    1346              :     /// Tenant struct and launching a background task to download
    1347              :     /// the remote index files.  On return, the tenant is most likely still in
    1348              :     /// Attaching state, and it will become Active once the background task
    1349              :     /// finishes. You can use wait_until_active() to wait for the task to
    1350              :     /// complete.
    1351              :     ///
    1352              :     #[allow(clippy::too_many_arguments)]
    1353            0 :     pub(crate) fn spawn(
    1354            0 :         conf: &'static PageServerConf,
    1355            0 :         tenant_shard_id: TenantShardId,
    1356            0 :         resources: TenantSharedResources,
    1357            0 :         attached_conf: AttachedTenantConf,
    1358            0 :         shard_identity: ShardIdentity,
    1359            0 :         init_order: Option<InitializationOrder>,
    1360            0 :         mode: SpawnMode,
    1361            0 :         ctx: &RequestContext,
    1362            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1363            0 :         let wal_redo_manager =
    1364            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1365              : 
    1366              :         let TenantSharedResources {
    1367            0 :             broker_client,
    1368            0 :             remote_storage,
    1369            0 :             deletion_queue_client,
    1370            0 :             l0_flush_global_state,
    1371            0 :             basebackup_cache,
    1372            0 :             feature_resolver,
    1373            0 :         } = resources;
    1374              : 
    1375            0 :         let attach_mode = attached_conf.location.attach_mode;
    1376            0 :         let generation = attached_conf.location.generation;
    1377              : 
    1378            0 :         let tenant = Arc::new(TenantShard::new(
    1379            0 :             TenantState::Attaching,
    1380            0 :             conf,
    1381            0 :             attached_conf,
    1382            0 :             shard_identity,
    1383            0 :             Some(wal_redo_manager),
    1384            0 :             tenant_shard_id,
    1385            0 :             remote_storage.clone(),
    1386            0 :             deletion_queue_client,
    1387            0 :             l0_flush_global_state,
    1388            0 :             basebackup_cache,
    1389            0 :             feature_resolver,
    1390              :         ));
    1391              : 
    1392              :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1393              :         // we shut down while attaching.
    1394            0 :         let attach_gate_guard = tenant
    1395            0 :             .gate
    1396            0 :             .enter()
    1397            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1398              : 
    1399              :         // Do all the hard work in the background
    1400            0 :         let tenant_clone = Arc::clone(&tenant);
    1401            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1402            0 :         task_mgr::spawn(
    1403            0 :             &tokio::runtime::Handle::current(),
    1404            0 :             TaskKind::Attach,
    1405            0 :             tenant_shard_id,
    1406            0 :             None,
    1407            0 :             "attach tenant",
    1408            0 :             async move {
    1409              : 
    1410            0 :                 info!(
    1411              :                     ?attach_mode,
    1412            0 :                     "Attaching tenant"
    1413              :                 );
    1414              : 
    1415            0 :                 let _gate_guard = attach_gate_guard;
    1416              : 
    1417              :                 // Is this tenant being spawned as part of process startup?
    1418            0 :                 let starting_up = init_order.is_some();
    1419            0 :                 scopeguard::defer! {
    1420              :                     if starting_up {
    1421              :                         TENANT.startup_complete.inc();
    1422              :                     }
    1423              :                 }
    1424              : 
    1425            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1426            0 :                     t.state.send_modify(|state| match state {
    1427              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1428              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1429              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1430              :                         // logs don't show this happening in production, remove the Stopping cases.
    1431            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1432            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1433              :                         }
    1434              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1435            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1436            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1437              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1438            0 :                             *state = TenantState::Stopping { progress: None };
    1439              :                         }
    1440              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1441              :                         // Stopping. Retain its progress.
    1442              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1443            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1444            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1445            0 :                             info!("attach cancelled, already Stopping: {err}");
    1446              :                         }
    1447              :                         // Mark the tenant as broken.
    1448              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1449            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1450            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1451              :                         }
    1452              :                         // The attach task owns the tenant state until activated.
    1453            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1454            0 :                     });
    1455            0 :                 }
    1456              : 
    1457              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1458            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1459            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1460            0 :                     return Ok(());
    1461            0 :                 }
    1462              : 
    1463            0 :                 let mut init_order = init_order;
    1464              :                 // take the completion because initial tenant loading will complete when all of
    1465              :                 // these tasks complete.
    1466            0 :                 let _completion = init_order
    1467            0 :                     .as_mut()
    1468            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1469            0 :                 let remote_load_completion = init_order
    1470            0 :                     .as_mut()
    1471            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1472              : 
    1473              :                 enum AttachType<'a> {
    1474              :                     /// We are attaching this tenant lazily in the background.
    1475              :                     Warmup {
    1476              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1477              :                         during_startup: bool
    1478              :                     },
    1479              :                     /// We are attaching this tenant as soon as we can, because for example an
    1480              :                     /// endpoint tried to access it.
    1481              :                     OnDemand,
    1482              :                     /// During normal operations after startup, we are attaching a tenant, and
    1483              :                     /// eager attach was requested.
    1484              :                     Normal,
    1485              :                 }
    1486              : 
    1487            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1488              :                     // Before doing any I/O, wait for at least one of:
    1489              :                     // - A client attempting to access to this tenant (on-demand loading)
    1490              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1491              : 
    1492            0 :                     tokio::select!(
    1493            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1494            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1495            0 :                             tracing::info!("Activating tenant (on-demand)");
    1496            0 :                             AttachType::OnDemand
    1497              :                         },
    1498            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1499            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1500            0 :                             tracing::info!("Activating tenant (warmup)");
    1501            0 :                             AttachType::Warmup {
    1502            0 :                                 _permit,
    1503            0 :                                 during_startup: init_order.is_some()
    1504            0 :                             }
    1505              :                         }
    1506            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1507              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1508              :                             // stayed in Activating for such a long time that shutdown found it in
    1509              :                             // that state.
    1510            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1511              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1512            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1513            0 :                             return Ok(());
    1514              :                         },
    1515              :                     )
    1516              :                 } else {
    1517              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1518              :                     // concurrent_tenant_warmup queue
    1519            0 :                     AttachType::Normal
    1520              :                 };
    1521              : 
    1522            0 :                 let preload = match &mode {
    1523              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1524            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1525            0 :                         let res = tenant_clone
    1526            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1527            0 :                             .await;
    1528            0 :                         match res {
    1529            0 :                             Ok(p) => Some(p),
    1530            0 :                             Err(e) => {
    1531            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1532            0 :                                 return Ok(());
    1533              :                             }
    1534              :                         }
    1535              :                     }
    1536              : 
    1537              :                 };
    1538              : 
    1539              :                 // Remote preload is complete.
    1540            0 :                 drop(remote_load_completion);
    1541              : 
    1542              : 
    1543              :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1544            0 :                 let attach_start = std::time::Instant::now();
    1545            0 :                 let attached = {
    1546            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1547            0 :                     tenant_clone.attach(preload, &ctx).await
    1548              :                 };
    1549            0 :                 let attach_duration = attach_start.elapsed();
    1550            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1551              : 
    1552            0 :                 match attached {
    1553              :                     Ok(()) => {
    1554            0 :                         info!("attach finished, activating");
    1555            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1556              :                     }
    1557            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1558              :                 }
    1559              : 
    1560              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1561              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1562              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1563              :                 //
    1564              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1565              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1566              :                 // then warmup will wait for that before proceeding to the next tenant.
    1567            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1568            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1569            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1570            0 :                     while futs.next().await.is_some() {}
    1571            0 :                     tracing::info!("Warm-up complete");
    1572            0 :                 }
    1573              : 
    1574            0 :                 Ok(())
    1575            0 :             }
    1576            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1577              :         );
    1578            0 :         Ok(tenant)
    1579            0 :     }
    1580              : 
    1581              :     #[instrument(skip_all)]
    1582              :     pub(crate) async fn preload(
    1583              :         self: &Arc<Self>,
    1584              :         remote_storage: &GenericRemoteStorage,
    1585              :         cancel: CancellationToken,
    1586              :     ) -> anyhow::Result<TenantPreload> {
    1587              :         span::debug_assert_current_span_has_tenant_id();
    1588              :         // Get list of remote timelines
    1589              :         // download index files for every tenant timeline
    1590              :         info!("listing remote timelines");
    1591              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1592              :             remote_storage,
    1593              :             self.tenant_shard_id,
    1594              :             cancel.clone(),
    1595              :         )
    1596              :         .await?;
    1597              : 
    1598              :         let tenant_manifest = match download_tenant_manifest(
    1599              :             remote_storage,
    1600              :             &self.tenant_shard_id,
    1601              :             self.generation,
    1602              :             &cancel,
    1603              :         )
    1604              :         .await
    1605              :         {
    1606              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1607              :             Err(DownloadError::NotFound) => None,
    1608              :             Err(err) => return Err(err.into()),
    1609              :         };
    1610              : 
    1611              :         info!(
    1612              :             "found {} timelines ({} offloaded timelines)",
    1613              :             remote_timeline_ids.len(),
    1614              :             tenant_manifest
    1615              :                 .as_ref()
    1616            3 :                 .map(|m| m.offloaded_timelines.len())
    1617              :                 .unwrap_or(0)
    1618              :         );
    1619              : 
    1620              :         for k in other_keys {
    1621              :             warn!("Unexpected non timeline key {k}");
    1622              :         }
    1623              : 
    1624              :         // Avoid downloading IndexPart of offloaded timelines.
    1625              :         let mut offloaded_with_prefix = HashSet::new();
    1626              :         if let Some(tenant_manifest) = &tenant_manifest {
    1627              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1628              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1629              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1630              :                 } else {
    1631              :                     // We'll take care later of timelines in the manifest without a prefix
    1632              :                 }
    1633              :             }
    1634              :         }
    1635              : 
    1636              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1637              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1638              :         // will kick the secondary in any case and cause a download.
    1639              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1640              : 
    1641              :         let timelines = self
    1642              :             .load_timelines_metadata(
    1643              :                 remote_timeline_ids,
    1644              :                 remote_storage,
    1645              :                 maybe_heatmap_at,
    1646              :                 cancel,
    1647              :             )
    1648              :             .await?;
    1649              : 
    1650              :         Ok(TenantPreload {
    1651              :             tenant_manifest,
    1652              :             timelines: timelines
    1653              :                 .into_iter()
    1654            3 :                 .map(|(id, tl)| (id, Some(tl)))
    1655            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1656              :                 .collect(),
    1657              :         })
    1658              :     }
    1659              : 
    1660          119 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1661          119 :         if !self.conf.load_previous_heatmap {
    1662            0 :             return None;
    1663          119 :         }
    1664              : 
    1665          119 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1666          119 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1667            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1668            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1669            0 :                 Err(err) => {
    1670            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1671            0 :                     None
    1672              :                 }
    1673              :             },
    1674          119 :             Err(err) => match err.kind() {
    1675          119 :                 std::io::ErrorKind::NotFound => None,
    1676              :                 _ => {
    1677            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1678            0 :                     None
    1679              :                 }
    1680              :             },
    1681              :         }
    1682          119 :     }
    1683              : 
    1684              :     ///
    1685              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1686              :     ///
    1687              :     /// No background tasks are started as part of this routine.
    1688              :     ///
    1689          119 :     async fn attach(
    1690          119 :         self: &Arc<TenantShard>,
    1691          119 :         preload: Option<TenantPreload>,
    1692          119 :         ctx: &RequestContext,
    1693          119 :     ) -> anyhow::Result<()> {
    1694          119 :         span::debug_assert_current_span_has_tenant_id();
    1695              : 
    1696          119 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1697              : 
    1698          119 :         let Some(preload) = preload else {
    1699            0 :             anyhow::bail!(
    1700            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1701              :             );
    1702              :         };
    1703              : 
    1704          119 :         let mut offloaded_timeline_ids = HashSet::new();
    1705          119 :         let mut offloaded_timelines_list = Vec::new();
    1706          119 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1707            3 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1708            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1709            0 :                 let offloaded_timeline =
    1710            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1711            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1712            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1713            0 :             }
    1714          116 :         }
    1715              :         // Complete deletions for offloaded timeline id's from manifest.
    1716              :         // The manifest will be uploaded later in this function.
    1717          119 :         offloaded_timelines_list
    1718          119 :             .retain(|(offloaded_id, offloaded)| {
    1719              :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1720              :                 // If there is dangling references in another location, they need to be cleaned up.
    1721            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1722            0 :                 if delete {
    1723            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1724            0 :                     offloaded.defuse_for_tenant_drop();
    1725            0 :                 }
    1726            0 :                 !delete
    1727            0 :         });
    1728              : 
    1729          119 :         let mut timelines_to_resume_deletions = vec![];
    1730              : 
    1731          119 :         let mut remote_index_and_client = HashMap::new();
    1732          119 :         let mut timeline_ancestors = HashMap::new();
    1733          119 :         let mut existent_timelines = HashSet::new();
    1734          122 :         for (timeline_id, preload) in preload.timelines {
    1735            3 :             let Some(preload) = preload else { continue };
    1736              :             // This is an invariant of the `preload` function's API
    1737            3 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1738            3 :             let index_part = match preload.index_part {
    1739            3 :                 Ok(i) => {
    1740            3 :                     debug!("remote index part exists for timeline {timeline_id}");
    1741              :                     // We found index_part on the remote, this is the standard case.
    1742            3 :                     existent_timelines.insert(timeline_id);
    1743            3 :                     i
    1744              :                 }
    1745              :                 Err(DownloadError::NotFound) => {
    1746              :                     // There is no index_part on the remote. We only get here
    1747              :                     // if there is some prefix for the timeline in the remote storage.
    1748              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1749              :                     // remnant from a prior incomplete creation or deletion attempt.
    1750              :                     // Delete the local directory as the deciding criterion for a
    1751              :                     // timeline's existence is presence of index_part.
    1752            0 :                     info!(%timeline_id, "index_part not found on remote");
    1753            0 :                     continue;
    1754              :                 }
    1755            0 :                 Err(DownloadError::Fatal(why)) => {
    1756              :                     // If, while loading one remote timeline, we saw an indication that our generation
    1757              :                     // number is likely invalid, then we should not load the whole tenant.
    1758            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1759            0 :                     anyhow::bail!(why.to_string());
    1760              :                 }
    1761            0 :                 Err(e) => {
    1762              :                     // Some (possibly ephemeral) error happened during index_part download.
    1763              :                     // Pretend the timeline exists to not delete the timeline directory,
    1764              :                     // as it might be a temporary issue and we don't want to re-download
    1765              :                     // everything after it resolves.
    1766            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1767              : 
    1768            0 :                     existent_timelines.insert(timeline_id);
    1769            0 :                     continue;
    1770              :                 }
    1771              :             };
    1772            3 :             match index_part {
    1773            3 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1774            3 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1775            3 :                     remote_index_and_client.insert(
    1776            3 :                         timeline_id,
    1777            3 :                         (index_part, preload.client, preload.previous_heatmap),
    1778            3 :                     );
    1779            3 :                 }
    1780            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1781            0 :                     info!(
    1782            0 :                         "timeline {} is deleted, picking to resume deletion",
    1783              :                         timeline_id
    1784              :                     );
    1785            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1786              :                 }
    1787              :             }
    1788              :         }
    1789              : 
    1790          119 :         let mut gc_blocks = HashMap::new();
    1791              : 
    1792              :         // For every timeline, download the metadata file, scan the local directory,
    1793              :         // and build a layer map that contains an entry for each remote and local
    1794              :         // layer file.
    1795          119 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1796          122 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1797            3 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1798            3 :                 .remove(&timeline_id)
    1799            3 :                 .expect("just put it in above");
    1800              : 
    1801            3 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1802              :                 // could just filter these away, but it helps while testing
    1803            0 :                 anyhow::ensure!(
    1804            0 :                     !blocking.reasons.is_empty(),
    1805            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1806              :                 );
    1807            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1808            0 :                 assert!(prev.is_none());
    1809            3 :             }
    1810              : 
    1811              :             // TODO again handle early failure
    1812            3 :             let effect = self
    1813            3 :                 .load_remote_timeline(
    1814            3 :                     timeline_id,
    1815            3 :                     index_part,
    1816            3 :                     remote_metadata,
    1817            3 :                     previous_heatmap,
    1818            3 :                     self.get_timeline_resources_for(remote_client),
    1819            3 :                     LoadTimelineCause::Attach,
    1820            3 :                     ctx,
    1821            3 :                 )
    1822            3 :                 .await
    1823            3 :                 .with_context(|| {
    1824            0 :                     format!(
    1825            0 :                         "failed to load remote timeline {} for tenant {}",
    1826            0 :                         timeline_id, self.tenant_shard_id
    1827              :                     )
    1828            0 :                 })?;
    1829              : 
    1830            3 :             match effect {
    1831            3 :                 TimelineInitAndSyncResult::ReadyToActivate => {
    1832            3 :                     // activation happens later, on Tenant::activate
    1833            3 :                 }
    1834              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1835              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1836            0 :                         timeline,
    1837            0 :                         import_pgdata,
    1838            0 :                         guard,
    1839              :                     },
    1840              :                 ) => {
    1841            0 :                     let timeline_id = timeline.timeline_id;
    1842            0 :                     let import_task_gate = Gate::default();
    1843            0 :                     let import_task_guard = import_task_gate.enter().unwrap();
    1844            0 :                     let import_task_handle =
    1845            0 :                         tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1846            0 :                             timeline.clone(),
    1847            0 :                             import_pgdata,
    1848            0 :                             guard,
    1849            0 :                             import_task_guard,
    1850            0 :                             ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1851              :                         ));
    1852              : 
    1853            0 :                     let prev = self.timelines_importing.lock().unwrap().insert(
    1854            0 :                         timeline_id,
    1855            0 :                         Arc::new(ImportingTimeline {
    1856            0 :                             timeline: timeline.clone(),
    1857            0 :                             import_task_handle,
    1858            0 :                             import_task_gate,
    1859            0 :                             delete_progress: TimelineDeleteProgress::default(),
    1860            0 :                         }),
    1861            0 :                     );
    1862              : 
    1863            0 :                     assert!(prev.is_none());
    1864              :                 }
    1865              :             }
    1866              :         }
    1867              : 
    1868              :         // At this point we've initialized all timelines and are tracking them.
    1869              :         // Now compute the layer visibility for all (not offloaded) timelines.
    1870          119 :         let compute_visiblity_for = {
    1871          119 :             let timelines_accessor = self.timelines.lock().unwrap();
    1872          119 :             let mut timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    1873              : 
    1874          119 :             timelines_offloaded_accessor.extend(offloaded_timelines_list.into_iter());
    1875              : 
    1876              :             // Before activation, populate each Timeline's GcInfo with information about its children
    1877          119 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    1878              : 
    1879          119 :             timelines_accessor.values().cloned().collect::<Vec<_>>()
    1880              :         };
    1881              : 
    1882          122 :         for tl in compute_visiblity_for {
    1883            3 :             tl.update_layer_visibility().await.with_context(|| {
    1884            0 :                 format!(
    1885            0 :                     "failed initial timeline visibility computation {} for tenant {}",
    1886            0 :                     tl.timeline_id, self.tenant_shard_id
    1887              :                 )
    1888            0 :             })?;
    1889              :         }
    1890              : 
    1891              :         // Walk through deleted timelines, resume deletion
    1892          119 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1893            0 :             remote_timeline_client
    1894            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1895            0 :                 .context("init queue stopped")
    1896            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1897              : 
    1898            0 :             DeleteTimelineFlow::resume_deletion(
    1899            0 :                 Arc::clone(self),
    1900            0 :                 timeline_id,
    1901            0 :                 &index_part.metadata,
    1902            0 :                 remote_timeline_client,
    1903            0 :                 ctx,
    1904              :             )
    1905            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1906            0 :             .await
    1907            0 :             .context("resume_deletion")
    1908            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1909              :         }
    1910              : 
    1911              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1912              :         //
    1913              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1914              :         // offloaded timelines, which are included in the manifest.
    1915              :         {
    1916          119 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1917          119 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1918          119 :             *guard = preload.tenant_manifest;
    1919              :         }
    1920          119 :         self.maybe_upload_tenant_manifest().await?;
    1921              : 
    1922              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1923              :         // IndexPart is the source of truth.
    1924          119 :         self.clean_up_timelines(&existent_timelines)?;
    1925              : 
    1926          119 :         self.gc_block.set_scanned(gc_blocks);
    1927              : 
    1928          119 :         fail::fail_point!("attach-before-activate", |_| {
    1929            0 :             anyhow::bail!("attach-before-activate");
    1930            0 :         });
    1931          119 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1932              : 
    1933          119 :         info!("Done");
    1934              : 
    1935          119 :         Ok(())
    1936          119 :     }
    1937              : 
    1938              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1939              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1940              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1941          119 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1942          119 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1943              : 
    1944          119 :         let entries = match timelines_dir.read_dir_utf8() {
    1945          119 :             Ok(d) => d,
    1946            0 :             Err(e) => {
    1947            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1948            0 :                     return Ok(());
    1949              :                 } else {
    1950            0 :                     return Err(e).context("list timelines directory for tenant");
    1951              :                 }
    1952              :             }
    1953              :         };
    1954              : 
    1955          123 :         for entry in entries {
    1956            4 :             let entry = entry.context("read timeline dir entry")?;
    1957            4 :             let entry_path = entry.path();
    1958              : 
    1959            4 :             let purge = if crate::is_temporary(entry_path) {
    1960            0 :                 true
    1961              :             } else {
    1962            4 :                 match TimelineId::try_from(entry_path.file_name()) {
    1963            4 :                     Ok(i) => {
    1964              :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1965            4 :                         !existent_timelines.contains(&i)
    1966              :                     }
    1967            0 :                     Err(e) => {
    1968            0 :                         tracing::warn!(
    1969            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1970              :                         );
    1971              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1972            0 :                         false
    1973              :                     }
    1974              :                 }
    1975              :             };
    1976              : 
    1977            4 :             if purge {
    1978            1 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1979            1 :                 if let Err(e) = match entry.file_type() {
    1980            1 :                     Ok(t) => if t.is_dir() {
    1981            1 :                         std::fs::remove_dir_all(entry_path)
    1982              :                     } else {
    1983            0 :                         std::fs::remove_file(entry_path)
    1984              :                     }
    1985            1 :                     .or_else(fs_ext::ignore_not_found),
    1986            0 :                     Err(e) => Err(e),
    1987              :                 } {
    1988            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1989            1 :                 }
    1990            3 :             }
    1991              :         }
    1992              : 
    1993          119 :         Ok(())
    1994          119 :     }
    1995              : 
    1996              :     /// Get sum of all remote timelines sizes
    1997              :     ///
    1998              :     /// This function relies on the index_part instead of listing the remote storage
    1999            0 :     pub fn remote_size(&self) -> u64 {
    2000            0 :         let mut size = 0;
    2001              : 
    2002            0 :         for timeline in self.list_timelines() {
    2003            0 :             size += timeline.remote_client.get_remote_physical_size();
    2004            0 :         }
    2005              : 
    2006            0 :         size
    2007            0 :     }
    2008              : 
    2009              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    2010              :     #[allow(clippy::too_many_arguments)]
    2011              :     async fn load_remote_timeline(
    2012              :         self: &Arc<Self>,
    2013              :         timeline_id: TimelineId,
    2014              :         index_part: IndexPart,
    2015              :         remote_metadata: TimelineMetadata,
    2016              :         previous_heatmap: Option<PreviousHeatmap>,
    2017              :         resources: TimelineResources,
    2018              :         cause: LoadTimelineCause,
    2019              :         ctx: &RequestContext,
    2020              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    2021              :         span::debug_assert_current_span_has_tenant_id();
    2022              : 
    2023              :         info!("downloading index file for timeline {}", timeline_id);
    2024              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    2025              :             .await
    2026              :             .context("Failed to create new timeline directory")?;
    2027              : 
    2028              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    2029              :             let timelines = self.timelines.lock().unwrap();
    2030              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    2031            0 :                 || {
    2032            0 :                     anyhow::anyhow!(
    2033            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    2034              :                     )
    2035            0 :                 },
    2036              :             )?))
    2037              :         } else {
    2038              :             None
    2039              :         };
    2040              : 
    2041              :         self.timeline_init_and_sync(
    2042              :             timeline_id,
    2043              :             resources,
    2044              :             index_part,
    2045              :             remote_metadata,
    2046              :             previous_heatmap,
    2047              :             ancestor,
    2048              :             cause,
    2049              :             ctx,
    2050              :         )
    2051              :         .await
    2052              :     }
    2053              : 
    2054          119 :     async fn load_timelines_metadata(
    2055          119 :         self: &Arc<TenantShard>,
    2056          119 :         timeline_ids: HashSet<TimelineId>,
    2057          119 :         remote_storage: &GenericRemoteStorage,
    2058          119 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    2059          119 :         cancel: CancellationToken,
    2060          119 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    2061          119 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    2062              : 
    2063          119 :         let mut part_downloads = JoinSet::new();
    2064          122 :         for timeline_id in timeline_ids {
    2065            3 :             let cancel_clone = cancel.clone();
    2066              : 
    2067            3 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    2068            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    2069            0 :                     heatmap: h,
    2070            0 :                     read_at: hs.1,
    2071            0 :                     end_lsn: None,
    2072            0 :                 })
    2073            0 :             });
    2074            3 :             part_downloads.spawn(
    2075            3 :                 self.load_timeline_metadata(
    2076            3 :                     timeline_id,
    2077            3 :                     remote_storage.clone(),
    2078            3 :                     previous_timeline_heatmap,
    2079            3 :                     cancel_clone,
    2080              :                 )
    2081            3 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    2082              :             );
    2083              :         }
    2084              : 
    2085          119 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    2086              : 
    2087              :         loop {
    2088          122 :             tokio::select!(
    2089          122 :                 next = part_downloads.join_next() => {
    2090          122 :                     match next {
    2091            3 :                         Some(result) => {
    2092            3 :                             let preload = result.context("join preload task")?;
    2093            3 :                             timeline_preloads.insert(preload.timeline_id, preload);
    2094              :                         },
    2095              :                         None => {
    2096          119 :                             break;
    2097              :                         }
    2098              :                     }
    2099              :                 },
    2100          122 :                 _ = cancel.cancelled() => {
    2101            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2102              :                 }
    2103              :             )
    2104              :         }
    2105              : 
    2106          119 :         Ok(timeline_preloads)
    2107          119 :     }
    2108              : 
    2109            3 :     fn build_timeline_client(
    2110            3 :         &self,
    2111            3 :         timeline_id: TimelineId,
    2112            3 :         remote_storage: GenericRemoteStorage,
    2113            3 :     ) -> RemoteTimelineClient {
    2114            3 :         RemoteTimelineClient::new(
    2115            3 :             remote_storage.clone(),
    2116            3 :             self.deletion_queue_client.clone(),
    2117            3 :             self.conf,
    2118            3 :             self.tenant_shard_id,
    2119            3 :             timeline_id,
    2120            3 :             self.generation,
    2121            3 :             &self.tenant_conf.load().location,
    2122              :         )
    2123            3 :     }
    2124              : 
    2125            3 :     fn load_timeline_metadata(
    2126            3 :         self: &Arc<TenantShard>,
    2127            3 :         timeline_id: TimelineId,
    2128            3 :         remote_storage: GenericRemoteStorage,
    2129            3 :         previous_heatmap: Option<PreviousHeatmap>,
    2130            3 :         cancel: CancellationToken,
    2131            3 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2132            3 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2133            3 :         async move {
    2134            3 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2135            3 :             debug!("starting index part download");
    2136              : 
    2137            3 :             let index_part = client.download_index_file(&cancel).await;
    2138              : 
    2139            3 :             debug!("finished index part download");
    2140              : 
    2141            3 :             TimelinePreload {
    2142            3 :                 client,
    2143            3 :                 timeline_id,
    2144            3 :                 index_part,
    2145            3 :                 previous_heatmap,
    2146            3 :             }
    2147            3 :         }
    2148            3 :     }
    2149              : 
    2150            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2151            0 :         timeline_id: TimelineId,
    2152            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2153            0 :     ) -> Result<(), TimelineArchivalError> {
    2154            0 :         let children: Vec<TimelineId> = timelines
    2155            0 :             .iter()
    2156            0 :             .filter_map(|(id, entry)| {
    2157            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2158            0 :                     return None;
    2159            0 :                 }
    2160            0 :                 if entry.is_archived() == Some(true) {
    2161            0 :                     return None;
    2162            0 :                 }
    2163            0 :                 Some(*id)
    2164            0 :             })
    2165            0 :             .collect();
    2166              : 
    2167            0 :         if !children.is_empty() {
    2168            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2169            0 :         }
    2170            0 :         Ok(())
    2171            0 :     }
    2172              : 
    2173            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2174            0 :         ancestor_timeline_id: TimelineId,
    2175            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2176            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2177            0 :             '_,
    2178            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2179            0 :         >,
    2180            0 :     ) -> Result<(), TimelineArchivalError> {
    2181            0 :         let has_archived_parent =
    2182            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2183            0 :                 ancestor_timeline.is_archived() == Some(true)
    2184            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2185            0 :                 true
    2186              :             } else {
    2187            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2188            0 :                 if cfg!(debug_assertions) {
    2189            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2190            0 :                 }
    2191            0 :                 return Err(TimelineArchivalError::NotFound);
    2192              :             };
    2193            0 :         if has_archived_parent {
    2194            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2195            0 :                 ancestor_timeline_id,
    2196            0 :             ));
    2197            0 :         }
    2198            0 :         Ok(())
    2199            0 :     }
    2200              : 
    2201            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2202            0 :         timeline: &Arc<Timeline>,
    2203            0 :     ) -> Result<(), TimelineArchivalError> {
    2204            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2205            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2206            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2207            0 :                     ancestor_timeline.timeline_id,
    2208            0 :                 ));
    2209            0 :             }
    2210            0 :         }
    2211            0 :         Ok(())
    2212            0 :     }
    2213              : 
    2214              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2215              :     ///
    2216              :     /// Counterpart to [`offload_timeline`].
    2217            0 :     async fn unoffload_timeline(
    2218            0 :         self: &Arc<Self>,
    2219            0 :         timeline_id: TimelineId,
    2220            0 :         broker_client: storage_broker::BrokerClientChannel,
    2221            0 :         ctx: RequestContext,
    2222            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2223            0 :         info!("unoffloading timeline");
    2224              : 
    2225              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2226              :         // We expect callers of this function to ensure this.
    2227            0 :         match self.current_state() {
    2228              :             TenantState::Activating { .. }
    2229              :             | TenantState::Attaching
    2230              :             | TenantState::Broken { .. } => {
    2231            0 :                 panic!("Timeline expected to be active")
    2232              :             }
    2233            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2234            0 :             TenantState::Active => {}
    2235              :         }
    2236            0 :         let cancel = self.cancel.clone();
    2237              : 
    2238              :         // Protect against concurrent attempts to use this TimelineId
    2239              :         // We don't care much about idempotency, as it's ensured a layer above.
    2240            0 :         let allow_offloaded = true;
    2241            0 :         let _create_guard = self
    2242            0 :             .create_timeline_create_guard(
    2243            0 :                 timeline_id,
    2244            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2245            0 :                 allow_offloaded,
    2246              :             )
    2247            0 :             .map_err(|err| match err {
    2248            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2249              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2250            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2251              :                 }
    2252            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2253            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2254            0 :             })?;
    2255              : 
    2256            0 :         let timeline_preload = self
    2257            0 :             .load_timeline_metadata(
    2258            0 :                 timeline_id,
    2259            0 :                 self.remote_storage.clone(),
    2260            0 :                 None,
    2261            0 :                 cancel.clone(),
    2262            0 :             )
    2263            0 :             .await;
    2264              : 
    2265            0 :         let index_part = match timeline_preload.index_part {
    2266            0 :             Ok(index_part) => {
    2267            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2268            0 :                 index_part
    2269              :             }
    2270              :             Err(DownloadError::NotFound) => {
    2271            0 :                 error!(%timeline_id, "index_part not found on remote");
    2272            0 :                 return Err(TimelineArchivalError::NotFound);
    2273              :             }
    2274            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2275            0 :             Err(e) => {
    2276              :                 // Some (possibly ephemeral) error happened during index_part download.
    2277            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2278            0 :                 return Err(TimelineArchivalError::Other(
    2279            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2280            0 :                 ));
    2281              :             }
    2282              :         };
    2283            0 :         let index_part = match index_part {
    2284            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2285            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2286            0 :                 info!("timeline is deleted according to index_part.json");
    2287            0 :                 return Err(TimelineArchivalError::NotFound);
    2288              :             }
    2289              :         };
    2290            0 :         let remote_metadata = index_part.metadata.clone();
    2291            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2292            0 :         self.load_remote_timeline(
    2293            0 :             timeline_id,
    2294            0 :             index_part,
    2295            0 :             remote_metadata,
    2296            0 :             None,
    2297            0 :             timeline_resources,
    2298            0 :             LoadTimelineCause::Unoffload,
    2299            0 :             &ctx,
    2300            0 :         )
    2301            0 :         .await
    2302            0 :         .with_context(|| {
    2303            0 :             format!(
    2304            0 :                 "failed to load remote timeline {} for tenant {}",
    2305            0 :                 timeline_id, self.tenant_shard_id
    2306              :             )
    2307            0 :         })
    2308            0 :         .map_err(TimelineArchivalError::Other)?;
    2309              : 
    2310            0 :         let timeline = {
    2311            0 :             let timelines = self.timelines.lock().unwrap();
    2312            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2313            0 :                 warn!("timeline not available directly after attach");
    2314              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2315              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2316            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2317            0 :                     "timeline not available directly after attach"
    2318            0 :                 )));
    2319              :             };
    2320            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2321            0 :             match offloaded_timelines.remove(&timeline_id) {
    2322            0 :                 Some(offloaded) => {
    2323            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2324            0 :                 }
    2325            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2326              :             }
    2327              : 
    2328            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2329              : 
    2330            0 :             Arc::clone(timeline)
    2331              :         };
    2332              : 
    2333              :         // Upload new list of offloaded timelines to S3
    2334            0 :         self.maybe_upload_tenant_manifest().await?;
    2335              : 
    2336              :         // Activate the timeline (if it makes sense)
    2337            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2338            0 :             let background_jobs_can_start = None;
    2339            0 :             timeline.activate(
    2340            0 :                 self.clone(),
    2341            0 :                 broker_client.clone(),
    2342            0 :                 background_jobs_can_start,
    2343            0 :                 &ctx.with_scope_timeline(&timeline),
    2344            0 :             );
    2345            0 :         }
    2346              : 
    2347            0 :         info!("timeline unoffloading complete");
    2348            0 :         Ok(timeline)
    2349            0 :     }
    2350              : 
    2351            0 :     pub(crate) async fn apply_timeline_archival_config(
    2352            0 :         self: &Arc<Self>,
    2353            0 :         timeline_id: TimelineId,
    2354            0 :         new_state: TimelineArchivalState,
    2355            0 :         broker_client: storage_broker::BrokerClientChannel,
    2356            0 :         ctx: RequestContext,
    2357            0 :     ) -> Result<(), TimelineArchivalError> {
    2358            0 :         info!("setting timeline archival config");
    2359              :         // First part: figure out what is needed to do, and do validation
    2360            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2361            0 :             let timelines = self.timelines.lock().unwrap();
    2362              : 
    2363            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2364            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2365            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2366            0 :                     return Err(TimelineArchivalError::NotFound);
    2367              :                 };
    2368            0 :                 if new_state == TimelineArchivalState::Archived {
    2369              :                     // It's offloaded already, so nothing to do
    2370            0 :                     return Ok(());
    2371            0 :                 }
    2372            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2373            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2374            0 :                         ancestor_timeline_id,
    2375            0 :                         &timelines,
    2376            0 :                         &offloaded_timelines,
    2377            0 :                     )?;
    2378            0 :                 }
    2379            0 :                 break 'outer None;
    2380              :             };
    2381              : 
    2382              :             // Do some validation. We release the timelines lock below, so there is potential
    2383              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2384              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2385            0 :             match new_state {
    2386              :                 TimelineArchivalState::Unarchived => {
    2387            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2388              :                 }
    2389              :                 TimelineArchivalState::Archived => {
    2390            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2391              :                 }
    2392              :             }
    2393            0 :             Some(Arc::clone(timeline))
    2394              :         };
    2395              : 
    2396              :         // Second part: unoffload timeline (if needed)
    2397            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2398            0 :             timeline
    2399              :         } else {
    2400              :             // Turn offloaded timeline into a non-offloaded one
    2401            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2402            0 :                 .await?
    2403              :         };
    2404              : 
    2405              :         // Third part: upload new timeline archival state and block until it is present in S3
    2406            0 :         let upload_needed = match timeline
    2407            0 :             .remote_client
    2408            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2409              :         {
    2410            0 :             Ok(upload_needed) => upload_needed,
    2411            0 :             Err(e) => {
    2412            0 :                 if timeline.cancel.is_cancelled() {
    2413            0 :                     return Err(TimelineArchivalError::Cancelled);
    2414              :                 } else {
    2415            0 :                     return Err(TimelineArchivalError::Other(e));
    2416              :                 }
    2417              :             }
    2418              :         };
    2419              : 
    2420            0 :         if upload_needed {
    2421            0 :             info!("Uploading new state");
    2422              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2423            0 :             let Ok(v) =
    2424            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2425              :             else {
    2426            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2427            0 :                 return Err(TimelineArchivalError::Timeout);
    2428              :             };
    2429            0 :             v.map_err(|e| match e {
    2430            0 :                 WaitCompletionError::NotInitialized(e) => {
    2431            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2432              :                 }
    2433              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2434            0 :                     TimelineArchivalError::Cancelled
    2435              :                 }
    2436            0 :             })?;
    2437            0 :         }
    2438            0 :         Ok(())
    2439            0 :     }
    2440              : 
    2441            1 :     pub fn get_offloaded_timeline(
    2442            1 :         &self,
    2443            1 :         timeline_id: TimelineId,
    2444            1 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2445            1 :         self.timelines_offloaded
    2446            1 :             .lock()
    2447            1 :             .unwrap()
    2448            1 :             .get(&timeline_id)
    2449            1 :             .map(Arc::clone)
    2450            1 :             .ok_or(GetTimelineError::NotFound {
    2451            1 :                 tenant_id: self.tenant_shard_id,
    2452            1 :                 timeline_id,
    2453            1 :             })
    2454            1 :     }
    2455              : 
    2456            2 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2457            2 :         self.tenant_shard_id
    2458            2 :     }
    2459              : 
    2460              :     /// Get Timeline handle for given Neon timeline ID.
    2461              :     /// This function is idempotent. It doesn't change internal state in any way.
    2462          111 :     pub fn get_timeline(
    2463          111 :         &self,
    2464          111 :         timeline_id: TimelineId,
    2465          111 :         active_only: bool,
    2466          111 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2467          111 :         let timelines_accessor = self.timelines.lock().unwrap();
    2468          111 :         let timeline = timelines_accessor
    2469          111 :             .get(&timeline_id)
    2470          111 :             .ok_or(GetTimelineError::NotFound {
    2471          111 :                 tenant_id: self.tenant_shard_id,
    2472          111 :                 timeline_id,
    2473          111 :             })?;
    2474              : 
    2475          110 :         if active_only && !timeline.is_active() {
    2476            0 :             Err(GetTimelineError::NotActive {
    2477            0 :                 tenant_id: self.tenant_shard_id,
    2478            0 :                 timeline_id,
    2479            0 :                 state: timeline.current_state(),
    2480            0 :             })
    2481              :         } else {
    2482          110 :             Ok(Arc::clone(timeline))
    2483              :         }
    2484          111 :     }
    2485              : 
    2486              :     /// Lists timelines the tenant contains.
    2487              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2488            3 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2489            3 :         self.timelines
    2490            3 :             .lock()
    2491            3 :             .unwrap()
    2492            3 :             .values()
    2493            3 :             .map(Arc::clone)
    2494            3 :             .collect()
    2495            3 :     }
    2496              : 
    2497              :     /// Lists timelines the tenant contains.
    2498              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2499            0 :     pub fn list_importing_timelines(&self) -> Vec<Arc<ImportingTimeline>> {
    2500            0 :         self.timelines_importing
    2501            0 :             .lock()
    2502            0 :             .unwrap()
    2503            0 :             .values()
    2504            0 :             .map(Arc::clone)
    2505            0 :             .collect()
    2506            0 :     }
    2507              : 
    2508              :     /// Lists timelines the tenant manages, including offloaded ones.
    2509              :     ///
    2510              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2511            0 :     pub fn list_timelines_and_offloaded(
    2512            0 :         &self,
    2513            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2514            0 :         let timelines = self
    2515            0 :             .timelines
    2516            0 :             .lock()
    2517            0 :             .unwrap()
    2518            0 :             .values()
    2519            0 :             .map(Arc::clone)
    2520            0 :             .collect();
    2521            0 :         let offloaded = self
    2522            0 :             .timelines_offloaded
    2523            0 :             .lock()
    2524            0 :             .unwrap()
    2525            0 :             .values()
    2526            0 :             .map(Arc::clone)
    2527            0 :             .collect();
    2528            0 :         (timelines, offloaded)
    2529            0 :     }
    2530              : 
    2531            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2532            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2533            0 :     }
    2534              : 
    2535              :     /// This is used by tests & import-from-basebackup.
    2536              :     ///
    2537              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2538              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2539              :     ///
    2540              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2541              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2542              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2543              :     /// to the [`TenantShard::timelines`].
    2544              :     ///
    2545              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2546          115 :     pub(crate) async fn create_empty_timeline(
    2547          115 :         self: &Arc<Self>,
    2548          115 :         new_timeline_id: TimelineId,
    2549          115 :         initdb_lsn: Lsn,
    2550          115 :         pg_version: PgMajorVersion,
    2551          115 :         ctx: &RequestContext,
    2552          115 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2553          115 :         anyhow::ensure!(
    2554          115 :             self.is_active(),
    2555            0 :             "Cannot create empty timelines on inactive tenant"
    2556              :         );
    2557              : 
    2558              :         // Protect against concurrent attempts to use this TimelineId
    2559          115 :         let create_guard = match self
    2560          115 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2561          115 :             .await?
    2562              :         {
    2563          114 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2564              :             StartCreatingTimelineResult::Idempotent(_) => {
    2565            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2566              :             }
    2567              :         };
    2568              : 
    2569          114 :         let new_metadata = TimelineMetadata::new(
    2570              :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2571              :             // make it valid, before calling finish_creation()
    2572          114 :             Lsn(0),
    2573          114 :             None,
    2574          114 :             None,
    2575          114 :             Lsn(0),
    2576          114 :             initdb_lsn,
    2577          114 :             initdb_lsn,
    2578          114 :             pg_version,
    2579              :         );
    2580          114 :         self.prepare_new_timeline(
    2581          114 :             new_timeline_id,
    2582          114 :             &new_metadata,
    2583          114 :             create_guard,
    2584          114 :             initdb_lsn,
    2585          114 :             None,
    2586          114 :             None,
    2587          114 :             ctx,
    2588          114 :         )
    2589          114 :         .await
    2590          115 :     }
    2591              : 
    2592              :     /// Helper for unit tests to create an empty timeline.
    2593              :     ///
    2594              :     /// The timeline is has state value `Active` but its background loops are not running.
    2595              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2596              :     // Our current tests don't need the background loops.
    2597              :     #[cfg(test)]
    2598          110 :     pub async fn create_test_timeline(
    2599          110 :         self: &Arc<Self>,
    2600          110 :         new_timeline_id: TimelineId,
    2601          110 :         initdb_lsn: Lsn,
    2602          110 :         pg_version: PgMajorVersion,
    2603          110 :         ctx: &RequestContext,
    2604          110 :     ) -> anyhow::Result<Arc<Timeline>> {
    2605          110 :         let (uninit_tl, ctx) = self
    2606          110 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2607          110 :             .await?;
    2608          110 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2609          110 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2610              : 
    2611              :         // Setup minimum keys required for the timeline to be usable.
    2612          110 :         let mut modification = tline.begin_modification(initdb_lsn);
    2613          110 :         modification
    2614          110 :             .init_empty_test_timeline()
    2615          110 :             .context("init_empty_test_timeline")?;
    2616          110 :         modification
    2617          110 :             .commit(&ctx)
    2618          110 :             .await
    2619          110 :             .context("commit init_empty_test_timeline modification")?;
    2620              : 
    2621              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2622          110 :         tline.maybe_spawn_flush_loop();
    2623          110 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2624              : 
    2625              :         // Make sure the freeze_and_flush reaches remote storage.
    2626          110 :         tline.remote_client.wait_completion().await.unwrap();
    2627              : 
    2628          110 :         let tl = uninit_tl.finish_creation().await?;
    2629              :         // The non-test code would call tl.activate() here.
    2630          110 :         tl.set_state(TimelineState::Active);
    2631          110 :         Ok(tl)
    2632          110 :     }
    2633              : 
    2634              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2635              :     #[cfg(test)]
    2636              :     #[allow(clippy::too_many_arguments)]
    2637           24 :     pub async fn create_test_timeline_with_layers(
    2638           24 :         self: &Arc<Self>,
    2639           24 :         new_timeline_id: TimelineId,
    2640           24 :         initdb_lsn: Lsn,
    2641           24 :         pg_version: PgMajorVersion,
    2642           24 :         ctx: &RequestContext,
    2643           24 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2644           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2645           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2646           24 :         end_lsn: Lsn,
    2647           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    2648              :         use checks::check_valid_layermap;
    2649              :         use itertools::Itertools;
    2650              : 
    2651           24 :         let tline = self
    2652           24 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2653           24 :             .await?;
    2654           24 :         tline.force_advance_lsn(end_lsn);
    2655           71 :         for deltas in delta_layer_desc {
    2656           47 :             tline
    2657           47 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2658           47 :                 .await?;
    2659              :         }
    2660           58 :         for (lsn, images) in image_layer_desc {
    2661           34 :             tline
    2662           34 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2663           34 :                 .await?;
    2664              :         }
    2665           28 :         for in_memory in in_memory_layer_desc {
    2666            4 :             tline
    2667            4 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2668            4 :                 .await?;
    2669              :         }
    2670           24 :         let layer_names = tline
    2671           24 :             .layers
    2672           24 :             .read(LayerManagerLockHolder::Testing)
    2673           24 :             .await
    2674           24 :             .layer_map()
    2675           24 :             .unwrap()
    2676           24 :             .iter_historic_layers()
    2677          105 :             .map(|layer| layer.layer_name())
    2678           24 :             .collect_vec();
    2679           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2680            0 :             bail!("invalid layermap: {err}");
    2681           24 :         }
    2682           24 :         Ok(tline)
    2683           24 :     }
    2684              : 
    2685              :     /// Create a new timeline.
    2686              :     ///
    2687              :     /// Returns the new timeline ID and reference to its Timeline object.
    2688              :     ///
    2689              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2690              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2691              :     #[allow(clippy::too_many_arguments)]
    2692            0 :     pub(crate) async fn create_timeline(
    2693            0 :         self: &Arc<TenantShard>,
    2694            0 :         params: CreateTimelineParams,
    2695            0 :         broker_client: storage_broker::BrokerClientChannel,
    2696            0 :         ctx: &RequestContext,
    2697            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2698            0 :         if !self.is_active() {
    2699            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2700            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2701              :             } else {
    2702            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2703            0 :                     "Cannot create timelines on inactive tenant"
    2704            0 :                 )));
    2705              :             }
    2706            0 :         }
    2707              : 
    2708            0 :         let _gate = self
    2709            0 :             .gate
    2710            0 :             .enter()
    2711            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2712              : 
    2713            0 :         let result: CreateTimelineResult = match params {
    2714              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2715            0 :                 new_timeline_id,
    2716            0 :                 existing_initdb_timeline_id,
    2717            0 :                 pg_version,
    2718              :             }) => {
    2719            0 :                 self.bootstrap_timeline(
    2720            0 :                     new_timeline_id,
    2721            0 :                     pg_version,
    2722            0 :                     existing_initdb_timeline_id,
    2723            0 :                     ctx,
    2724            0 :                 )
    2725            0 :                 .await?
    2726              :             }
    2727              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2728            0 :                 new_timeline_id,
    2729            0 :                 ancestor_timeline_id,
    2730            0 :                 mut ancestor_start_lsn,
    2731              :             }) => {
    2732            0 :                 let ancestor_timeline = self
    2733            0 :                     .get_timeline(ancestor_timeline_id, false)
    2734            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2735              : 
    2736              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2737              :                 // ready for other purposes either.
    2738            0 :                 if !ancestor_timeline.is_active() {
    2739            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2740            0 :                 }
    2741              : 
    2742            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2743            0 :                     info!("tried to branch archived timeline");
    2744            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2745            0 :                 }
    2746              : 
    2747            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2748            0 :                     *lsn = lsn.align();
    2749              : 
    2750            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2751            0 :                     if ancestor_ancestor_lsn > *lsn {
    2752              :                         // can we safely just branch from the ancestor instead?
    2753            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2754            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2755            0 :                             lsn,
    2756            0 :                             ancestor_timeline_id,
    2757            0 :                             ancestor_ancestor_lsn,
    2758            0 :                         )));
    2759            0 :                     }
    2760              : 
    2761              :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2762              :                     // to the requested branch point. The repository code itself doesn't
    2763              :                     // require it, but if we start to receive WAL on the new timeline,
    2764              :                     // decoding the new WAL might need to look up previous pages, relation
    2765              :                     // sizes etc. and that would get confused if the previous page versions
    2766              :                     // are not in the repository yet.
    2767            0 :                     ancestor_timeline
    2768            0 :                         .wait_lsn(
    2769            0 :                             *lsn,
    2770            0 :                             timeline::WaitLsnWaiter::Tenant,
    2771            0 :                             timeline::WaitLsnTimeout::Default,
    2772            0 :                             ctx,
    2773            0 :                         )
    2774            0 :                         .await
    2775            0 :                         .map_err(|e| match e {
    2776            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2777            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2778              :                             }
    2779            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2780            0 :                         })?;
    2781            0 :                 }
    2782              : 
    2783            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2784            0 :                     .await?
    2785              :             }
    2786            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2787            0 :                 self.create_timeline_import_pgdata(params, ctx).await?
    2788              :             }
    2789              :         };
    2790              : 
    2791              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2792              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2793              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2794              :         //
    2795              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2796              :         // assume that, because they can see the timeline via API, that the creation is done and
    2797              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2798              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2799              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2800              :         //
    2801              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2802              :         // creation API until it returns success. Only then is durability guaranteed.
    2803            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2804            0 :         result
    2805            0 :             .timeline()
    2806            0 :             .remote_client
    2807            0 :             .wait_completion()
    2808            0 :             .await
    2809            0 :             .map_err(|e| match e {
    2810              :                 WaitCompletionError::NotInitialized(
    2811            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2812            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2813              :                 WaitCompletionError::NotInitialized(_) => {
    2814              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2815            0 :                     debug_assert!(false);
    2816            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2817              :                 }
    2818              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2819            0 :                     CreateTimelineError::ShuttingDown
    2820              :                 }
    2821            0 :             })?;
    2822              : 
    2823              :         // The creating task is responsible for activating the timeline.
    2824              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2825              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2826            0 :         let activated_timeline = match result {
    2827            0 :             CreateTimelineResult::Created(timeline) => {
    2828            0 :                 timeline.activate(
    2829            0 :                     self.clone(),
    2830            0 :                     broker_client,
    2831            0 :                     None,
    2832            0 :                     &ctx.with_scope_timeline(&timeline),
    2833              :                 );
    2834            0 :                 timeline
    2835              :             }
    2836            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2837            0 :                 info!(
    2838            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2839              :                 );
    2840            0 :                 timeline
    2841              :             }
    2842            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2843            0 :                 info!(
    2844            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2845              :                 );
    2846            0 :                 timeline
    2847              :             }
    2848              :         };
    2849              : 
    2850            0 :         Ok(activated_timeline)
    2851            0 :     }
    2852              : 
    2853              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2854              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2855              :     /// [`TenantShard::timelines`] map when the import completes.
    2856              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2857              :     /// for the response.
    2858            0 :     async fn create_timeline_import_pgdata(
    2859            0 :         self: &Arc<Self>,
    2860            0 :         params: CreateTimelineParamsImportPgdata,
    2861            0 :         ctx: &RequestContext,
    2862            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2863              :         let CreateTimelineParamsImportPgdata {
    2864            0 :             new_timeline_id,
    2865            0 :             location,
    2866            0 :             idempotency_key,
    2867            0 :         } = params;
    2868              : 
    2869            0 :         let started_at = chrono::Utc::now().naive_utc();
    2870              : 
    2871              :         //
    2872              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2873              :         // is the canonical way we do it.
    2874              :         // - create an empty timeline in-memory
    2875              :         // - use its remote_timeline_client to do the upload
    2876              :         // - dispose of the uninit timeline
    2877              :         // - keep the creation guard alive
    2878              : 
    2879            0 :         let timeline_create_guard = match self
    2880            0 :             .start_creating_timeline(
    2881            0 :                 new_timeline_id,
    2882            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2883            0 :                     idempotency_key: idempotency_key.clone(),
    2884            0 :                 }),
    2885            0 :             )
    2886            0 :             .await?
    2887              :         {
    2888            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2889            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2890            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2891              :             }
    2892              :         };
    2893              : 
    2894            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2895            0 :             let this = &self;
    2896            0 :             let initdb_lsn = Lsn(0);
    2897            0 :             async move {
    2898            0 :                 let new_metadata = TimelineMetadata::new(
    2899              :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2900              :                     // make it valid, before calling finish_creation()
    2901            0 :                     Lsn(0),
    2902            0 :                     None,
    2903            0 :                     None,
    2904            0 :                     Lsn(0),
    2905            0 :                     initdb_lsn,
    2906            0 :                     initdb_lsn,
    2907            0 :                     PgMajorVersion::PG15,
    2908              :                 );
    2909            0 :                 this.prepare_new_timeline(
    2910            0 :                     new_timeline_id,
    2911            0 :                     &new_metadata,
    2912            0 :                     timeline_create_guard,
    2913            0 :                     initdb_lsn,
    2914            0 :                     None,
    2915            0 :                     None,
    2916            0 :                     ctx,
    2917            0 :                 )
    2918            0 :                 .await
    2919            0 :             }
    2920              :         }
    2921            0 :         .await?;
    2922              : 
    2923            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2924            0 :             idempotency_key,
    2925            0 :             location,
    2926            0 :             started_at,
    2927            0 :         };
    2928            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2929            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2930            0 :         );
    2931            0 :         uninit_timeline
    2932            0 :             .raw_timeline()
    2933            0 :             .unwrap()
    2934            0 :             .remote_client
    2935            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2936              : 
    2937              :         // wait_completion happens in caller
    2938              : 
    2939            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2940              : 
    2941            0 :         let import_task_gate = Gate::default();
    2942            0 :         let import_task_guard = import_task_gate.enter().unwrap();
    2943              : 
    2944            0 :         let import_task_handle = tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2945            0 :             timeline.clone(),
    2946            0 :             index_part,
    2947            0 :             timeline_create_guard,
    2948            0 :             import_task_guard,
    2949            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2950              :         ));
    2951              : 
    2952            0 :         let prev = self.timelines_importing.lock().unwrap().insert(
    2953            0 :             timeline.timeline_id,
    2954            0 :             Arc::new(ImportingTimeline {
    2955            0 :                 timeline: timeline.clone(),
    2956            0 :                 import_task_handle,
    2957            0 :                 import_task_gate,
    2958            0 :                 delete_progress: TimelineDeleteProgress::default(),
    2959            0 :             }),
    2960            0 :         );
    2961              : 
    2962              :         // Idempotency is enforced higher up the stack
    2963            0 :         assert!(prev.is_none());
    2964              : 
    2965              :         // NB: the timeline doesn't exist in self.timelines at this point
    2966            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2967            0 :     }
    2968              : 
    2969              :     /// Finalize the import of a timeline on this shard by marking it complete in
    2970              :     /// the index part. If the import task hasn't finished yet, returns an error.
    2971              :     ///
    2972              :     /// This method is idempotent. If the import was finalized once, the next call
    2973              :     /// will be a no-op.
    2974            0 :     pub(crate) async fn finalize_importing_timeline(
    2975            0 :         &self,
    2976            0 :         timeline_id: TimelineId,
    2977            0 :     ) -> Result<(), FinalizeTimelineImportError> {
    2978            0 :         let timeline = {
    2979            0 :             let locked = self.timelines_importing.lock().unwrap();
    2980            0 :             match locked.get(&timeline_id) {
    2981            0 :                 Some(importing_timeline) => {
    2982            0 :                     if !importing_timeline.import_task_handle.is_finished() {
    2983            0 :                         return Err(FinalizeTimelineImportError::ImportTaskStillRunning);
    2984            0 :                     }
    2985              : 
    2986            0 :                     importing_timeline.timeline.clone()
    2987              :                 }
    2988              :                 None => {
    2989            0 :                     return Ok(());
    2990              :                 }
    2991              :             }
    2992              :         };
    2993              : 
    2994            0 :         timeline
    2995            0 :             .remote_client
    2996            0 :             .schedule_index_upload_for_import_pgdata_finalize()
    2997            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    2998            0 :         timeline
    2999            0 :             .remote_client
    3000            0 :             .wait_completion()
    3001            0 :             .await
    3002            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    3003              : 
    3004            0 :         self.timelines_importing
    3005            0 :             .lock()
    3006            0 :             .unwrap()
    3007            0 :             .remove(&timeline_id);
    3008              : 
    3009            0 :         Ok(())
    3010            0 :     }
    3011              : 
    3012              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
    3013              :     async fn create_timeline_import_pgdata_task(
    3014              :         self: Arc<TenantShard>,
    3015              :         timeline: Arc<Timeline>,
    3016              :         index_part: import_pgdata::index_part_format::Root,
    3017              :         timeline_create_guard: TimelineCreateGuard,
    3018              :         _import_task_guard: GateGuard,
    3019              :         ctx: RequestContext,
    3020              :     ) {
    3021              :         debug_assert_current_span_has_tenant_and_timeline_id();
    3022              :         info!("starting");
    3023              :         scopeguard::defer! {info!("exiting")};
    3024              : 
    3025              :         let res = self
    3026              :             .create_timeline_import_pgdata_task_impl(
    3027              :                 timeline,
    3028              :                 index_part,
    3029              :                 timeline_create_guard,
    3030              :                 ctx,
    3031              :             )
    3032              :             .await;
    3033              :         if let Err(err) = &res {
    3034              :             error!(?err, "task failed");
    3035              :             // TODO sleep & retry, sensitive to tenant shutdown
    3036              :             // TODO: allow timeline deletion requests => should cancel the task
    3037              :         }
    3038              :     }
    3039              : 
    3040            0 :     async fn create_timeline_import_pgdata_task_impl(
    3041            0 :         self: Arc<TenantShard>,
    3042            0 :         timeline: Arc<Timeline>,
    3043            0 :         index_part: import_pgdata::index_part_format::Root,
    3044            0 :         _timeline_create_guard: TimelineCreateGuard,
    3045            0 :         ctx: RequestContext,
    3046            0 :     ) -> Result<(), anyhow::Error> {
    3047            0 :         info!("importing pgdata");
    3048            0 :         let ctx = ctx.with_scope_timeline(&timeline);
    3049            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    3050            0 :             .await
    3051            0 :             .context("import")?;
    3052            0 :         info!("import done - waiting for activation");
    3053              : 
    3054            0 :         anyhow::Ok(())
    3055            0 :     }
    3056              : 
    3057            0 :     pub(crate) async fn delete_timeline(
    3058            0 :         self: Arc<Self>,
    3059            0 :         timeline_id: TimelineId,
    3060            0 :     ) -> Result<(), DeleteTimelineError> {
    3061            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    3062              : 
    3063            0 :         Ok(())
    3064            0 :     }
    3065              : 
    3066              :     /// perform one garbage collection iteration, removing old data files from disk.
    3067              :     /// this function is periodically called by gc task.
    3068              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    3069              :     ///
    3070              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    3071              :     ///
    3072              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    3073              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    3074              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    3075              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    3076              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    3077              :     /// requires more history to be retained.
    3078              :     //
    3079          377 :     pub(crate) async fn gc_iteration(
    3080          377 :         &self,
    3081          377 :         target_timeline_id: Option<TimelineId>,
    3082          377 :         horizon: u64,
    3083          377 :         pitr: Duration,
    3084          377 :         cancel: &CancellationToken,
    3085          377 :         ctx: &RequestContext,
    3086          377 :     ) -> Result<GcResult, GcError> {
    3087              :         // Don't start doing work during shutdown
    3088          377 :         if let TenantState::Stopping { .. } = self.current_state() {
    3089            0 :             return Ok(GcResult::default());
    3090          377 :         }
    3091              : 
    3092              :         // there is a global allowed_error for this
    3093          377 :         if !self.is_active() {
    3094            0 :             return Err(GcError::NotActive);
    3095          377 :         }
    3096              : 
    3097              :         {
    3098          377 :             let conf = self.tenant_conf.load();
    3099              : 
    3100              :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    3101              :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    3102              :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    3103              :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    3104          377 :             if !conf.location.may_delete_layers_hint() {
    3105            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    3106            0 :                 return Ok(GcResult::default());
    3107          377 :             }
    3108              : 
    3109          377 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    3110            0 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3111            0 :                 return Ok(GcResult::default());
    3112          377 :             }
    3113              :         }
    3114              : 
    3115          377 :         let _guard = match self.gc_block.start().await {
    3116          377 :             Ok(guard) => guard,
    3117            0 :             Err(reasons) => {
    3118            0 :                 info!("Skipping GC: {reasons}");
    3119            0 :                 return Ok(GcResult::default());
    3120              :             }
    3121              :         };
    3122              : 
    3123          377 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3124          377 :             .await
    3125          377 :     }
    3126              : 
    3127              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3128              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3129              :     /// immediate L0 compaction.
    3130              :     ///
    3131              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3132            0 :     async fn compaction_iteration(
    3133            0 :         self: &Arc<Self>,
    3134            0 :         cancel: &CancellationToken,
    3135            0 :         ctx: &RequestContext,
    3136            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3137              :         // Don't compact inactive tenants.
    3138            0 :         if !self.is_active() {
    3139            0 :             return Ok(CompactionOutcome::Skipped);
    3140            0 :         }
    3141              : 
    3142              :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3143              :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3144            0 :         let location = self.tenant_conf.load().location;
    3145            0 :         if !location.may_upload_layers_hint() {
    3146            0 :             info!("skipping compaction in location state {location:?}");
    3147            0 :             return Ok(CompactionOutcome::Skipped);
    3148            0 :         }
    3149              : 
    3150              :         // Don't compact if the circuit breaker is tripped.
    3151            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3152            0 :             info!("skipping compaction due to previous failures");
    3153            0 :             return Ok(CompactionOutcome::Skipped);
    3154            0 :         }
    3155              : 
    3156              :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3157            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3158            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3159            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3160              : 
    3161              :         {
    3162            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3163            0 :             let timelines = self.timelines.lock().unwrap();
    3164            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3165              :                 // Skip inactive timelines.
    3166            0 :                 if !timeline.is_active() {
    3167            0 :                     continue;
    3168            0 :                 }
    3169              : 
    3170              :                 // Schedule the timeline for compaction.
    3171            0 :                 compact.push(timeline.clone());
    3172              : 
    3173              :                 // Schedule the timeline for offloading if eligible.
    3174            0 :                 let can_offload = offload_enabled
    3175            0 :                     && timeline.can_offload().0
    3176            0 :                     && !timelines
    3177            0 :                         .iter()
    3178            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3179            0 :                 if can_offload {
    3180            0 :                     offload.insert(timeline_id);
    3181            0 :                 }
    3182              :             }
    3183              :         } // release timelines lock
    3184              : 
    3185            0 :         for timeline in &compact {
    3186              :             // Collect L0 counts. Can't await while holding lock above.
    3187            0 :             if let Ok(lm) = timeline
    3188            0 :                 .layers
    3189            0 :                 .read(LayerManagerLockHolder::Compaction)
    3190            0 :                 .await
    3191            0 :                 .layer_map()
    3192            0 :             {
    3193            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3194            0 :             }
    3195              :         }
    3196              : 
    3197              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3198              :         // bound read amplification.
    3199              :         //
    3200              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3201              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3202              :         // splitting L0 and image/GC compaction to separate background jobs.
    3203            0 :         if self.get_compaction_l0_first() {
    3204            0 :             let compaction_threshold = self.get_compaction_threshold();
    3205            0 :             let compact_l0 = compact
    3206            0 :                 .iter()
    3207            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3208            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3209            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3210            0 :                 .rev()
    3211            0 :                 .map(|(tli, _)| tli.clone())
    3212            0 :                 .collect_vec();
    3213              : 
    3214            0 :             let mut has_pending_l0 = false;
    3215            0 :             for timeline in compact_l0 {
    3216            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3217              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3218            0 :                 let outcome = timeline
    3219            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3220            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3221            0 :                     .await
    3222            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3223            0 :                 match outcome {
    3224            0 :                     CompactionOutcome::Done => {}
    3225            0 :                     CompactionOutcome::Skipped => {}
    3226            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3227            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3228              :                 }
    3229              :             }
    3230            0 :             if has_pending_l0 {
    3231            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3232            0 :             }
    3233            0 :         }
    3234              : 
    3235              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3236              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3237              :         // pending L0 compaction on any tenant timeline.
    3238              :         //
    3239              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3240              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3241            0 :         let mut has_pending = false;
    3242            0 :         for timeline in compact {
    3243            0 :             if !timeline.is_active() {
    3244            0 :                 continue;
    3245            0 :             }
    3246            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3247              : 
    3248              :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3249            0 :             let mut flags = EnumSet::default();
    3250            0 :             if self.get_compaction_l0_first() {
    3251            0 :                 flags |= CompactFlags::YieldForL0;
    3252            0 :             }
    3253              : 
    3254            0 :             let mut outcome = timeline
    3255            0 :                 .compact(cancel, flags, ctx)
    3256            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3257            0 :                 .await
    3258            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3259              : 
    3260              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3261            0 :             if outcome == CompactionOutcome::Done {
    3262            0 :                 let queue = {
    3263            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3264            0 :                     guard
    3265            0 :                         .entry(timeline.timeline_id)
    3266            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3267            0 :                         .clone()
    3268              :                 };
    3269            0 :                 let gc_compaction_strategy = self
    3270            0 :                     .feature_resolver
    3271            0 :                     .evaluate_multivariate("gc-comapction-strategy")
    3272            0 :                     .ok();
    3273            0 :                 let span = if let Some(gc_compaction_strategy) = gc_compaction_strategy {
    3274            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id, strategy = %gc_compaction_strategy)
    3275              :                 } else {
    3276            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id)
    3277              :                 };
    3278            0 :                 outcome = queue
    3279            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3280            0 :                     .instrument(span)
    3281            0 :                     .await?;
    3282            0 :             }
    3283              : 
    3284              :             // If we're done compacting, offload the timeline if requested.
    3285            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3286            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3287            0 :                 offload_timeline(self, &timeline)
    3288            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3289            0 :                     .await
    3290            0 :                     .or_else(|err| match err {
    3291              :                         // Ignore this, we likely raced with unarchival.
    3292            0 :                         OffloadError::NotArchived => Ok(()),
    3293            0 :                         OffloadError::AlreadyInProgress => Ok(()),
    3294            0 :                         OffloadError::Cancelled => Err(CompactionError::new_cancelled()),
    3295              :                         // don't break the anyhow chain
    3296            0 :                         OffloadError::Other(err) => Err(CompactionError::Other(err)),
    3297            0 :                     })?;
    3298            0 :             }
    3299              : 
    3300            0 :             match outcome {
    3301            0 :                 CompactionOutcome::Done => {}
    3302            0 :                 CompactionOutcome::Skipped => {}
    3303            0 :                 CompactionOutcome::Pending => has_pending = true,
    3304              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3305              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3306            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3307              :             }
    3308              :         }
    3309              : 
    3310              :         // Success! Untrip the breaker if necessary.
    3311            0 :         self.compaction_circuit_breaker
    3312            0 :             .lock()
    3313            0 :             .unwrap()
    3314            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3315              : 
    3316            0 :         match has_pending {
    3317            0 :             true => Ok(CompactionOutcome::Pending),
    3318            0 :             false => Ok(CompactionOutcome::Done),
    3319              :         }
    3320            0 :     }
    3321              : 
    3322              :     /// Trips the compaction circuit breaker if appropriate.
    3323            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3324            0 :         if err.is_cancel() {
    3325            0 :             return;
    3326            0 :         }
    3327            0 :         self.compaction_circuit_breaker
    3328            0 :             .lock()
    3329            0 :             .unwrap()
    3330            0 :             .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3331            0 :     }
    3332              : 
    3333              :     /// Cancel scheduled compaction tasks
    3334            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3335            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3336            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3337            0 :             q.cancel_scheduled();
    3338            0 :         }
    3339            0 :     }
    3340              : 
    3341            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3342            0 :         &self,
    3343            0 :         timeline_id: TimelineId,
    3344            0 :     ) -> Vec<CompactInfoResponse> {
    3345            0 :         let res = {
    3346            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3347            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3348              :         };
    3349            0 :         let Some((running, remaining)) = res else {
    3350            0 :             return Vec::new();
    3351              :         };
    3352            0 :         let mut result = Vec::new();
    3353            0 :         if let Some((id, running)) = running {
    3354            0 :             result.extend(running.into_compact_info_resp(id, true));
    3355            0 :         }
    3356            0 :         for (id, job) in remaining {
    3357            0 :             result.extend(job.into_compact_info_resp(id, false));
    3358            0 :         }
    3359            0 :         result
    3360            0 :     }
    3361              : 
    3362              :     /// Schedule a compaction task for a timeline.
    3363            0 :     pub(crate) async fn schedule_compaction(
    3364            0 :         &self,
    3365            0 :         timeline_id: TimelineId,
    3366            0 :         options: CompactOptions,
    3367            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3368            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3369            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3370            0 :         let q = guard
    3371            0 :             .entry(timeline_id)
    3372            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3373            0 :         q.schedule_manual_compaction(options, Some(tx));
    3374            0 :         Ok(rx)
    3375            0 :     }
    3376              : 
    3377              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3378            0 :     async fn housekeeping(&self) {
    3379              :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3380              :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3381              :         //
    3382              :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3383              :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3384              :         // layers that won't be compacted down.
    3385            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3386            0 :             let timelines = self
    3387            0 :                 .timelines
    3388            0 :                 .lock()
    3389            0 :                 .unwrap()
    3390            0 :                 .values()
    3391            0 :                 .filter(|tli| tli.is_active())
    3392            0 :                 .cloned()
    3393            0 :                 .collect_vec();
    3394              : 
    3395            0 :             for timeline in timelines {
    3396              :                 // Include a span with the timeline ID. The parent span already has the tenant ID.
    3397            0 :                 let span =
    3398            0 :                     info_span!("maybe_freeze_ephemeral_layer", timeline_id = %timeline.timeline_id);
    3399            0 :                 timeline
    3400            0 :                     .maybe_freeze_ephemeral_layer()
    3401            0 :                     .instrument(span)
    3402            0 :                     .await;
    3403              :             }
    3404            0 :         }
    3405              : 
    3406              :         // Shut down walredo if idle.
    3407              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3408            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3409            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3410            0 :         }
    3411              : 
    3412              :         // Update the feature resolver with the latest tenant-spcific data.
    3413            0 :         self.feature_resolver.refresh_properties_and_flags(self);
    3414            0 :     }
    3415              : 
    3416            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3417            0 :         let timelines = self.timelines.lock().unwrap();
    3418            0 :         !timelines
    3419            0 :             .iter()
    3420            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3421            0 :     }
    3422              : 
    3423         1371 :     pub fn current_state(&self) -> TenantState {
    3424         1371 :         self.state.borrow().clone()
    3425         1371 :     }
    3426              : 
    3427          990 :     pub fn is_active(&self) -> bool {
    3428          990 :         self.current_state() == TenantState::Active
    3429          990 :     }
    3430              : 
    3431            0 :     pub fn generation(&self) -> Generation {
    3432            0 :         self.generation
    3433            0 :     }
    3434              : 
    3435            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3436            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3437            0 :     }
    3438              : 
    3439              :     /// Changes tenant status to active, unless shutdown was already requested.
    3440              :     ///
    3441              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3442              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3443            0 :     fn activate(
    3444            0 :         self: &Arc<Self>,
    3445            0 :         broker_client: BrokerClientChannel,
    3446            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3447            0 :         ctx: &RequestContext,
    3448            0 :     ) {
    3449            0 :         span::debug_assert_current_span_has_tenant_id();
    3450              : 
    3451            0 :         let mut activating = false;
    3452            0 :         self.state.send_modify(|current_state| {
    3453              :             use pageserver_api::models::ActivatingFrom;
    3454            0 :             match &*current_state {
    3455              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3456            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {current_state:?}");
    3457              :                 }
    3458            0 :                 TenantState::Attaching => {
    3459            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3460            0 :                 }
    3461              :             }
    3462            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3463            0 :             activating = true;
    3464              :             // Continue outside the closure. We need to grab timelines.lock()
    3465              :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3466            0 :         });
    3467              : 
    3468            0 :         if activating {
    3469            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3470            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3471            0 :             let timelines_to_activate = timelines_accessor
    3472            0 :                 .values()
    3473            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3474              : 
    3475              :             // Spawn gc and compaction loops. The loops will shut themselves
    3476              :             // down when they notice that the tenant is inactive.
    3477            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3478              : 
    3479            0 :             let mut activated_timelines = 0;
    3480              : 
    3481            0 :             for timeline in timelines_to_activate {
    3482            0 :                 timeline.activate(
    3483            0 :                     self.clone(),
    3484            0 :                     broker_client.clone(),
    3485            0 :                     background_jobs_can_start,
    3486            0 :                     &ctx.with_scope_timeline(timeline),
    3487            0 :                 );
    3488            0 :                 activated_timelines += 1;
    3489            0 :             }
    3490              : 
    3491            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3492            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3493            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3494            0 :             TENANT_OFFLOADED_TIMELINES
    3495            0 :                 .with_label_values(&[&tid, &shard_id])
    3496            0 :                 .set(offloaded_timeline_count as u64);
    3497              : 
    3498            0 :             self.state.send_modify(move |current_state| {
    3499            0 :                 assert!(
    3500            0 :                     matches!(current_state, TenantState::Activating(_)),
    3501            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3502              :                 );
    3503            0 :                 *current_state = TenantState::Active;
    3504              : 
    3505            0 :                 let elapsed = self.constructed_at.elapsed();
    3506            0 :                 let total_timelines = timelines_accessor.len();
    3507              : 
    3508              :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3509              :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3510            0 :                 info!(
    3511            0 :                     since_creation_millis = elapsed.as_millis(),
    3512            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3513            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3514              :                     activated_timelines,
    3515              :                     total_timelines,
    3516            0 :                     post_state = <&'static str>::from(&*current_state),
    3517            0 :                     "activation attempt finished"
    3518              :                 );
    3519              : 
    3520            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3521            0 :             });
    3522            0 :         }
    3523            0 :     }
    3524              : 
    3525              :     /// Shutdown the tenant and join all of the spawned tasks.
    3526              :     ///
    3527              :     /// The method caters for all use-cases:
    3528              :     /// - pageserver shutdown (freeze_and_flush == true)
    3529              :     /// - detach + ignore (freeze_and_flush == false)
    3530              :     ///
    3531              :     /// This will attempt to shutdown even if tenant is broken.
    3532              :     ///
    3533              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3534              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3535              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3536              :     /// the ongoing shutdown.
    3537            3 :     async fn shutdown(
    3538            3 :         &self,
    3539            3 :         shutdown_progress: completion::Barrier,
    3540            3 :         shutdown_mode: timeline::ShutdownMode,
    3541            3 :     ) -> Result<(), completion::Barrier> {
    3542            3 :         span::debug_assert_current_span_has_tenant_id();
    3543              : 
    3544              :         // Set tenant (and its timlines) to Stoppping state.
    3545              :         //
    3546              :         // Since we can only transition into Stopping state after activation is complete,
    3547              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3548              :         //
    3549              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3550              :         // 1. Lock out any new requests to the tenants.
    3551              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3552              :         // 3. Signal cancellation for other tenant background loops.
    3553              :         // 4. ???
    3554              :         //
    3555              :         // The waiting for the cancellation is not done uniformly.
    3556              :         // We certainly wait for WAL receivers to shut down.
    3557              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3558              :         // But the tenant background loops are joined-on in our caller.
    3559              :         // It's mesed up.
    3560              :         // we just ignore the failure to stop
    3561              : 
    3562              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3563              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3564              :         // is very slow.
    3565            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3566            0 :             self.cancel.cancel();
    3567              : 
    3568              :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3569              :             // are children of ours, so their flush loops will have shut down already
    3570            0 :             timeline::ShutdownMode::Hard
    3571              :         } else {
    3572            3 :             shutdown_mode
    3573              :         };
    3574              : 
    3575            3 :         match self.set_stopping(shutdown_progress).await {
    3576            3 :             Ok(()) => {}
    3577            0 :             Err(SetStoppingError::Broken) => {
    3578            0 :                 // assume that this is acceptable
    3579            0 :             }
    3580            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3581              :                 // give caller the option to wait for this this shutdown
    3582            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3583            0 :                 return Err(other);
    3584              :             }
    3585              :         };
    3586              : 
    3587            3 :         let mut js = tokio::task::JoinSet::new();
    3588              :         {
    3589            3 :             let timelines = self.timelines.lock().unwrap();
    3590            3 :             timelines.values().for_each(|timeline| {
    3591            3 :                 let timeline = Arc::clone(timeline);
    3592            3 :                 let timeline_id = timeline.timeline_id;
    3593            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3594            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3595            3 :             });
    3596              :         }
    3597              :         {
    3598            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3599            3 :             timelines_offloaded.values().for_each(|timeline| {
    3600            0 :                 timeline.defuse_for_tenant_drop();
    3601            0 :             });
    3602              :         }
    3603              :         {
    3604            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3605            3 :             timelines_importing
    3606            3 :                 .drain()
    3607            3 :                 .for_each(|(timeline_id, importing_timeline)| {
    3608            0 :                     let span = tracing::info_span!("importing_timeline_shutdown", %timeline_id);
    3609            0 :                     js.spawn(async move { importing_timeline.shutdown().instrument(span).await });
    3610            0 :                 });
    3611              :         }
    3612              :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3613            3 :         tracing::info!("Waiting for timelines...");
    3614            6 :         while let Some(res) = js.join_next().await {
    3615            0 :             match res {
    3616            3 :                 Ok(()) => {}
    3617            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3618            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3619            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3620              :             }
    3621              :         }
    3622              : 
    3623            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3624            0 :             tracing::info!("Flushing deletion queue");
    3625            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3626            0 :                 match e {
    3627            0 :                     DeletionQueueError::ShuttingDown => {
    3628            0 :                         // This is the only error we expect for now. In the future, if more error
    3629            0 :                         // variants are added, we should handle them here.
    3630            0 :                     }
    3631              :                 }
    3632            0 :             }
    3633            3 :         }
    3634              : 
    3635              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3636              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3637            3 :         tracing::debug!("Cancelling CancellationToken");
    3638            3 :         self.cancel.cancel();
    3639              : 
    3640              :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3641              :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3642              :         //
    3643              :         // this will additionally shutdown and await all timeline tasks.
    3644            3 :         tracing::debug!("Waiting for tasks...");
    3645            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3646              : 
    3647            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3648            3 :             walredo_mgr.shutdown().await;
    3649            0 :         }
    3650              : 
    3651              :         // Wait for any in-flight operations to complete
    3652            3 :         self.gate.close().await;
    3653              : 
    3654            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3655              : 
    3656            3 :         Ok(())
    3657            3 :     }
    3658              : 
    3659              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3660              :     ///
    3661              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3662              :     ///
    3663              :     /// This function is not cancel-safe!
    3664            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3665            3 :         let mut rx = self.state.subscribe();
    3666              : 
    3667              :         // cannot stop before we're done activating, so wait out until we're done activating
    3668            3 :         rx.wait_for(|state| match state {
    3669              :             TenantState::Activating(_) | TenantState::Attaching => {
    3670            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3671            0 :                 false
    3672              :             }
    3673            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3674            3 :         })
    3675            3 :         .await
    3676            3 :         .expect("cannot drop self.state while on a &self method");
    3677              : 
    3678              :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3679            3 :         let mut err = None;
    3680            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3681              :             TenantState::Activating(_) | TenantState::Attaching => {
    3682            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3683              :             }
    3684              :             TenantState::Active => {
    3685              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3686              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3687              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3688            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3689              :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3690              :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3691            3 :                 true
    3692              :             }
    3693              :             TenantState::Stopping { progress: None } => {
    3694              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3695              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3696            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3697            0 :                 true
    3698              :             }
    3699            0 :             TenantState::Broken { reason, .. } => {
    3700            0 :                 info!(
    3701            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3702              :                 );
    3703            0 :                 err = Some(SetStoppingError::Broken);
    3704            0 :                 false
    3705              :             }
    3706            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3707            0 :                 info!("Tenant is already in Stopping state");
    3708            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3709            0 :                 false
    3710              :             }
    3711            3 :         });
    3712            3 :         match (stopping, err) {
    3713            3 :             (true, None) => {} // continue
    3714            0 :             (false, Some(err)) => return Err(err),
    3715            0 :             (true, Some(_)) => unreachable!(
    3716              :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3717              :             ),
    3718            0 :             (false, None) => unreachable!(
    3719              :                 "send_if_modified closure must return true if transitioning to Stopping"
    3720              :             ),
    3721              :         }
    3722              : 
    3723            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3724            3 :         let not_broken_timelines = timelines_accessor
    3725            3 :             .values()
    3726            3 :             .filter(|timeline| !timeline.is_broken());
    3727            6 :         for timeline in not_broken_timelines {
    3728            3 :             timeline.set_state(TimelineState::Stopping);
    3729            3 :         }
    3730            3 :         Ok(())
    3731            3 :     }
    3732              : 
    3733              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3734              :     /// `remove_tenant_from_memory`
    3735              :     ///
    3736              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3737              :     ///
    3738              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3739            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3740            0 :         let mut rx = self.state.subscribe();
    3741              : 
    3742              :         // The load & attach routines own the tenant state until it has reached `Active`.
    3743              :         // So, wait until it's done.
    3744            0 :         rx.wait_for(|state| match state {
    3745              :             TenantState::Activating(_) | TenantState::Attaching => {
    3746            0 :                 info!(
    3747            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3748            0 :                     <&'static str>::from(state)
    3749              :                 );
    3750            0 :                 false
    3751              :             }
    3752            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3753            0 :         })
    3754            0 :         .await
    3755            0 :         .expect("cannot drop self.state while on a &self method");
    3756              : 
    3757              :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3758            0 :         self.set_broken_no_wait(reason)
    3759            0 :     }
    3760              : 
    3761            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3762            0 :         let reason = reason.to_string();
    3763            0 :         self.state.send_modify(|current_state| {
    3764            0 :             match *current_state {
    3765              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3766            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3767              :                 }
    3768              :                 TenantState::Active => {
    3769            0 :                     if cfg!(feature = "testing") {
    3770            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3771            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3772              :                     } else {
    3773            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3774              :                     }
    3775              :                 }
    3776              :                 TenantState::Broken { .. } => {
    3777            0 :                     warn!("Tenant is already in Broken state");
    3778              :                 }
    3779              :                 // This is the only "expected" path, any other path is a bug.
    3780              :                 TenantState::Stopping { .. } => {
    3781            0 :                     warn!(
    3782            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3783              :                         reason
    3784              :                     );
    3785            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3786              :                 }
    3787              :            }
    3788            0 :         });
    3789            0 :     }
    3790              : 
    3791            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3792            0 :         self.state.subscribe()
    3793            0 :     }
    3794              : 
    3795              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3796              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3797            0 :     pub(crate) fn activate_now(&self) {
    3798            0 :         self.activate_now_sem.add_permits(1);
    3799            0 :     }
    3800              : 
    3801            0 :     pub(crate) async fn wait_to_become_active(
    3802            0 :         &self,
    3803            0 :         timeout: Duration,
    3804            0 :     ) -> Result<(), GetActiveTenantError> {
    3805            0 :         let mut receiver = self.state.subscribe();
    3806              :         loop {
    3807            0 :             let current_state = receiver.borrow_and_update().clone();
    3808            0 :             match current_state {
    3809              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3810              :                     // in these states, there's a chance that we can reach ::Active
    3811            0 :                     self.activate_now();
    3812            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3813            0 :                         Ok(r) => {
    3814            0 :                             r.map_err(
    3815              :                             |_e: tokio::sync::watch::error::RecvError|
    3816              :                                 // Tenant existed but was dropped: report it as non-existent
    3817            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3818            0 :                         )?
    3819              :                         }
    3820              :                         Err(TimeoutCancellableError::Cancelled) => {
    3821            0 :                             return Err(GetActiveTenantError::Cancelled);
    3822              :                         }
    3823              :                         Err(TimeoutCancellableError::Timeout) => {
    3824            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3825            0 :                                 latest_state: Some(self.current_state()),
    3826            0 :                                 wait_time: timeout,
    3827            0 :                             });
    3828              :                         }
    3829              :                     }
    3830              :                 }
    3831              :                 TenantState::Active => {
    3832            0 :                     return Ok(());
    3833              :                 }
    3834            0 :                 TenantState::Broken { reason, .. } => {
    3835              :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3836              :                     // it's logically a 500 to external API users (broken is always a bug).
    3837            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3838              :                 }
    3839              :                 TenantState::Stopping { .. } => {
    3840              :                     // There's no chance the tenant can transition back into ::Active
    3841            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3842              :                 }
    3843              :             }
    3844              :         }
    3845            0 :     }
    3846              : 
    3847            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3848            0 :         self.tenant_conf.load().location.attach_mode
    3849            0 :     }
    3850              : 
    3851              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3852              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3853              :     /// rare external API calls, like a reconciliation at startup.
    3854            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3855            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3856              : 
    3857            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3858            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3859            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3860            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3861              :         };
    3862              : 
    3863            0 :         models::LocationConfig {
    3864            0 :             mode: location_config_mode,
    3865            0 :             generation: self.generation.into(),
    3866            0 :             secondary_conf: None,
    3867            0 :             shard_number: self.shard_identity.number.0,
    3868            0 :             shard_count: self.shard_identity.count.literal(),
    3869            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3870            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3871            0 :         }
    3872            0 :     }
    3873              : 
    3874            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3875            0 :         &self.tenant_shard_id
    3876            0 :     }
    3877              : 
    3878            0 :     pub(crate) fn get_shard_identity(&self) -> ShardIdentity {
    3879            0 :         self.shard_identity
    3880            0 :     }
    3881              : 
    3882          120 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3883          120 :         self.shard_identity.stripe_size
    3884          120 :     }
    3885              : 
    3886            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3887            0 :         self.generation
    3888            0 :     }
    3889              : 
    3890              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3891              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3892              :     /// resetting this tenant to a valid state if we fail.
    3893            0 :     pub(crate) async fn split_prepare(
    3894            0 :         &self,
    3895            0 :         child_shards: &Vec<TenantShardId>,
    3896            0 :     ) -> anyhow::Result<()> {
    3897            0 :         let (timelines, offloaded) = {
    3898            0 :             let timelines = self.timelines.lock().unwrap();
    3899            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3900            0 :             (timelines.clone(), offloaded.clone())
    3901            0 :         };
    3902            0 :         let timelines_iter = timelines
    3903            0 :             .values()
    3904            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3905            0 :             .chain(
    3906            0 :                 offloaded
    3907            0 :                     .values()
    3908            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3909              :             );
    3910            0 :         for timeline in timelines_iter {
    3911              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3912              :             // to ensure that they do not start a split if currently in the process of doing these.
    3913              : 
    3914            0 :             let timeline_id = timeline.timeline_id();
    3915              : 
    3916            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3917              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3918              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3919              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3920            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3921            0 :                 timeline
    3922            0 :                     .remote_client
    3923            0 :                     .schedule_index_upload_for_file_changes()?;
    3924            0 :                 timeline.remote_client.wait_completion().await?;
    3925            0 :             }
    3926              : 
    3927            0 :             let remote_client = match timeline {
    3928            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3929            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3930            0 :                     let remote_client = self
    3931            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3932            0 :                     Arc::new(remote_client)
    3933              :                 }
    3934              :                 TimelineOrOffloadedArcRef::Importing(_) => {
    3935            0 :                     unreachable!("Importing timelines are not included in the iterator")
    3936              :                 }
    3937              :             };
    3938              : 
    3939              :             // Shut down the timeline's remote client: this means that the indices we write
    3940              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3941            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3942            0 :             remote_client.shutdown().await;
    3943              : 
    3944              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3945              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3946              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3947              :             // we use here really is the remotely persistent one).
    3948            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3949            0 :             let result = remote_client
    3950            0 :                 .download_index_file(&self.cancel)
    3951            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))
    3952            0 :                 .await?;
    3953            0 :             let index_part = match result {
    3954              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3955            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3956              :                 }
    3957            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3958              :             };
    3959              : 
    3960              :             // A shard split may not take place while a timeline import is on-going
    3961              :             // for the tenant. Timeline imports run as part of each tenant shard
    3962              :             // and rely on the sharding scheme to split the work among pageservers.
    3963              :             // If we were to split in the middle of this process, we would have to
    3964              :             // either ensure that it's driven to completion on the old shard set
    3965              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3966            0 :             match index_part.import_pgdata {
    3967            0 :                 Some(ref import) if !import.is_done() => {
    3968            0 :                     anyhow::bail!(
    3969            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3970            0 :                         import.idempotency_key()
    3971              :                     );
    3972              :                 }
    3973            0 :                 Some(_) | None => {
    3974            0 :                     // fallthrough
    3975            0 :                 }
    3976              :             }
    3977              : 
    3978            0 :             for child_shard in child_shards {
    3979            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3980            0 :                 upload_index_part(
    3981            0 :                     &self.remote_storage,
    3982            0 :                     child_shard,
    3983            0 :                     &timeline_id,
    3984            0 :                     self.generation,
    3985            0 :                     &index_part,
    3986            0 :                     &self.cancel,
    3987            0 :                 )
    3988            0 :                 .await?;
    3989              :             }
    3990              :         }
    3991              : 
    3992            0 :         let tenant_manifest = self.build_tenant_manifest();
    3993            0 :         for child_shard in child_shards {
    3994            0 :             tracing::info!(
    3995            0 :                 "Uploading tenant manifest for child {}",
    3996            0 :                 child_shard.to_index()
    3997              :             );
    3998            0 :             upload_tenant_manifest(
    3999            0 :                 &self.remote_storage,
    4000            0 :                 child_shard,
    4001            0 :                 self.generation,
    4002            0 :                 &tenant_manifest,
    4003            0 :                 &self.cancel,
    4004            0 :             )
    4005            0 :             .await?;
    4006              :         }
    4007              : 
    4008            0 :         Ok(())
    4009            0 :     }
    4010              : 
    4011            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    4012            0 :         let mut result = TopTenantShardItem {
    4013            0 :             id: self.tenant_shard_id,
    4014            0 :             resident_size: 0,
    4015            0 :             physical_size: 0,
    4016            0 :             max_logical_size: 0,
    4017            0 :             max_logical_size_per_shard: 0,
    4018            0 :         };
    4019              : 
    4020            0 :         for timeline in self.timelines.lock().unwrap().values() {
    4021            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    4022            0 : 
    4023            0 :             result.physical_size += timeline
    4024            0 :                 .remote_client
    4025            0 :                 .metrics
    4026            0 :                 .remote_physical_size_gauge
    4027            0 :                 .get();
    4028            0 :             result.max_logical_size = std::cmp::max(
    4029            0 :                 result.max_logical_size,
    4030            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    4031            0 :             );
    4032            0 :         }
    4033              : 
    4034            0 :         result.max_logical_size_per_shard = result
    4035            0 :             .max_logical_size
    4036            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    4037              : 
    4038            0 :         result
    4039            0 :     }
    4040              : }
    4041              : 
    4042              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    4043              : /// perform a topological sort, so that the parent of each timeline comes
    4044              : /// before the children.
    4045              : /// E extracts the ancestor from T
    4046              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    4047          119 : fn tree_sort_timelines<T, E>(
    4048          119 :     timelines: HashMap<TimelineId, T>,
    4049          119 :     extractor: E,
    4050          119 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    4051          119 : where
    4052          119 :     E: Fn(&T) -> Option<TimelineId>,
    4053              : {
    4054          119 :     let mut result = Vec::with_capacity(timelines.len());
    4055              : 
    4056          119 :     let mut now = Vec::with_capacity(timelines.len());
    4057              :     // (ancestor, children)
    4058          119 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    4059          119 :         HashMap::with_capacity(timelines.len());
    4060              : 
    4061          122 :     for (timeline_id, value) in timelines {
    4062            3 :         if let Some(ancestor_id) = extractor(&value) {
    4063            1 :             let children = later.entry(ancestor_id).or_default();
    4064            1 :             children.push((timeline_id, value));
    4065            2 :         } else {
    4066            2 :             now.push((timeline_id, value));
    4067            2 :         }
    4068              :     }
    4069              : 
    4070          122 :     while let Some((timeline_id, metadata)) = now.pop() {
    4071            3 :         result.push((timeline_id, metadata));
    4072              :         // All children of this can be loaded now
    4073            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    4074            1 :             now.append(&mut children);
    4075            2 :         }
    4076              :     }
    4077              : 
    4078              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    4079          119 :     if !later.is_empty() {
    4080            0 :         for (missing_id, orphan_ids) in later {
    4081            0 :             for (orphan_id, _) in orphan_ids {
    4082            0 :                 error!(
    4083            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    4084              :                 );
    4085              :             }
    4086              :         }
    4087            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    4088          119 :     }
    4089              : 
    4090          119 :     Ok(result)
    4091          119 : }
    4092              : 
    4093              : impl TenantShard {
    4094            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    4095            0 :         self.tenant_conf.load().tenant_conf.clone()
    4096            0 :     }
    4097              : 
    4098            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    4099            0 :         self.tenant_specific_overrides()
    4100            0 :             .merge(self.conf.default_tenant_conf.clone())
    4101            0 :     }
    4102              : 
    4103            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    4104            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4105            0 :         tenant_conf
    4106            0 :             .checkpoint_distance
    4107            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    4108            0 :     }
    4109              : 
    4110            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    4111            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4112            0 :         tenant_conf
    4113            0 :             .checkpoint_timeout
    4114            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    4115            0 :     }
    4116              : 
    4117            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    4118            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4119            0 :         tenant_conf
    4120            0 :             .compaction_target_size
    4121            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    4122            0 :     }
    4123              : 
    4124            0 :     pub fn get_compaction_period(&self) -> Duration {
    4125            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4126            0 :         tenant_conf
    4127            0 :             .compaction_period
    4128            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    4129            0 :     }
    4130              : 
    4131            0 :     pub fn get_compaction_threshold(&self) -> usize {
    4132            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4133            0 :         tenant_conf
    4134            0 :             .compaction_threshold
    4135            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4136            0 :     }
    4137              : 
    4138            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4139            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4140            0 :         tenant_conf
    4141            0 :             .rel_size_v2_enabled
    4142            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4143            0 :     }
    4144              : 
    4145            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4146            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4147            0 :         tenant_conf
    4148            0 :             .compaction_upper_limit
    4149            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4150            0 :     }
    4151              : 
    4152            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4153            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4154            0 :         tenant_conf
    4155            0 :             .compaction_l0_first
    4156            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4157            0 :     }
    4158              : 
    4159          121 :     pub fn get_gc_horizon(&self) -> u64 {
    4160          121 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4161          121 :         tenant_conf
    4162          121 :             .gc_horizon
    4163          121 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4164          121 :     }
    4165              : 
    4166            0 :     pub fn get_gc_period(&self) -> Duration {
    4167            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4168            0 :         tenant_conf
    4169            0 :             .gc_period
    4170            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4171            0 :     }
    4172              : 
    4173            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4174            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4175            0 :         tenant_conf
    4176            0 :             .image_creation_threshold
    4177            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4178            0 :     }
    4179              : 
    4180              :     // HADRON
    4181            0 :     pub fn get_image_creation_timeout(&self) -> Option<Duration> {
    4182            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4183            0 :         tenant_conf.image_layer_force_creation_period.or(self
    4184            0 :             .conf
    4185            0 :             .default_tenant_conf
    4186            0 :             .image_layer_force_creation_period)
    4187            0 :     }
    4188              : 
    4189            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4190            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4191            2 :         tenant_conf
    4192            2 :             .pitr_interval
    4193            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4194            2 :     }
    4195              : 
    4196            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4197            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4198            0 :         tenant_conf
    4199            0 :             .min_resident_size_override
    4200            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4201            0 :     }
    4202              : 
    4203            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4204            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4205            0 :         let heatmap_period = tenant_conf
    4206            0 :             .heatmap_period
    4207            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4208            0 :         if heatmap_period.is_zero() {
    4209            0 :             None
    4210              :         } else {
    4211            0 :             Some(heatmap_period)
    4212              :         }
    4213            0 :     }
    4214              : 
    4215            0 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4216            0 :         Self::get_lsn_lease_length_impl(self.conf, &self.tenant_conf.load().tenant_conf)
    4217            0 :     }
    4218              : 
    4219          119 :     pub fn get_lsn_lease_length_impl(
    4220          119 :         conf: &'static PageServerConf,
    4221          119 :         tenant_conf: &pageserver_api::models::TenantConfig,
    4222          119 :     ) -> Duration {
    4223          119 :         tenant_conf
    4224          119 :             .lsn_lease_length
    4225          119 :             .unwrap_or(conf.default_tenant_conf.lsn_lease_length)
    4226          119 :     }
    4227              : 
    4228            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4229            0 :         if self.conf.timeline_offloading {
    4230            0 :             return true;
    4231            0 :         }
    4232            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4233            0 :         tenant_conf
    4234            0 :             .timeline_offloading
    4235            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4236            0 :     }
    4237              : 
    4238              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4239          120 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4240              :         // Collect the offloaded timelines, and sort them for deterministic output.
    4241          120 :         let offloaded_timelines = self
    4242          120 :             .timelines_offloaded
    4243          120 :             .lock()
    4244          120 :             .unwrap()
    4245          120 :             .values()
    4246          120 :             .map(|tli| tli.manifest())
    4247          120 :             .sorted_by_key(|m| m.timeline_id)
    4248          120 :             .collect_vec();
    4249              : 
    4250          120 :         TenantManifest {
    4251          120 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4252          120 :             stripe_size: Some(self.get_shard_stripe_size()),
    4253          120 :             offloaded_timelines,
    4254          120 :         }
    4255          120 :     }
    4256              : 
    4257            1 :     pub fn update_tenant_config<
    4258            1 :         F: Fn(
    4259            1 :             pageserver_api::models::TenantConfig,
    4260            1 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4261            1 :     >(
    4262            1 :         &self,
    4263            1 :         update: F,
    4264            1 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4265              :         // Use read-copy-update in order to avoid overwriting the location config
    4266              :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4267              :         // this race is not possible if both request types come from the storage
    4268              :         // controller (as they should!) because an exclusive op lock is required
    4269              :         // on the storage controller side.
    4270              : 
    4271            1 :         self.tenant_conf
    4272            1 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4273            1 :                 Ok(Arc::new(AttachedTenantConf {
    4274            1 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4275            1 :                     location: attached_conf.location,
    4276            1 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4277              :                 }))
    4278            1 :             })?;
    4279              : 
    4280            1 :         let updated = self.tenant_conf.load();
    4281              : 
    4282            1 :         self.tenant_conf_updated(&updated.tenant_conf);
    4283              :         // Don't hold self.timelines.lock() during the notifies.
    4284              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4285              :         // mutexes in struct Timeline in the future.
    4286            1 :         let timelines = self.list_timelines();
    4287            1 :         for timeline in timelines {
    4288            0 :             timeline.tenant_conf_updated(&updated);
    4289            0 :         }
    4290              : 
    4291            1 :         Ok(updated.tenant_conf.clone())
    4292            1 :     }
    4293              : 
    4294            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4295            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4296              : 
    4297            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4298              : 
    4299            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4300              :         // Don't hold self.timelines.lock() during the notifies.
    4301              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4302              :         // mutexes in struct Timeline in the future.
    4303            0 :         let timelines = self.list_timelines();
    4304            0 :         for timeline in timelines {
    4305            0 :             timeline.tenant_conf_updated(&new_conf);
    4306            0 :         }
    4307            0 :     }
    4308              : 
    4309          120 :     fn get_pagestream_throttle_config(
    4310          120 :         psconf: &'static PageServerConf,
    4311          120 :         overrides: &pageserver_api::models::TenantConfig,
    4312          120 :     ) -> throttle::Config {
    4313          120 :         overrides
    4314          120 :             .timeline_get_throttle
    4315          120 :             .clone()
    4316          120 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4317          120 :     }
    4318              : 
    4319            1 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4320            1 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4321            1 :         self.pagestream_throttle.reconfigure(conf)
    4322            1 :     }
    4323              : 
    4324              :     /// Helper function to create a new Timeline struct.
    4325              :     ///
    4326              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4327              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4328              :     /// map.
    4329              :     ///
    4330              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4331              :     /// and we might not have the ancestor present anymore which is fine for to be
    4332              :     /// deleted timelines.
    4333              :     #[allow(clippy::too_many_arguments)]
    4334          235 :     fn create_timeline_struct(
    4335          235 :         &self,
    4336          235 :         new_timeline_id: TimelineId,
    4337          235 :         new_metadata: &TimelineMetadata,
    4338          235 :         previous_heatmap: Option<PreviousHeatmap>,
    4339          235 :         ancestor: Option<Arc<Timeline>>,
    4340          235 :         resources: TimelineResources,
    4341          235 :         cause: CreateTimelineCause,
    4342          235 :         create_idempotency: CreateTimelineIdempotency,
    4343          235 :         gc_compaction_state: Option<GcCompactionState>,
    4344          235 :         rel_size_v2_status: Option<RelSizeMigration>,
    4345          235 :         ctx: &RequestContext,
    4346          235 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4347          235 :         let state = match cause {
    4348              :             CreateTimelineCause::Load => {
    4349          235 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4350          235 :                 anyhow::ensure!(
    4351          235 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4352            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4353              :                 );
    4354          235 :                 TimelineState::Loading
    4355              :             }
    4356            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4357              :         };
    4358              : 
    4359          235 :         let pg_version = new_metadata.pg_version();
    4360              : 
    4361          235 :         let timeline = Timeline::new(
    4362          235 :             self.conf,
    4363          235 :             Arc::clone(&self.tenant_conf),
    4364          235 :             new_metadata,
    4365          235 :             previous_heatmap,
    4366          235 :             ancestor,
    4367          235 :             new_timeline_id,
    4368          235 :             self.tenant_shard_id,
    4369          235 :             self.generation,
    4370          235 :             self.shard_identity,
    4371          235 :             self.walredo_mgr.clone(),
    4372          235 :             resources,
    4373          235 :             pg_version,
    4374          235 :             state,
    4375          235 :             self.attach_wal_lag_cooldown.clone(),
    4376          235 :             create_idempotency,
    4377          235 :             gc_compaction_state,
    4378          235 :             rel_size_v2_status,
    4379          235 :             self.cancel.child_token(),
    4380              :         );
    4381              : 
    4382          235 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4383          235 :             .scope(context::Scope::new_timeline(&timeline))
    4384          235 :             .detached_child();
    4385              : 
    4386          235 :         Ok((timeline, timeline_ctx))
    4387          235 :     }
    4388              : 
    4389              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4390              :     /// to ensure proper cleanup of background tasks and metrics.
    4391              :     //
    4392              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4393              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4394              :     #[allow(clippy::too_many_arguments)]
    4395          119 :     fn new(
    4396          119 :         state: TenantState,
    4397          119 :         conf: &'static PageServerConf,
    4398          119 :         attached_conf: AttachedTenantConf,
    4399          119 :         shard_identity: ShardIdentity,
    4400          119 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4401          119 :         tenant_shard_id: TenantShardId,
    4402          119 :         remote_storage: GenericRemoteStorage,
    4403          119 :         deletion_queue_client: DeletionQueueClient,
    4404          119 :         l0_flush_global_state: L0FlushGlobalState,
    4405          119 :         basebackup_cache: Arc<BasebackupCache>,
    4406          119 :         feature_resolver: FeatureResolver,
    4407          119 :     ) -> TenantShard {
    4408          119 :         assert!(!attached_conf.location.generation.is_none());
    4409              : 
    4410          119 :         let (state, mut rx) = watch::channel(state);
    4411              : 
    4412          119 :         tokio::spawn(async move {
    4413              :             // reflect tenant state in metrics:
    4414              :             // - global per tenant state: TENANT_STATE_METRIC
    4415              :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4416              :             //
    4417              :             // set of broken tenants should not have zero counts so that it remains accessible for
    4418              :             // alerting.
    4419              : 
    4420          118 :             let tid = tenant_shard_id.to_string();
    4421          118 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4422          118 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4423              : 
    4424          236 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4425          236 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4426          236 :             }
    4427              : 
    4428          118 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4429              : 
    4430          118 :             let is_broken = tuple.1;
    4431          118 :             let mut counted_broken = if is_broken {
    4432              :                 // add the id to the set right away, there should not be any updates on the channel
    4433              :                 // after before tenant is removed, if ever
    4434            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4435            0 :                 true
    4436              :             } else {
    4437          118 :                 false
    4438              :             };
    4439              : 
    4440              :             loop {
    4441          236 :                 let labels = &tuple.0;
    4442          236 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4443          236 :                 current.inc();
    4444              : 
    4445          236 :                 if rx.changed().await.is_err() {
    4446              :                     // tenant has been dropped
    4447            7 :                     current.dec();
    4448            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4449            7 :                     break;
    4450          118 :                 }
    4451              : 
    4452          118 :                 current.dec();
    4453          118 :                 tuple = inspect_state(&rx.borrow_and_update());
    4454              : 
    4455          118 :                 let is_broken = tuple.1;
    4456          118 :                 if is_broken && !counted_broken {
    4457            0 :                     counted_broken = true;
    4458            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4459            0 :                     // access
    4460            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4461          118 :                 }
    4462              :             }
    4463            7 :         });
    4464              : 
    4465          119 :         TenantShard {
    4466          119 :             tenant_shard_id,
    4467          119 :             shard_identity,
    4468          119 :             generation: attached_conf.location.generation,
    4469          119 :             conf,
    4470          119 :             // using now here is good enough approximation to catch tenants with really long
    4471          119 :             // activation times.
    4472          119 :             constructed_at: Instant::now(),
    4473          119 :             timelines: Mutex::new(HashMap::new()),
    4474          119 :             timelines_creating: Mutex::new(HashSet::new()),
    4475          119 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4476          119 :             timelines_importing: Mutex::new(HashMap::new()),
    4477          119 :             remote_tenant_manifest: Default::default(),
    4478          119 :             gc_cs: tokio::sync::Mutex::new(()),
    4479          119 :             walredo_mgr,
    4480          119 :             remote_storage,
    4481          119 :             deletion_queue_client,
    4482          119 :             state,
    4483          119 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4484          119 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4485          119 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4486          119 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4487          119 :                 format!("compaction-{tenant_shard_id}"),
    4488          119 :                 5,
    4489          119 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4490          119 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4491          119 :                 // use an extremely long backoff.
    4492          119 :                 Some(Duration::from_secs(3600 * 24)),
    4493          119 :             )),
    4494          119 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4495          119 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4496          119 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4497          119 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4498          119 :             cancel: CancellationToken::default(),
    4499          119 :             gate: Gate::default(),
    4500          119 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4501          119 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4502          119 :             )),
    4503          119 :             pagestream_throttle_metrics: Arc::new(
    4504          119 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4505          119 :             ),
    4506          119 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4507          119 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4508          119 :             gc_block: Default::default(),
    4509          119 :             l0_flush_global_state,
    4510          119 :             basebackup_cache,
    4511          119 :             feature_resolver: Arc::new(TenantFeatureResolver::new(
    4512          119 :                 feature_resolver,
    4513          119 :                 tenant_shard_id.tenant_id,
    4514          119 :             )),
    4515          119 :         }
    4516          119 :     }
    4517              : 
    4518              :     /// Locate and load config
    4519            0 :     pub(super) fn load_tenant_config(
    4520            0 :         conf: &'static PageServerConf,
    4521            0 :         tenant_shard_id: &TenantShardId,
    4522            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4523            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4524              : 
    4525            0 :         info!("loading tenant configuration from {config_path}");
    4526              : 
    4527              :         // load and parse file
    4528            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4529            0 :             match e.kind() {
    4530              :                 std::io::ErrorKind::NotFound => {
    4531              :                     // The config should almost always exist for a tenant directory:
    4532              :                     //  - When attaching a tenant, the config is the first thing we write
    4533              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4534              :                     //    before deleting contents.
    4535              :                     //
    4536              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4537              :                     // between creating directory and writing config.  Callers should handle that as if the
    4538              :                     // directory didn't exist.
    4539              : 
    4540            0 :                     LoadConfigError::NotFound(config_path)
    4541              :                 }
    4542              :                 _ => {
    4543              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4544              :                     // that we cannot cleanly recover
    4545            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4546              :                 }
    4547              :             }
    4548            0 :         })?;
    4549              : 
    4550            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4551            0 :     }
    4552              : 
    4553              :     /// Stores a tenant location config to disk.
    4554              :     ///
    4555              :     /// NB: make sure to call `ShardIdentity::assert_equal` before persisting a new config, to avoid
    4556              :     /// changes to shard parameters that may result in data corruption.
    4557              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4558              :     pub(super) async fn persist_tenant_config(
    4559              :         conf: &'static PageServerConf,
    4560              :         tenant_shard_id: &TenantShardId,
    4561              :         location_conf: &LocationConf,
    4562              :     ) -> std::io::Result<()> {
    4563              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4564              : 
    4565              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4566              :     }
    4567              : 
    4568              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4569              :     pub(super) async fn persist_tenant_config_at(
    4570              :         tenant_shard_id: &TenantShardId,
    4571              :         config_path: &Utf8Path,
    4572              :         location_conf: &LocationConf,
    4573              :     ) -> std::io::Result<()> {
    4574              :         debug!("persisting tenantconf to {config_path}");
    4575              : 
    4576              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4577              : #  It is read in case of pageserver restart.
    4578              : "#
    4579              :         .to_string();
    4580              : 
    4581            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4582            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4583            0 :         });
    4584              : 
    4585              :         // Convert the config to a toml file.
    4586              :         conf_content +=
    4587              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4588              : 
    4589              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4590              : 
    4591              :         let conf_content = conf_content.into_bytes();
    4592              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4593              :     }
    4594              : 
    4595              :     //
    4596              :     // How garbage collection works:
    4597              :     //
    4598              :     //                    +--bar------------->
    4599              :     //                   /
    4600              :     //             +----+-----foo---------------->
    4601              :     //            /
    4602              :     // ----main--+-------------------------->
    4603              :     //                \
    4604              :     //                 +-----baz-------->
    4605              :     //
    4606              :     //
    4607              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4608              :     //    `gc_infos` are being refreshed
    4609              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4610              :     //    all the points where other timelines have been branched off.
    4611              :     //    We will refrain from removing page versions at those LSNs.
    4612              :     // 3. For each timeline, scan all layer files on the timeline.
    4613              :     //    Remove all files for which a newer file exists and which
    4614              :     //    don't cover any branch point LSNs.
    4615              :     //
    4616              :     // TODO:
    4617              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4618              :     //   don't need to keep that in the parent anymore. But currently
    4619              :     //   we do.
    4620          377 :     async fn gc_iteration_internal(
    4621          377 :         &self,
    4622          377 :         target_timeline_id: Option<TimelineId>,
    4623          377 :         horizon: u64,
    4624          377 :         pitr: Duration,
    4625          377 :         cancel: &CancellationToken,
    4626          377 :         ctx: &RequestContext,
    4627          377 :     ) -> Result<GcResult, GcError> {
    4628          377 :         let mut totals: GcResult = Default::default();
    4629          377 :         let now = Instant::now();
    4630              : 
    4631          377 :         let gc_timelines = self
    4632          377 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4633          377 :             .await?;
    4634              : 
    4635          377 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4636              : 
    4637              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4638          377 :         if !gc_timelines.is_empty() {
    4639          377 :             info!("{} timelines need GC", gc_timelines.len());
    4640              :         } else {
    4641            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4642              :         }
    4643              : 
    4644              :         // Perform GC for each timeline.
    4645              :         //
    4646              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4647              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4648              :         // with branch creation.
    4649              :         //
    4650              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4651              :         // creation task can run concurrently with timeline's GC iteration.
    4652          754 :         for timeline in gc_timelines {
    4653          377 :             if cancel.is_cancelled() {
    4654              :                 // We were requested to shut down. Stop and return with the progress we
    4655              :                 // made.
    4656            0 :                 break;
    4657          377 :             }
    4658          377 :             let result = match timeline.gc().await {
    4659              :                 Err(GcError::TimelineCancelled) => {
    4660            0 :                     if target_timeline_id.is_some() {
    4661              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4662            0 :                         return Err(GcError::TimelineCancelled);
    4663              :                     } else {
    4664              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4665              :                         // skip past this and proceed to try GC on other timelines.
    4666            0 :                         continue;
    4667              :                     }
    4668              :                 }
    4669          377 :                 r => r?,
    4670              :             };
    4671          377 :             totals += result;
    4672              :         }
    4673              : 
    4674          377 :         totals.elapsed = now.elapsed();
    4675          377 :         Ok(totals)
    4676          377 :     }
    4677              : 
    4678              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4679              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4680              :     /// [`TenantShard::get_gc_horizon`].
    4681              :     ///
    4682              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4683            2 :     pub(crate) async fn refresh_gc_info(
    4684            2 :         &self,
    4685            2 :         cancel: &CancellationToken,
    4686            2 :         ctx: &RequestContext,
    4687            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4688              :         // since this method can now be called at different rates than the configured gc loop, it
    4689              :         // might be that these configuration values get applied faster than what it was previously,
    4690              :         // since these were only read from the gc task.
    4691            2 :         let horizon = self.get_gc_horizon();
    4692            2 :         let pitr = self.get_pitr_interval();
    4693              : 
    4694              :         // refresh all timelines
    4695            2 :         let target_timeline_id = None;
    4696              : 
    4697            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4698            2 :             .await
    4699            2 :     }
    4700              : 
    4701              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4702              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4703              :     ///
    4704              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4705          119 :     fn initialize_gc_info(
    4706          119 :         &self,
    4707          119 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4708          119 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4709          119 :         restrict_to_timeline: Option<TimelineId>,
    4710          119 :     ) {
    4711          119 :         if restrict_to_timeline.is_none() {
    4712              :             // This function must be called before activation: after activation timeline create/delete operations
    4713              :             // might happen, and this function is not safe to run concurrently with those.
    4714          119 :             assert!(!self.is_active());
    4715            0 :         }
    4716              : 
    4717              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4718              :         // the branch point where it was created.
    4719          119 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4720          119 :             BTreeMap::new();
    4721          119 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4722            3 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4723            1 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4724            1 :                 ancestor_children.push((
    4725            1 :                     timeline_entry.get_ancestor_lsn(),
    4726            1 :                     *timeline_id,
    4727            1 :                     MaybeOffloaded::No,
    4728            1 :                 ));
    4729            2 :             }
    4730            3 :         });
    4731          119 :         timelines_offloaded
    4732          119 :             .iter()
    4733          119 :             .for_each(|(timeline_id, timeline_entry)| {
    4734            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4735            0 :                     return;
    4736              :                 };
    4737            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4738            0 :                     return;
    4739              :                 };
    4740            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4741            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4742            0 :             });
    4743              : 
    4744              :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4745          119 :         let horizon = self.get_gc_horizon();
    4746              : 
    4747              :         // Populate each timeline's GcInfo with information about its child branches
    4748          119 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4749            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4750              :         } else {
    4751          119 :             itertools::Either::Right(timelines.values())
    4752              :         };
    4753          122 :         for timeline in timelines_to_write {
    4754            3 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4755            3 :                 .remove(&timeline.timeline_id)
    4756            3 :                 .unwrap_or_default();
    4757              : 
    4758            3 :             branchpoints.sort_by_key(|b| b.0);
    4759              : 
    4760            3 :             let mut target = timeline.gc_info.write().unwrap();
    4761              : 
    4762            3 :             target.retain_lsns = branchpoints;
    4763              : 
    4764            3 :             let space_cutoff = timeline
    4765            3 :                 .get_last_record_lsn()
    4766            3 :                 .checked_sub(horizon)
    4767            3 :                 .unwrap_or(Lsn(0));
    4768              : 
    4769            3 :             target.cutoffs = GcCutoffs {
    4770            3 :                 space: space_cutoff,
    4771            3 :                 time: None,
    4772            3 :             };
    4773              :         }
    4774          119 :     }
    4775              : 
    4776          379 :     async fn refresh_gc_info_internal(
    4777          379 :         &self,
    4778          379 :         target_timeline_id: Option<TimelineId>,
    4779          379 :         horizon: u64,
    4780          379 :         pitr: Duration,
    4781          379 :         cancel: &CancellationToken,
    4782          379 :         ctx: &RequestContext,
    4783          379 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4784              :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4785              :         // currently visible timelines.
    4786          379 :         let timelines = self
    4787          379 :             .timelines
    4788          379 :             .lock()
    4789          379 :             .unwrap()
    4790          379 :             .values()
    4791         1663 :             .filter(|tl| match target_timeline_id.as_ref() {
    4792         1655 :                 Some(target) => &tl.timeline_id == target,
    4793            8 :                 None => true,
    4794         1663 :             })
    4795          379 :             .cloned()
    4796          379 :             .collect::<Vec<_>>();
    4797              : 
    4798          379 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4799              :             // We were to act on a particular timeline and it wasn't found
    4800            0 :             return Err(GcError::TimelineNotFound);
    4801          379 :         }
    4802              : 
    4803          379 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4804          379 :             HashMap::with_capacity(timelines.len());
    4805              : 
    4806              :         // Ensures all timelines use the same start time when computing the time cutoff.
    4807          379 :         let now_ts_for_pitr_calc = SystemTime::now();
    4808          385 :         for timeline in timelines.iter() {
    4809          385 :             let ctx = &ctx.with_scope_timeline(timeline);
    4810          385 :             let cutoff = timeline
    4811          385 :                 .get_last_record_lsn()
    4812          385 :                 .checked_sub(horizon)
    4813          385 :                 .unwrap_or(Lsn(0));
    4814              : 
    4815          385 :             let cutoffs = timeline
    4816          385 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4817          385 :                 .await?;
    4818          385 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4819          385 :             assert!(old.is_none());
    4820              :         }
    4821              : 
    4822          379 :         if !self.is_active() || self.cancel.is_cancelled() {
    4823            0 :             return Err(GcError::TenantCancelled);
    4824          379 :         }
    4825              : 
    4826              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4827              :         // because that will stall branch creation.
    4828          379 :         let gc_cs = self.gc_cs.lock().await;
    4829              : 
    4830              :         // Ok, we now know all the branch points.
    4831              :         // Update the GC information for each timeline.
    4832          379 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4833          764 :         for timeline in timelines {
    4834              :             // We filtered the timeline list above
    4835          385 :             if let Some(target_timeline_id) = target_timeline_id {
    4836          377 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4837            8 :             }
    4838              : 
    4839              :             {
    4840          385 :                 let mut target = timeline.gc_info.write().unwrap();
    4841              : 
    4842              :                 // Cull any expired leases
    4843          385 :                 let now = SystemTime::now();
    4844          385 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4845              : 
    4846          385 :                 timeline
    4847          385 :                     .metrics
    4848          385 :                     .valid_lsn_lease_count_gauge
    4849          385 :                     .set(target.leases.len() as u64);
    4850              : 
    4851              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4852          385 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4853           56 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4854            6 :                         target.within_ancestor_pitr =
    4855            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4856           50 :                     }
    4857          329 :                 }
    4858              : 
    4859              :                 // Update metrics that depend on GC state
    4860          385 :                 timeline
    4861          385 :                     .metrics
    4862          385 :                     .archival_size
    4863          385 :                     .set(if target.within_ancestor_pitr {
    4864            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4865              :                     } else {
    4866          385 :                         0
    4867              :                     });
    4868          385 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4869          319 :                     timeline.metrics.pitr_history_size.set(
    4870          319 :                         timeline
    4871          319 :                             .get_last_record_lsn()
    4872          319 :                             .checked_sub(time_cutoff)
    4873          319 :                             .unwrap_or_default()
    4874          319 :                             .0,
    4875          319 :                     );
    4876          319 :                 }
    4877              : 
    4878              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4879              :                 // - this timeline was created while we were finding cutoffs
    4880              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4881          385 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4882          385 :                     let original_cutoffs = target.cutoffs.clone();
    4883              :                     // GC cutoffs should never go back
    4884          385 :                     target.cutoffs = GcCutoffs {
    4885          385 :                         space: cutoffs.space.max(original_cutoffs.space),
    4886          385 :                         time: cutoffs.time.max(original_cutoffs.time),
    4887          385 :                     }
    4888            0 :                 }
    4889              :             }
    4890              : 
    4891          385 :             gc_timelines.push(timeline);
    4892              :         }
    4893          379 :         drop(gc_cs);
    4894          379 :         Ok(gc_timelines)
    4895          379 :     }
    4896              : 
    4897              :     /// A substitute for `branch_timeline` for use in unit tests.
    4898              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4899              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4900              :     /// timeline background tasks are launched, except the flush loop.
    4901              :     #[cfg(test)]
    4902          119 :     async fn branch_timeline_test(
    4903          119 :         self: &Arc<Self>,
    4904          119 :         src_timeline: &Arc<Timeline>,
    4905          119 :         dst_id: TimelineId,
    4906          119 :         ancestor_lsn: Option<Lsn>,
    4907          119 :         ctx: &RequestContext,
    4908          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4909          119 :         let tl = self
    4910          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4911          119 :             .await?
    4912          117 :             .into_timeline_for_test();
    4913          117 :         tl.set_state(TimelineState::Active);
    4914          117 :         Ok(tl)
    4915          119 :     }
    4916              : 
    4917              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4918              :     #[cfg(test)]
    4919              :     #[allow(clippy::too_many_arguments)]
    4920            6 :     pub async fn branch_timeline_test_with_layers(
    4921            6 :         self: &Arc<Self>,
    4922            6 :         src_timeline: &Arc<Timeline>,
    4923            6 :         dst_id: TimelineId,
    4924            6 :         ancestor_lsn: Option<Lsn>,
    4925            6 :         ctx: &RequestContext,
    4926            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4927            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4928            6 :         end_lsn: Lsn,
    4929            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4930              :         use checks::check_valid_layermap;
    4931              :         use itertools::Itertools;
    4932              : 
    4933            6 :         let tline = self
    4934            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4935            6 :             .await?;
    4936            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4937            6 :             ancestor_lsn
    4938              :         } else {
    4939            0 :             tline.get_last_record_lsn()
    4940              :         };
    4941            6 :         assert!(end_lsn >= ancestor_lsn);
    4942            6 :         tline.force_advance_lsn(end_lsn);
    4943            9 :         for deltas in delta_layer_desc {
    4944            3 :             tline
    4945            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4946            3 :                 .await?;
    4947              :         }
    4948            8 :         for (lsn, images) in image_layer_desc {
    4949            2 :             tline
    4950            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4951            2 :                 .await?;
    4952              :         }
    4953            6 :         let layer_names = tline
    4954            6 :             .layers
    4955            6 :             .read(LayerManagerLockHolder::Testing)
    4956            6 :             .await
    4957            6 :             .layer_map()
    4958            6 :             .unwrap()
    4959            6 :             .iter_historic_layers()
    4960            6 :             .map(|layer| layer.layer_name())
    4961            6 :             .collect_vec();
    4962            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4963            0 :             bail!("invalid layermap: {err}");
    4964            6 :         }
    4965            6 :         Ok(tline)
    4966            6 :     }
    4967              : 
    4968              :     /// Branch an existing timeline.
    4969            0 :     async fn branch_timeline(
    4970            0 :         self: &Arc<Self>,
    4971            0 :         src_timeline: &Arc<Timeline>,
    4972            0 :         dst_id: TimelineId,
    4973            0 :         start_lsn: Option<Lsn>,
    4974            0 :         ctx: &RequestContext,
    4975            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4976            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4977            0 :             .await
    4978            0 :     }
    4979              : 
    4980          119 :     async fn branch_timeline_impl(
    4981          119 :         self: &Arc<Self>,
    4982          119 :         src_timeline: &Arc<Timeline>,
    4983          119 :         dst_id: TimelineId,
    4984          119 :         start_lsn: Option<Lsn>,
    4985          119 :         ctx: &RequestContext,
    4986          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4987          119 :         let src_id = src_timeline.timeline_id;
    4988              : 
    4989              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4990              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4991              :         // valid while we are creating the branch.
    4992          119 :         let _gc_cs = self.gc_cs.lock().await;
    4993              : 
    4994              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4995          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4996            1 :             let lsn = src_timeline.get_last_record_lsn();
    4997            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4998            1 :             lsn
    4999            1 :         });
    5000              : 
    5001              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    5002          119 :         let timeline_create_guard = match self
    5003          119 :             .start_creating_timeline(
    5004          119 :                 dst_id,
    5005          119 :                 CreateTimelineIdempotency::Branch {
    5006          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    5007          119 :                     ancestor_start_lsn: start_lsn,
    5008          119 :                 },
    5009          119 :             )
    5010          119 :             .await?
    5011              :         {
    5012          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5013            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5014            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5015              :             }
    5016              :         };
    5017              : 
    5018              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    5019              :         // horizon on the source timeline
    5020              :         //
    5021              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    5022              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    5023              :         // planned GC cutoff in 'gc_info' is normally larger than
    5024              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    5025              :         // changed the GC settings for the tenant to make the PITR window
    5026              :         // larger, but some of the data was already removed by an earlier GC
    5027              :         // iteration.
    5028              : 
    5029              :         // check against last actual 'latest_gc_cutoff' first
    5030          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    5031              :         {
    5032          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    5033          119 :             let planned_cutoff = gc_info.min_cutoff();
    5034          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    5035            0 :                 tracing::info!(
    5036            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    5037            0 :                     *applied_gc_cutoff_lsn
    5038              :                 );
    5039              :             } else {
    5040          119 :                 src_timeline
    5041          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    5042          119 :                     .context(format!(
    5043          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    5044          119 :                         *applied_gc_cutoff_lsn,
    5045              :                     ))
    5046          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    5047              : 
    5048              :                 // and then the planned GC cutoff
    5049          117 :                 if start_lsn < planned_cutoff {
    5050            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    5051            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    5052            0 :                     )));
    5053          117 :                 }
    5054              :             }
    5055              :         }
    5056              : 
    5057              :         //
    5058              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    5059              :         // so that GC cannot advance the GC cutoff until we are finished.
    5060              :         // Proceed with the branch creation.
    5061              :         //
    5062              : 
    5063              :         // Determine prev-LSN for the new timeline. We can only determine it if
    5064              :         // the timeline was branched at the current end of the source timeline.
    5065              :         let RecordLsn {
    5066          117 :             last: src_last,
    5067          117 :             prev: src_prev,
    5068          117 :         } = src_timeline.get_last_record_rlsn();
    5069          117 :         let dst_prev = if src_last == start_lsn {
    5070          108 :             Some(src_prev)
    5071              :         } else {
    5072            9 :             None
    5073              :         };
    5074              : 
    5075              :         // Create the metadata file, noting the ancestor of the new timeline.
    5076              :         // There is initially no data in it, but all the read-calls know to look
    5077              :         // into the ancestor.
    5078          117 :         let metadata = TimelineMetadata::new(
    5079          117 :             start_lsn,
    5080          117 :             dst_prev,
    5081          117 :             Some(src_id),
    5082          117 :             start_lsn,
    5083          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    5084          117 :             src_timeline.initdb_lsn,
    5085          117 :             src_timeline.pg_version,
    5086              :         );
    5087              : 
    5088          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    5089          117 :             .prepare_new_timeline(
    5090          117 :                 dst_id,
    5091          117 :                 &metadata,
    5092          117 :                 timeline_create_guard,
    5093          117 :                 start_lsn + 1,
    5094          117 :                 Some(Arc::clone(src_timeline)),
    5095          117 :                 Some(src_timeline.get_rel_size_v2_status()),
    5096          117 :                 ctx,
    5097          117 :             )
    5098          117 :             .await?;
    5099              : 
    5100          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    5101              : 
    5102              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    5103              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    5104              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    5105              :         // could get incorrect information and remove more layers, than needed.
    5106              :         // See also https://github.com/neondatabase/neon/issues/3865
    5107          117 :         new_timeline
    5108          117 :             .remote_client
    5109          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    5110          117 :             .context("branch initial metadata upload")?;
    5111              : 
    5112              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5113              : 
    5114          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    5115          119 :     }
    5116              : 
    5117              :     /// For unit tests, make this visible so that other modules can directly create timelines
    5118              :     #[cfg(test)]
    5119              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    5120              :     pub(crate) async fn bootstrap_timeline_test(
    5121              :         self: &Arc<Self>,
    5122              :         timeline_id: TimelineId,
    5123              :         pg_version: PgMajorVersion,
    5124              :         load_existing_initdb: Option<TimelineId>,
    5125              :         ctx: &RequestContext,
    5126              :     ) -> anyhow::Result<Arc<Timeline>> {
    5127              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    5128              :             .await
    5129              :             .map_err(anyhow::Error::new)
    5130            1 :             .map(|r| r.into_timeline_for_test())
    5131              :     }
    5132              : 
    5133              :     /// Get exclusive access to the timeline ID for creation.
    5134              :     ///
    5135              :     /// Timeline-creating code paths must use this function before making changes
    5136              :     /// to in-memory or persistent state.
    5137              :     ///
    5138              :     /// The `state` parameter is a description of the timeline creation operation
    5139              :     /// we intend to perform.
    5140              :     /// If the timeline was already created in the meantime, we check whether this
    5141              :     /// request conflicts or is idempotent , based on `state`.
    5142          235 :     async fn start_creating_timeline(
    5143          235 :         self: &Arc<Self>,
    5144          235 :         new_timeline_id: TimelineId,
    5145          235 :         idempotency: CreateTimelineIdempotency,
    5146          235 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    5147          235 :         let allow_offloaded = false;
    5148          235 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    5149          234 :             Ok(create_guard) => {
    5150          234 :                 pausable_failpoint!("timeline-creation-after-uninit");
    5151          234 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    5152              :             }
    5153            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    5154              :             Err(TimelineExclusionError::AlreadyCreating) => {
    5155              :                 // Creation is in progress, we cannot create it again, and we cannot
    5156              :                 // check if this request matches the existing one, so caller must try
    5157              :                 // again later.
    5158            0 :                 Err(CreateTimelineError::AlreadyCreating)
    5159              :             }
    5160            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    5161              :             Err(TimelineExclusionError::AlreadyExists {
    5162            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5163              :                 ..
    5164              :             }) => {
    5165            0 :                 info!("timeline already exists but is offloaded");
    5166            0 :                 Err(CreateTimelineError::Conflict)
    5167              :             }
    5168              :             Err(TimelineExclusionError::AlreadyExists {
    5169            0 :                 existing: TimelineOrOffloaded::Importing(_existing),
    5170              :                 ..
    5171              :             }) => {
    5172              :                 // If there's a timeline already importing, then we would hit
    5173              :                 // the [`TimelineExclusionError::AlreadyCreating`] branch above.
    5174            0 :                 unreachable!("Importing timelines hold the creation guard")
    5175              :             }
    5176              :             Err(TimelineExclusionError::AlreadyExists {
    5177            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5178            1 :                 arg,
    5179              :             }) => {
    5180              :                 {
    5181            1 :                     let existing = &existing.create_idempotency;
    5182            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5183            1 :                     debug!("timeline already exists");
    5184              : 
    5185            1 :                     match (existing, &arg) {
    5186              :                         // FailWithConflict => no idempotency check
    5187              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5188              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5189            1 :                             warn!("timeline already exists, failing request");
    5190            1 :                             return Err(CreateTimelineError::Conflict);
    5191              :                         }
    5192              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5193            0 :                         (x, y) if x == y => {
    5194            0 :                             info!(
    5195            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5196              :                             );
    5197              :                             // fallthrough
    5198              :                         }
    5199              :                         (_, _) => {
    5200            0 :                             warn!("idempotency conflict, failing request");
    5201            0 :                             return Err(CreateTimelineError::Conflict);
    5202              :                         }
    5203              :                     }
    5204              :                 }
    5205              : 
    5206            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5207              :             }
    5208              :         }
    5209          235 :     }
    5210              : 
    5211            0 :     async fn upload_initdb(
    5212            0 :         &self,
    5213            0 :         timelines_path: &Utf8PathBuf,
    5214            0 :         pgdata_path: &Utf8PathBuf,
    5215            0 :         timeline_id: &TimelineId,
    5216            0 :     ) -> anyhow::Result<()> {
    5217            0 :         let temp_path = timelines_path.join(format!(
    5218            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5219            0 :         ));
    5220              : 
    5221            0 :         scopeguard::defer! {
    5222              :             if let Err(e) = fs::remove_file(&temp_path) {
    5223              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5224              :             }
    5225              :         }
    5226              : 
    5227            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5228              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5229            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5230            0 :             warn!(
    5231            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5232              :             );
    5233            0 :         }
    5234              : 
    5235            0 :         pausable_failpoint!("before-initdb-upload");
    5236              : 
    5237            0 :         backoff::retry(
    5238            0 :             || async {
    5239            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5240            0 :                     &self.remote_storage,
    5241            0 :                     &self.tenant_shard_id.tenant_id,
    5242            0 :                     timeline_id,
    5243            0 :                     pgdata_zstd.try_clone().await?,
    5244            0 :                     tar_zst_size,
    5245            0 :                     &self.cancel,
    5246              :                 )
    5247            0 :                 .await
    5248            0 :             },
    5249              :             |_| false,
    5250              :             3,
    5251              :             u32::MAX,
    5252            0 :             "persist_initdb_tar_zst",
    5253            0 :             &self.cancel,
    5254              :         )
    5255            0 :         .await
    5256            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5257            0 :         .and_then(|x| x)
    5258            0 :     }
    5259              : 
    5260              :     /// - run initdb to init temporary instance and get bootstrap data
    5261              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5262            1 :     async fn bootstrap_timeline(
    5263            1 :         self: &Arc<Self>,
    5264            1 :         timeline_id: TimelineId,
    5265            1 :         pg_version: PgMajorVersion,
    5266            1 :         load_existing_initdb: Option<TimelineId>,
    5267            1 :         ctx: &RequestContext,
    5268            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5269            1 :         let timeline_create_guard = match self
    5270            1 :             .start_creating_timeline(
    5271            1 :                 timeline_id,
    5272            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5273            1 :             )
    5274            1 :             .await?
    5275              :         {
    5276            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5277            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5278            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5279              :             }
    5280              :         };
    5281              : 
    5282              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5283              :         // temporary directory for basebackup files for the given timeline.
    5284              : 
    5285            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5286            1 :         let pgdata_path = path_with_suffix_extension(
    5287            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5288            1 :             TEMP_FILE_SUFFIX,
    5289              :         );
    5290              : 
    5291              :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5292              :         // we won't race with other creations or existent timelines with the same path.
    5293            1 :         if pgdata_path.exists() {
    5294            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5295            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5296            0 :             })?;
    5297            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5298            1 :         }
    5299              : 
    5300              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5301            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5302            1 :         scopeguard::defer! {
    5303              :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5304              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5305              :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5306              :             } else {
    5307              :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5308              :             }
    5309              :         }
    5310            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5311            1 :             if existing_initdb_timeline_id != timeline_id {
    5312            0 :                 let source_path = &remote_initdb_archive_path(
    5313            0 :                     &self.tenant_shard_id.tenant_id,
    5314            0 :                     &existing_initdb_timeline_id,
    5315            0 :                 );
    5316            0 :                 let dest_path =
    5317            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5318              : 
    5319              :                 // if this fails, it will get retried by retried control plane requests
    5320            0 :                 self.remote_storage
    5321            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5322            0 :                     .await
    5323            0 :                     .context("copy initdb tar")?;
    5324            1 :             }
    5325            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5326            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5327            1 :                     self.conf,
    5328            1 :                     &self.remote_storage,
    5329            1 :                     &self.tenant_shard_id,
    5330            1 :                     &existing_initdb_timeline_id,
    5331            1 :                     &self.cancel,
    5332            1 :                 )
    5333            1 :                 .await
    5334            1 :                 .context("download initdb tar")?;
    5335              : 
    5336            1 :             scopeguard::defer! {
    5337              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5338              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5339              :                 }
    5340              :             }
    5341              : 
    5342            1 :             let buf_read =
    5343            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5344            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5345            1 :                 .await
    5346            1 :                 .context("extract initdb tar")?;
    5347              :         } else {
    5348              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5349            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5350            0 :                 .await
    5351            0 :                 .context("run initdb")?;
    5352              : 
    5353              :             // Upload the created data dir to S3
    5354            0 :             if self.tenant_shard_id().is_shard_zero() {
    5355            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5356            0 :                     .await?;
    5357            0 :             }
    5358              :         }
    5359            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5360              : 
    5361              :         // Import the contents of the data directory at the initial checkpoint
    5362              :         // LSN, and any WAL after that.
    5363              :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5364              :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5365            1 :         let new_metadata = TimelineMetadata::new(
    5366            1 :             Lsn(0),
    5367            1 :             None,
    5368            1 :             None,
    5369            1 :             Lsn(0),
    5370            1 :             pgdata_lsn,
    5371            1 :             pgdata_lsn,
    5372            1 :             pg_version,
    5373              :         );
    5374            1 :         let (mut raw_timeline, timeline_ctx) = self
    5375            1 :             .prepare_new_timeline(
    5376            1 :                 timeline_id,
    5377            1 :                 &new_metadata,
    5378            1 :                 timeline_create_guard,
    5379            1 :                 pgdata_lsn,
    5380            1 :                 None,
    5381            1 :                 None,
    5382            1 :                 ctx,
    5383            1 :             )
    5384            1 :             .await?;
    5385              : 
    5386            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5387            1 :         raw_timeline
    5388            1 :             .write(|unfinished_timeline| async move {
    5389            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5390            1 :                     &unfinished_timeline,
    5391            1 :                     &pgdata_path,
    5392            1 :                     pgdata_lsn,
    5393            1 :                     &timeline_ctx,
    5394            1 :                 )
    5395            1 :                 .await
    5396            1 :                 .with_context(|| {
    5397            0 :                     format!(
    5398            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5399              :                     )
    5400            0 :                 })?;
    5401              : 
    5402            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5403            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5404            0 :                         "failpoint before-checkpoint-new-timeline"
    5405            0 :                     )))
    5406            0 :                 });
    5407              : 
    5408            1 :                 Ok(())
    5409            2 :             })
    5410            1 :             .await?;
    5411              : 
    5412              :         // All done!
    5413            1 :         let timeline = raw_timeline.finish_creation().await?;
    5414              : 
    5415              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5416              : 
    5417            1 :         Ok(CreateTimelineResult::Created(timeline))
    5418            1 :     }
    5419              : 
    5420          232 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5421          232 :         RemoteTimelineClient::new(
    5422          232 :             self.remote_storage.clone(),
    5423          232 :             self.deletion_queue_client.clone(),
    5424          232 :             self.conf,
    5425          232 :             self.tenant_shard_id,
    5426          232 :             timeline_id,
    5427          232 :             self.generation,
    5428          232 :             &self.tenant_conf.load().location,
    5429              :         )
    5430          232 :     }
    5431              : 
    5432              :     /// Builds required resources for a new timeline.
    5433          232 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5434          232 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5435          232 :         self.get_timeline_resources_for(remote_client)
    5436          232 :     }
    5437              : 
    5438              :     /// Builds timeline resources for the given remote client.
    5439          235 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5440          235 :         TimelineResources {
    5441          235 :             remote_client,
    5442          235 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5443          235 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5444          235 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5445          235 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5446          235 :             basebackup_cache: self.basebackup_cache.clone(),
    5447          235 :             feature_resolver: self.feature_resolver.clone(),
    5448          235 :         }
    5449          235 :     }
    5450              : 
    5451              :     /// Creates intermediate timeline structure and its files.
    5452              :     ///
    5453              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5454              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5455              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5456              :     #[allow(clippy::too_many_arguments)]
    5457          232 :     async fn prepare_new_timeline<'a>(
    5458          232 :         &'a self,
    5459          232 :         new_timeline_id: TimelineId,
    5460          232 :         new_metadata: &TimelineMetadata,
    5461          232 :         create_guard: TimelineCreateGuard,
    5462          232 :         start_lsn: Lsn,
    5463          232 :         ancestor: Option<Arc<Timeline>>,
    5464          232 :         rel_size_v2_status: Option<RelSizeMigration>,
    5465          232 :         ctx: &RequestContext,
    5466          232 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5467          232 :         let tenant_shard_id = self.tenant_shard_id;
    5468              : 
    5469          232 :         let resources = self.build_timeline_resources(new_timeline_id);
    5470          232 :         resources
    5471          232 :             .remote_client
    5472          232 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5473              : 
    5474          232 :         let (timeline_struct, timeline_ctx) = self
    5475          232 :             .create_timeline_struct(
    5476          232 :                 new_timeline_id,
    5477          232 :                 new_metadata,
    5478          232 :                 None,
    5479          232 :                 ancestor,
    5480          232 :                 resources,
    5481          232 :                 CreateTimelineCause::Load,
    5482          232 :                 create_guard.idempotency.clone(),
    5483          232 :                 None,
    5484          232 :                 rel_size_v2_status,
    5485          232 :                 ctx,
    5486              :             )
    5487          232 :             .context("Failed to create timeline data structure")?;
    5488              : 
    5489          232 :         timeline_struct.init_empty_layer_map(start_lsn);
    5490              : 
    5491          232 :         if let Err(e) = self
    5492          232 :             .create_timeline_files(&create_guard.timeline_path)
    5493          232 :             .await
    5494              :         {
    5495            0 :             error!(
    5496            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5497              :             );
    5498            0 :             cleanup_timeline_directory(create_guard);
    5499            0 :             return Err(e);
    5500          232 :         }
    5501              : 
    5502          232 :         debug!(
    5503            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5504              :         );
    5505              : 
    5506          232 :         Ok((
    5507          232 :             UninitializedTimeline::new(
    5508          232 :                 self,
    5509          232 :                 new_timeline_id,
    5510          232 :                 Some((timeline_struct, create_guard)),
    5511          232 :             ),
    5512          232 :             timeline_ctx,
    5513          232 :         ))
    5514          232 :     }
    5515              : 
    5516          232 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5517          232 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5518              : 
    5519          232 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5520            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5521            0 :         });
    5522              : 
    5523          232 :         Ok(())
    5524          232 :     }
    5525              : 
    5526              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5527              :     /// concurrent attempts to create the same timeline.
    5528              :     ///
    5529              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5530              :     /// offloaded timelines or not.
    5531          235 :     fn create_timeline_create_guard(
    5532          235 :         self: &Arc<Self>,
    5533          235 :         timeline_id: TimelineId,
    5534          235 :         idempotency: CreateTimelineIdempotency,
    5535          235 :         allow_offloaded: bool,
    5536          235 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5537          235 :         let tenant_shard_id = self.tenant_shard_id;
    5538              : 
    5539          235 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5540              : 
    5541          235 :         let create_guard = TimelineCreateGuard::new(
    5542          235 :             self,
    5543          235 :             timeline_id,
    5544          235 :             timeline_path.clone(),
    5545          235 :             idempotency,
    5546          235 :             allow_offloaded,
    5547            1 :         )?;
    5548              : 
    5549              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5550              :         // for creation.
    5551              :         // A timeline directory should never exist on disk already:
    5552              :         // - a previous failed creation would have cleaned up after itself
    5553              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5554              :         //
    5555              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5556              :         // this error may indicate a bug in cleanup on failed creations.
    5557          234 :         if timeline_path.exists() {
    5558            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5559            0 :                 "Timeline directory already exists! This is a bug."
    5560            0 :             )));
    5561          234 :         }
    5562              : 
    5563          234 :         Ok(create_guard)
    5564          235 :     }
    5565              : 
    5566              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5567              :     ///
    5568              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5569              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5570              :     pub async fn gather_size_inputs(
    5571              :         &self,
    5572              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5573              :         // (only if it is shorter than the real cutoff).
    5574              :         max_retention_period: Option<u64>,
    5575              :         cause: LogicalSizeCalculationCause,
    5576              :         cancel: &CancellationToken,
    5577              :         ctx: &RequestContext,
    5578              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5579              :         let logical_sizes_at_once = self
    5580              :             .conf
    5581              :             .concurrent_tenant_size_logical_size_queries
    5582              :             .inner();
    5583              : 
    5584              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5585              :         //
    5586              :         // But the only case where we need to run multiple of these at once is when we
    5587              :         // request a size for a tenant manually via API, while another background calculation
    5588              :         // is in progress (which is not a common case).
    5589              :         //
    5590              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5591              :         let mut shared_cache = tokio::select! {
    5592              :             locked = self.cached_logical_sizes.lock() => locked,
    5593              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5594              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5595              :         };
    5596              : 
    5597              :         size::gather_inputs(
    5598              :             self,
    5599              :             logical_sizes_at_once,
    5600              :             max_retention_period,
    5601              :             &mut shared_cache,
    5602              :             cause,
    5603              :             cancel,
    5604              :             ctx,
    5605              :         )
    5606              :         .await
    5607              :     }
    5608              : 
    5609              :     /// Calculate synthetic tenant size and cache the result.
    5610              :     /// This is periodically called by background worker.
    5611              :     /// result is cached in tenant struct
    5612              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5613              :     pub async fn calculate_synthetic_size(
    5614              :         &self,
    5615              :         cause: LogicalSizeCalculationCause,
    5616              :         cancel: &CancellationToken,
    5617              :         ctx: &RequestContext,
    5618              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5619              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5620              : 
    5621              :         let size = inputs.calculate();
    5622              : 
    5623              :         self.set_cached_synthetic_size(size);
    5624              : 
    5625              :         Ok(size)
    5626              :     }
    5627              : 
    5628              :     /// Cache given synthetic size and update the metric value
    5629            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5630            0 :         self.cached_synthetic_tenant_size
    5631            0 :             .store(size, Ordering::Relaxed);
    5632              : 
    5633              :         // Only shard zero should be calculating synthetic sizes
    5634            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5635              : 
    5636            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5637            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5638            0 :             .unwrap()
    5639            0 :             .set(size);
    5640            0 :     }
    5641              : 
    5642            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5643            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5644            0 :     }
    5645              : 
    5646              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5647              :     ///
    5648              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5649              :     /// from an external API handler.
    5650              :     ///
    5651              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5652              :     /// still bounded by tenant/timeline shutdown.
    5653              :     #[tracing::instrument(skip_all)]
    5654              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5655              :         let timelines = self.timelines.lock().unwrap().clone();
    5656              : 
    5657            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5658            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5659            0 :             timeline.freeze_and_flush().await?;
    5660            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5661            0 :             timeline.remote_client.wait_completion().await?;
    5662              : 
    5663            0 :             Ok(())
    5664            0 :         }
    5665              : 
    5666              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5667              :         // aborted when this function's future is cancelled: they should stay alive
    5668              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5669              :         // before Timeline shutdown completes.
    5670              :         let mut results = FuturesUnordered::new();
    5671              : 
    5672              :         for (_timeline_id, timeline) in timelines {
    5673              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5674              :             // means that if this function's future is cancelled, the Timeline shutdown
    5675              :             // will still wait for any I/O in here to complete.
    5676              :             let Ok(gate) = timeline.gate.enter() else {
    5677              :                 continue;
    5678              :             };
    5679            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5680              :             results.push(jh);
    5681              :         }
    5682              : 
    5683              :         while let Some(r) = results.next().await {
    5684              :             if let Err(e) = r {
    5685              :                 if !e.is_cancelled() && !e.is_panic() {
    5686              :                     tracing::error!("unexpected join error: {e:?}");
    5687              :                 }
    5688              :             }
    5689              :         }
    5690              : 
    5691              :         // The flushes we did above were just writes, but the TenantShard might have had
    5692              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5693              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5694              :         // because it's typically a no-op.
    5695              :         match self.deletion_queue_client.flush_execute().await {
    5696              :             Ok(_) => {}
    5697              :             Err(DeletionQueueError::ShuttingDown) => {}
    5698              :         }
    5699              : 
    5700              :         Ok(())
    5701              :     }
    5702              : 
    5703            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5704            0 :         self.tenant_conf.load().tenant_conf.clone()
    5705            0 :     }
    5706              : 
    5707              :     /// How much local storage would this tenant like to have?  It can cope with
    5708              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5709              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5710              :     /// by keeping important things on local disk.
    5711              :     ///
    5712              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5713              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5714              :     /// actually use more than they report here.
    5715            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5716            0 :         let timelines = self.timelines.lock().unwrap();
    5717              : 
    5718              :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5719              :         // reflects the observation that on tenants with multiple large branches, typically only one
    5720              :         // of them is used actively enough to occupy space on disk.
    5721            0 :         timelines
    5722            0 :             .values()
    5723            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5724            0 :             .max()
    5725            0 :             .unwrap_or(0)
    5726            0 :     }
    5727              : 
    5728              :     /// HADRON
    5729              :     /// Return the visible size of all timelines in this tenant.
    5730            0 :     pub(crate) fn get_visible_size(&self) -> u64 {
    5731            0 :         let timelines = self.timelines.lock().unwrap();
    5732            0 :         timelines
    5733            0 :             .values()
    5734            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5735            0 :             .sum()
    5736            0 :     }
    5737              : 
    5738              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5739              :     /// manifest in `Self::remote_tenant_manifest`.
    5740              :     ///
    5741              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5742              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5743              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5744              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5745          120 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5746              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5747              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5748              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5749              :         // simple coalescing mechanism.
    5750          120 :         let mut guard = tokio::select! {
    5751          120 :             guard = self.remote_tenant_manifest.lock() => guard,
    5752          120 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5753              :         };
    5754              : 
    5755              :         // Build a new manifest.
    5756          120 :         let manifest = self.build_tenant_manifest();
    5757              : 
    5758              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5759              :         // uploading every manifest on version number bumps.
    5760          120 :         if let Some(old) = guard.as_ref() {
    5761            4 :             if manifest.eq_ignoring_version(old) {
    5762            3 :                 return Ok(());
    5763            1 :             }
    5764          116 :         }
    5765              : 
    5766              :         // Update metrics
    5767          117 :         let tid = self.tenant_shard_id.to_string();
    5768          117 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5769          117 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5770          117 :         TENANT_OFFLOADED_TIMELINES
    5771          117 :             .with_label_values(set_key)
    5772          117 :             .set(manifest.offloaded_timelines.len() as u64);
    5773              : 
    5774              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5775          117 :         match backoff::retry(
    5776          117 :             || async {
    5777          117 :                 upload_tenant_manifest(
    5778          117 :                     &self.remote_storage,
    5779          117 :                     &self.tenant_shard_id,
    5780          117 :                     self.generation,
    5781          117 :                     &manifest,
    5782          117 :                     &self.cancel,
    5783          117 :                 )
    5784          117 :                 .await
    5785          234 :             },
    5786            0 :             |_| self.cancel.is_cancelled(),
    5787              :             FAILED_UPLOAD_WARN_THRESHOLD,
    5788              :             FAILED_REMOTE_OP_RETRIES,
    5789          117 :             "uploading tenant manifest",
    5790          117 :             &self.cancel,
    5791              :         )
    5792          117 :         .await
    5793              :         {
    5794            0 :             None => Err(TenantManifestError::Cancelled),
    5795            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5796            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5797              :             Some(Ok(_)) => {
    5798              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5799              :                 // re-uploading the same thing.
    5800          117 :                 *guard = Some(manifest);
    5801              : 
    5802          117 :                 Ok(())
    5803              :             }
    5804              :         }
    5805          120 :     }
    5806              : }
    5807              : 
    5808              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5809              : /// to get bootstrap data for timeline initialization.
    5810            0 : async fn run_initdb(
    5811            0 :     conf: &'static PageServerConf,
    5812            0 :     initdb_target_dir: &Utf8Path,
    5813            0 :     pg_version: PgMajorVersion,
    5814            0 :     cancel: &CancellationToken,
    5815            0 : ) -> Result<(), InitdbError> {
    5816            0 :     let initdb_bin_path = conf
    5817            0 :         .pg_bin_dir(pg_version)
    5818            0 :         .map_err(InitdbError::Other)?
    5819            0 :         .join("initdb");
    5820            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5821            0 :     info!(
    5822            0 :         "running {} in {}, libdir: {}",
    5823              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5824              :     );
    5825              : 
    5826            0 :     let _permit = {
    5827            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5828            0 :         INIT_DB_SEMAPHORE.acquire().await
    5829              :     };
    5830              : 
    5831            0 :     CONCURRENT_INITDBS.inc();
    5832            0 :     scopeguard::defer! {
    5833              :         CONCURRENT_INITDBS.dec();
    5834              :     }
    5835              : 
    5836            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5837            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5838            0 :         superuser: &conf.superuser,
    5839            0 :         locale: &conf.locale,
    5840            0 :         initdb_bin: &initdb_bin_path,
    5841            0 :         pg_version,
    5842            0 :         library_search_path: &initdb_lib_dir,
    5843            0 :         pgdata: initdb_target_dir,
    5844            0 :     })
    5845            0 :     .await
    5846            0 :     .map_err(InitdbError::Inner);
    5847              : 
    5848              :     // This isn't true cancellation support, see above. Still return an error to
    5849              :     // excercise the cancellation code path.
    5850            0 :     if cancel.is_cancelled() {
    5851            0 :         return Err(InitdbError::Cancelled);
    5852            0 :     }
    5853              : 
    5854            0 :     res
    5855            0 : }
    5856              : 
    5857              : /// Dump contents of a layer file to stdout.
    5858            0 : pub async fn dump_layerfile_from_path(
    5859            0 :     path: &Utf8Path,
    5860            0 :     verbose: bool,
    5861            0 :     ctx: &RequestContext,
    5862            0 : ) -> anyhow::Result<()> {
    5863              :     use std::os::unix::fs::FileExt;
    5864              : 
    5865              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5866              :     // file.
    5867            0 :     let file = File::open(path)?;
    5868            0 :     let mut header_buf = [0u8; 2];
    5869            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5870              : 
    5871            0 :     match u16::from_be_bytes(header_buf) {
    5872              :         crate::IMAGE_FILE_MAGIC => {
    5873            0 :             ImageLayer::new_for_path(path, file)?
    5874            0 :                 .dump(verbose, ctx)
    5875            0 :                 .await?
    5876              :         }
    5877              :         crate::DELTA_FILE_MAGIC => {
    5878            0 :             DeltaLayer::new_for_path(path, file)?
    5879            0 :                 .dump(verbose, ctx)
    5880            0 :                 .await?
    5881              :         }
    5882            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5883              :     }
    5884              : 
    5885            0 :     Ok(())
    5886            0 : }
    5887              : 
    5888              : #[cfg(test)]
    5889              : pub(crate) mod harness {
    5890              :     use bytes::{Bytes, BytesMut};
    5891              :     use hex_literal::hex;
    5892              :     use once_cell::sync::OnceCell;
    5893              :     use pageserver_api::key::Key;
    5894              :     use pageserver_api::models::ShardParameters;
    5895              :     use pageserver_api::shard::ShardIndex;
    5896              :     use utils::id::TenantId;
    5897              :     use utils::logging;
    5898              :     use wal_decoder::models::record::NeonWalRecord;
    5899              : 
    5900              :     use super::*;
    5901              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5902              :     use crate::l0_flush::L0FlushConfig;
    5903              :     use crate::walredo::apply_neon;
    5904              : 
    5905              :     pub const TIMELINE_ID: TimelineId =
    5906              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5907              :     pub const NEW_TIMELINE_ID: TimelineId =
    5908              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5909              : 
    5910              :     /// Convenience function to create a page image with given string as the only content
    5911      2514385 :     pub fn test_img(s: &str) -> Bytes {
    5912      2514385 :         let mut buf = BytesMut::new();
    5913      2514385 :         buf.extend_from_slice(s.as_bytes());
    5914      2514385 :         buf.resize(64, 0);
    5915              : 
    5916      2514385 :         buf.freeze()
    5917      2514385 :     }
    5918              : 
    5919              :     pub struct TenantHarness {
    5920              :         pub conf: &'static PageServerConf,
    5921              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5922              :         pub tenant_shard_id: TenantShardId,
    5923              :         pub shard_identity: ShardIdentity,
    5924              :         pub generation: Generation,
    5925              :         pub shard: ShardIndex,
    5926              :         pub remote_storage: GenericRemoteStorage,
    5927              :         pub remote_fs_dir: Utf8PathBuf,
    5928              :         pub deletion_queue: MockDeletionQueue,
    5929              :     }
    5930              : 
    5931              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5932              : 
    5933          131 :     pub(crate) fn setup_logging() {
    5934          131 :         LOG_HANDLE.get_or_init(|| {
    5935          125 :             logging::init(
    5936          125 :                 logging::LogFormat::Test,
    5937              :                 // enable it in case the tests exercise code paths that use
    5938              :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5939          125 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5940          125 :                 logging::Output::Stdout,
    5941              :             )
    5942          125 :             .expect("Failed to init test logging");
    5943          125 :         });
    5944          131 :     }
    5945              : 
    5946              :     impl TenantHarness {
    5947          119 :         pub async fn create_custom(
    5948          119 :             test_name: &'static str,
    5949          119 :             tenant_conf: pageserver_api::models::TenantConfig,
    5950          119 :             tenant_id: TenantId,
    5951          119 :             shard_identity: ShardIdentity,
    5952          119 :             generation: Generation,
    5953          119 :         ) -> anyhow::Result<Self> {
    5954          119 :             setup_logging();
    5955              : 
    5956          119 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5957          119 :             let _ = fs::remove_dir_all(&repo_dir);
    5958          119 :             fs::create_dir_all(&repo_dir)?;
    5959              : 
    5960          119 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5961              :             // Make a static copy of the config. This can never be free'd, but that's
    5962              :             // OK in a test.
    5963          119 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5964              : 
    5965          119 :             let shard = shard_identity.shard_index();
    5966          119 :             let tenant_shard_id = TenantShardId {
    5967          119 :                 tenant_id,
    5968          119 :                 shard_number: shard.shard_number,
    5969          119 :                 shard_count: shard.shard_count,
    5970          119 :             };
    5971          119 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5972          119 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5973              : 
    5974              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5975          119 :             let remote_fs_dir = conf.workdir.join("localfs");
    5976          119 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5977          119 :             let config = RemoteStorageConfig {
    5978          119 :                 storage: RemoteStorageKind::LocalFs {
    5979          119 :                     local_path: remote_fs_dir.clone(),
    5980          119 :                 },
    5981          119 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5982          119 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5983          119 :             };
    5984          119 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5985          119 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5986              : 
    5987          119 :             Ok(Self {
    5988          119 :                 conf,
    5989          119 :                 tenant_conf,
    5990          119 :                 tenant_shard_id,
    5991          119 :                 shard_identity,
    5992          119 :                 generation,
    5993          119 :                 shard,
    5994          119 :                 remote_storage,
    5995          119 :                 remote_fs_dir,
    5996          119 :                 deletion_queue,
    5997          119 :             })
    5998          119 :         }
    5999              : 
    6000          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    6001              :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    6002              :             // The tests perform them manually if needed.
    6003          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    6004          110 :                 gc_period: Some(Duration::ZERO),
    6005          110 :                 compaction_period: Some(Duration::ZERO),
    6006          110 :                 ..Default::default()
    6007          110 :             };
    6008          110 :             let tenant_id = TenantId::generate();
    6009          110 :             let shard = ShardIdentity::unsharded();
    6010          110 :             Self::create_custom(
    6011          110 :                 test_name,
    6012          110 :                 tenant_conf,
    6013          110 :                 tenant_id,
    6014          110 :                 shard,
    6015          110 :                 Generation::new(0xdeadbeef),
    6016          110 :             )
    6017          110 :             .await
    6018          110 :         }
    6019              : 
    6020           10 :         pub fn span(&self) -> tracing::Span {
    6021           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    6022           10 :         }
    6023              : 
    6024          119 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    6025          119 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    6026          119 :                 .with_scope_unit_test();
    6027              :             (
    6028          119 :                 self.do_try_load(&ctx)
    6029          119 :                     .await
    6030          119 :                     .expect("failed to load test tenant"),
    6031          119 :                 ctx,
    6032              :             )
    6033          119 :         }
    6034              : 
    6035              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    6036              :         pub(crate) async fn do_try_load_with_redo(
    6037              :             &self,
    6038              :             walredo_mgr: Arc<WalRedoManager>,
    6039              :             ctx: &RequestContext,
    6040              :         ) -> anyhow::Result<Arc<TenantShard>> {
    6041              :             let (basebackup_cache, _) = BasebackupCache::new(Utf8PathBuf::new(), None);
    6042              : 
    6043              :             let tenant = Arc::new(TenantShard::new(
    6044              :                 TenantState::Attaching,
    6045              :                 self.conf,
    6046              :                 AttachedTenantConf::try_from(
    6047              :                     self.conf,
    6048              :                     LocationConf::attached_single(
    6049              :                         self.tenant_conf.clone(),
    6050              :                         self.generation,
    6051              :                         ShardParameters::default(),
    6052              :                     ),
    6053              :                 )
    6054              :                 .unwrap(),
    6055              :                 self.shard_identity,
    6056              :                 Some(walredo_mgr),
    6057              :                 self.tenant_shard_id,
    6058              :                 self.remote_storage.clone(),
    6059              :                 self.deletion_queue.new_client(),
    6060              :                 // TODO: ideally we should run all unit tests with both configs
    6061              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    6062              :                 basebackup_cache,
    6063              :                 FeatureResolver::new_disabled(),
    6064              :             ));
    6065              : 
    6066              :             let preload = tenant
    6067              :                 .preload(&self.remote_storage, CancellationToken::new())
    6068              :                 .await?;
    6069              :             tenant.attach(Some(preload), ctx).await?;
    6070              : 
    6071              :             tenant.state.send_replace(TenantState::Active);
    6072              :             for timeline in tenant.timelines.lock().unwrap().values() {
    6073              :                 timeline.set_state(TimelineState::Active);
    6074              :             }
    6075              :             Ok(tenant)
    6076              :         }
    6077              : 
    6078          119 :         pub(crate) async fn do_try_load(
    6079          119 :             &self,
    6080          119 :             ctx: &RequestContext,
    6081          119 :         ) -> anyhow::Result<Arc<TenantShard>> {
    6082          119 :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    6083          119 :             self.do_try_load_with_redo(walredo_mgr, ctx).await
    6084          119 :         }
    6085              : 
    6086            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    6087            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    6088            1 :         }
    6089              :     }
    6090              : 
    6091              :     // Mock WAL redo manager that doesn't do much
    6092              :     pub(crate) struct TestRedoManager;
    6093              : 
    6094              :     impl TestRedoManager {
    6095              :         /// # Cancel-Safety
    6096              :         ///
    6097              :         /// This method is cancellation-safe.
    6098        26774 :         pub async fn request_redo(
    6099        26774 :             &self,
    6100        26774 :             key: Key,
    6101        26774 :             lsn: Lsn,
    6102        26774 :             base_img: Option<(Lsn, Bytes)>,
    6103        26774 :             records: Vec<(Lsn, NeonWalRecord)>,
    6104        26774 :             _pg_version: PgMajorVersion,
    6105        26774 :             _redo_attempt_type: RedoAttemptType,
    6106        26774 :         ) -> Result<Bytes, walredo::Error> {
    6107      1403510 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    6108        26774 :             if records_neon {
    6109              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    6110        26774 :                 let mut page = match (base_img, records.first()) {
    6111        13029 :                     (Some((_lsn, img)), _) => {
    6112        13029 :                         let mut page = BytesMut::new();
    6113        13029 :                         page.extend_from_slice(&img);
    6114        13029 :                         page
    6115              :                     }
    6116        13745 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    6117              :                     _ => {
    6118            0 :                         panic!("Neon WAL redo requires base image or will init record");
    6119              :                     }
    6120              :                 };
    6121              : 
    6122      1430283 :                 for (record_lsn, record) in records {
    6123      1403510 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    6124              :                 }
    6125        26773 :                 Ok(page.freeze())
    6126              :             } else {
    6127              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    6128            0 :                 let s = format!(
    6129            0 :                     "redo for {} to get to {}, with {} and {} records",
    6130              :                     key,
    6131              :                     lsn,
    6132            0 :                     if base_img.is_some() {
    6133            0 :                         "base image"
    6134              :                     } else {
    6135            0 :                         "no base image"
    6136              :                     },
    6137            0 :                     records.len()
    6138              :                 );
    6139            0 :                 println!("{s}");
    6140              : 
    6141            0 :                 Ok(test_img(&s))
    6142              :             }
    6143        26774 :         }
    6144              :     }
    6145              : }
    6146              : 
    6147              : #[cfg(test)]
    6148              : mod tests {
    6149              :     use std::collections::{BTreeMap, BTreeSet};
    6150              : 
    6151              :     use bytes::{Bytes, BytesMut};
    6152              :     use hex_literal::hex;
    6153              :     use itertools::Itertools;
    6154              :     #[cfg(feature = "testing")]
    6155              :     use models::CompactLsnRange;
    6156              :     use pageserver_api::key::{
    6157              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    6158              :     };
    6159              :     use pageserver_api::keyspace::KeySpace;
    6160              :     #[cfg(feature = "testing")]
    6161              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    6162              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings, LsnLease};
    6163              :     use pageserver_compaction::helpers::overlaps_with;
    6164              :     #[cfg(feature = "testing")]
    6165              :     use rand::SeedableRng;
    6166              :     #[cfg(feature = "testing")]
    6167              :     use rand::rngs::StdRng;
    6168              :     use rand::{Rng, thread_rng};
    6169              :     #[cfg(feature = "testing")]
    6170              :     use std::ops::Range;
    6171              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    6172              :     use tests::storage_layer::ValuesReconstructState;
    6173              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    6174              :     #[cfg(feature = "testing")]
    6175              :     use timeline::GcInfo;
    6176              :     #[cfg(feature = "testing")]
    6177              :     use timeline::InMemoryLayerTestDesc;
    6178              :     #[cfg(feature = "testing")]
    6179              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    6180              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    6181              :     use utils::id::TenantId;
    6182              :     use utils::shard::{ShardCount, ShardNumber};
    6183              :     #[cfg(feature = "testing")]
    6184              :     use wal_decoder::models::record::NeonWalRecord;
    6185              :     use wal_decoder::models::value::Value;
    6186              : 
    6187              :     use super::*;
    6188              :     use crate::DEFAULT_PG_VERSION;
    6189              :     use crate::keyspace::KeySpaceAccum;
    6190              :     use crate::tenant::harness::*;
    6191              :     use crate::tenant::timeline::CompactFlags;
    6192              : 
    6193              :     static TEST_KEY: Lazy<Key> =
    6194           10 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    6195              : 
    6196              :     #[cfg(feature = "testing")]
    6197              :     struct TestTimelineSpecification {
    6198              :         start_lsn: Lsn,
    6199              :         last_record_lsn: Lsn,
    6200              : 
    6201              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6202              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6203              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6204              : 
    6205              :         gap_chance: u8,
    6206              :         will_init_chance: u8,
    6207              :     }
    6208              : 
    6209              :     #[cfg(feature = "testing")]
    6210              :     struct Storage {
    6211              :         storage: HashMap<(Key, Lsn), Value>,
    6212              :         start_lsn: Lsn,
    6213              :     }
    6214              : 
    6215              :     #[cfg(feature = "testing")]
    6216              :     impl Storage {
    6217        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6218              :             use bytes::BufMut;
    6219              : 
    6220        32000 :             let mut crnt_lsn = lsn;
    6221        32000 :             let mut got_base = false;
    6222              : 
    6223        32000 :             let mut acc = Vec::new();
    6224              : 
    6225      2831871 :             while crnt_lsn >= self.start_lsn {
    6226      2831871 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6227      1421172 :                     acc.push(value.clone());
    6228              : 
    6229      1402881 :                     match value {
    6230      1402881 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6231      1402881 :                             if *will_init {
    6232        13709 :                                 got_base = true;
    6233        13709 :                                 break;
    6234      1389172 :                             }
    6235              :                         }
    6236              :                         Value::Image(_) => {
    6237        18291 :                             got_base = true;
    6238        18291 :                             break;
    6239              :                         }
    6240            0 :                         _ => unreachable!(),
    6241              :                     }
    6242      1410699 :                 }
    6243              : 
    6244      2799871 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6245              :             }
    6246              : 
    6247        32000 :             assert!(
    6248        32000 :                 got_base,
    6249            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6250              :             );
    6251              : 
    6252        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6253              : 
    6254        32000 :             let mut blob = BytesMut::new();
    6255      1421172 :             for value in acc.into_iter().rev() {
    6256      1402881 :                 match value {
    6257      1402881 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6258      1402881 :                         blob.extend_from_slice(append.as_bytes());
    6259      1402881 :                     }
    6260        18291 :                     Value::Image(img) => {
    6261        18291 :                         blob.put(img);
    6262        18291 :                     }
    6263            0 :                     _ => unreachable!(),
    6264              :                 }
    6265              :             }
    6266              : 
    6267        32000 :             blob.into()
    6268        32000 :         }
    6269              :     }
    6270              : 
    6271              :     #[cfg(feature = "testing")]
    6272              :     #[allow(clippy::too_many_arguments)]
    6273            1 :     async fn randomize_timeline(
    6274            1 :         tenant: &Arc<TenantShard>,
    6275            1 :         new_timeline_id: TimelineId,
    6276            1 :         pg_version: PgMajorVersion,
    6277            1 :         spec: TestTimelineSpecification,
    6278            1 :         random: &mut rand::rngs::StdRng,
    6279            1 :         ctx: &RequestContext,
    6280            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6281            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6282            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6283              : 
    6284            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6285            2 :             let mut lsn = lsn_range.start;
    6286          202 :             while lsn < lsn_range.end {
    6287          200 :                 let mut key = key_range.start;
    6288        21018 :                 while key < key_range.end {
    6289        20818 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6290        20818 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6291              : 
    6292        20818 :                     if gap {
    6293         1018 :                         continue;
    6294        19800 :                     }
    6295              : 
    6296        19800 :                     let record = if will_init {
    6297          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6298              :                     } else {
    6299        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6300              :                     };
    6301              : 
    6302        19800 :                     storage.insert((key, lsn), record);
    6303              : 
    6304        19800 :                     key = key.next();
    6305              :                 }
    6306          200 :                 lsn = Lsn(lsn.0 + 1);
    6307              :             }
    6308              : 
    6309              :             // Stash some interesting LSN for future use
    6310            6 :             for offset in [0, 5, 100].iter() {
    6311            6 :                 if *offset == 0 {
    6312            2 :                     interesting_lsns.push(lsn_range.start);
    6313            2 :                 } else {
    6314            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6315            4 :                     match below {
    6316            4 :                         Some(v) if v >= spec.start_lsn => {
    6317            4 :                             interesting_lsns.push(v);
    6318            4 :                         }
    6319            0 :                         _ => {}
    6320              :                     }
    6321              : 
    6322            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6323            4 :                     interesting_lsns.push(above);
    6324              :                 }
    6325              :             }
    6326              :         }
    6327              : 
    6328            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6329            3 :             let mut lsn = lsn_range.start;
    6330          315 :             while lsn < lsn_range.end {
    6331          312 :                 let mut key = key_range.start;
    6332        11112 :                 while key < key_range.end {
    6333        10800 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6334        10800 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6335              : 
    6336        10800 :                     if gap {
    6337          504 :                         continue;
    6338        10296 :                     }
    6339              : 
    6340        10296 :                     let record = if will_init {
    6341          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6342              :                     } else {
    6343        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6344              :                     };
    6345              : 
    6346        10296 :                     storage.insert((key, lsn), record);
    6347              : 
    6348        10296 :                     key = key.next();
    6349              :                 }
    6350          312 :                 lsn = Lsn(lsn.0 + 1);
    6351              :             }
    6352              : 
    6353              :             // Stash some interesting LSN for future use
    6354            9 :             for offset in [0, 5, 100].iter() {
    6355            9 :                 if *offset == 0 {
    6356            3 :                     interesting_lsns.push(lsn_range.start);
    6357            3 :                 } else {
    6358            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6359            6 :                     match below {
    6360            6 :                         Some(v) if v >= spec.start_lsn => {
    6361            3 :                             interesting_lsns.push(v);
    6362            3 :                         }
    6363            3 :                         _ => {}
    6364              :                     }
    6365              : 
    6366            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6367            6 :                     interesting_lsns.push(above);
    6368              :                 }
    6369              :             }
    6370              :         }
    6371              : 
    6372            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6373            3 :             let mut key = key_range.start;
    6374          142 :             while key < key_range.end {
    6375          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6376          139 :                 let record = Value::Image(blob.clone());
    6377          139 :                 storage.insert((key, *lsn), record);
    6378          139 : 
    6379          139 :                 key = key.next();
    6380          139 :             }
    6381              : 
    6382              :             // Stash some interesting LSN for future use
    6383            9 :             for offset in [0, 5, 100].iter() {
    6384            9 :                 if *offset == 0 {
    6385            3 :                     interesting_lsns.push(*lsn);
    6386            3 :                 } else {
    6387            6 :                     let below = lsn.checked_sub(*offset);
    6388            6 :                     match below {
    6389            6 :                         Some(v) if v >= spec.start_lsn => {
    6390            4 :                             interesting_lsns.push(v);
    6391            4 :                         }
    6392            2 :                         _ => {}
    6393              :                     }
    6394              : 
    6395            6 :                     let above = Lsn(lsn.0 + offset);
    6396            6 :                     interesting_lsns.push(above);
    6397              :                 }
    6398              :             }
    6399              :         }
    6400              : 
    6401            1 :         let in_memory_test_layers = {
    6402            1 :             let mut acc = Vec::new();
    6403              : 
    6404            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6405            2 :                 let mut data = Vec::new();
    6406              : 
    6407            2 :                 let mut lsn = lsn_range.start;
    6408          202 :                 while lsn < lsn_range.end {
    6409          200 :                     let mut key = key_range.start;
    6410        20000 :                     while key < key_range.end {
    6411        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6412        19800 :                             data.push((key, lsn, record.clone()));
    6413        19800 :                         }
    6414              : 
    6415        19800 :                         key = key.next();
    6416              :                     }
    6417          200 :                     lsn = Lsn(lsn.0 + 1);
    6418              :                 }
    6419              : 
    6420            2 :                 acc.push(InMemoryLayerTestDesc {
    6421            2 :                     data,
    6422            2 :                     lsn_range: lsn_range.clone(),
    6423            2 :                     is_open: false,
    6424            2 :                 })
    6425              :             }
    6426              : 
    6427            1 :             acc
    6428              :         };
    6429              : 
    6430            1 :         let delta_test_layers = {
    6431            1 :             let mut acc = Vec::new();
    6432              : 
    6433            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6434            3 :                 let mut data = Vec::new();
    6435              : 
    6436            3 :                 let mut lsn = lsn_range.start;
    6437          315 :                 while lsn < lsn_range.end {
    6438          312 :                     let mut key = key_range.start;
    6439        10608 :                     while key < key_range.end {
    6440        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6441        10296 :                             data.push((key, lsn, record.clone()));
    6442        10296 :                         }
    6443              : 
    6444        10296 :                         key = key.next();
    6445              :                     }
    6446          312 :                     lsn = Lsn(lsn.0 + 1);
    6447              :                 }
    6448              : 
    6449            3 :                 acc.push(DeltaLayerTestDesc {
    6450            3 :                     data,
    6451            3 :                     lsn_range: lsn_range.clone(),
    6452            3 :                     key_range: key_range.clone(),
    6453            3 :                 })
    6454              :             }
    6455              : 
    6456            1 :             acc
    6457              :         };
    6458              : 
    6459            1 :         let image_test_layers = {
    6460            1 :             let mut acc = Vec::new();
    6461              : 
    6462            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6463            3 :                 let mut data = Vec::new();
    6464              : 
    6465            3 :                 let mut key = key_range.start;
    6466          142 :                 while key < key_range.end {
    6467          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6468          139 :                         let blob = match record {
    6469          139 :                             Value::Image(blob) => blob.clone(),
    6470            0 :                             _ => unreachable!(),
    6471              :                         };
    6472              : 
    6473          139 :                         data.push((key, blob));
    6474            0 :                     }
    6475              : 
    6476          139 :                     key = key.next();
    6477              :                 }
    6478              : 
    6479            3 :                 acc.push((*lsn, data));
    6480              :             }
    6481              : 
    6482            1 :             acc
    6483              :         };
    6484              : 
    6485            1 :         let tline = tenant
    6486            1 :             .create_test_timeline_with_layers(
    6487            1 :                 new_timeline_id,
    6488            1 :                 spec.start_lsn,
    6489            1 :                 pg_version,
    6490            1 :                 ctx,
    6491            1 :                 in_memory_test_layers,
    6492            1 :                 delta_test_layers,
    6493            1 :                 image_test_layers,
    6494            1 :                 spec.last_record_lsn,
    6495            1 :             )
    6496            1 :             .await?;
    6497              : 
    6498            1 :         Ok((
    6499            1 :             tline,
    6500            1 :             Storage {
    6501            1 :                 storage,
    6502            1 :                 start_lsn: spec.start_lsn,
    6503            1 :             },
    6504            1 :             interesting_lsns,
    6505            1 :         ))
    6506            1 :     }
    6507              : 
    6508              :     #[tokio::test]
    6509            1 :     async fn test_basic() -> anyhow::Result<()> {
    6510            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6511            1 :         let tline = tenant
    6512            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6513            1 :             .await?;
    6514              : 
    6515            1 :         let mut writer = tline.writer().await;
    6516            1 :         writer
    6517            1 :             .put(
    6518            1 :                 *TEST_KEY,
    6519            1 :                 Lsn(0x10),
    6520            1 :                 &Value::Image(test_img("foo at 0x10")),
    6521            1 :                 &ctx,
    6522            1 :             )
    6523            1 :             .await?;
    6524            1 :         writer.finish_write(Lsn(0x10));
    6525            1 :         drop(writer);
    6526              : 
    6527            1 :         let mut writer = tline.writer().await;
    6528            1 :         writer
    6529            1 :             .put(
    6530            1 :                 *TEST_KEY,
    6531            1 :                 Lsn(0x20),
    6532            1 :                 &Value::Image(test_img("foo at 0x20")),
    6533            1 :                 &ctx,
    6534            1 :             )
    6535            1 :             .await?;
    6536            1 :         writer.finish_write(Lsn(0x20));
    6537            1 :         drop(writer);
    6538              : 
    6539            1 :         assert_eq!(
    6540            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6541            1 :             test_img("foo at 0x10")
    6542              :         );
    6543            1 :         assert_eq!(
    6544            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6545            1 :             test_img("foo at 0x10")
    6546              :         );
    6547            1 :         assert_eq!(
    6548            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6549            1 :             test_img("foo at 0x20")
    6550              :         );
    6551              : 
    6552            2 :         Ok(())
    6553            1 :     }
    6554              : 
    6555              :     #[tokio::test]
    6556            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6557            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6558            1 :             .await?
    6559            1 :             .load()
    6560            1 :             .await;
    6561            1 :         let _ = tenant
    6562            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6563            1 :             .await?;
    6564              : 
    6565            1 :         match tenant
    6566            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6567            1 :             .await
    6568            1 :         {
    6569            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6570            1 :             Err(e) => assert_eq!(
    6571            1 :                 e.to_string(),
    6572            1 :                 "timeline already exists with different parameters".to_string()
    6573            1 :             ),
    6574            1 :         }
    6575            1 : 
    6576            1 :         Ok(())
    6577            1 :     }
    6578              : 
    6579              :     /// Convenience function to create a page image with given string as the only content
    6580            5 :     pub fn test_value(s: &str) -> Value {
    6581            5 :         let mut buf = BytesMut::new();
    6582            5 :         buf.extend_from_slice(s.as_bytes());
    6583            5 :         Value::Image(buf.freeze())
    6584            5 :     }
    6585              : 
    6586              :     ///
    6587              :     /// Test branch creation
    6588              :     ///
    6589              :     #[tokio::test]
    6590            1 :     async fn test_branch() -> anyhow::Result<()> {
    6591              :         use std::str::from_utf8;
    6592              : 
    6593            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6594            1 :         let tline = tenant
    6595            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6596            1 :             .await?;
    6597            1 :         let mut writer = tline.writer().await;
    6598              : 
    6599              :         #[allow(non_snake_case)]
    6600            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6601              :         #[allow(non_snake_case)]
    6602            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6603              : 
    6604              :         // Insert a value on the timeline
    6605            1 :         writer
    6606            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6607            1 :             .await?;
    6608            1 :         writer
    6609            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6610            1 :             .await?;
    6611            1 :         writer.finish_write(Lsn(0x20));
    6612              : 
    6613            1 :         writer
    6614            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6615            1 :             .await?;
    6616            1 :         writer.finish_write(Lsn(0x30));
    6617            1 :         writer
    6618            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6619            1 :             .await?;
    6620            1 :         writer.finish_write(Lsn(0x40));
    6621              : 
    6622              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6623              : 
    6624              :         // Branch the history, modify relation differently on the new timeline
    6625            1 :         tenant
    6626            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6627            1 :             .await?;
    6628            1 :         let newtline = tenant
    6629            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6630            1 :             .expect("Should have a local timeline");
    6631            1 :         let mut new_writer = newtline.writer().await;
    6632            1 :         new_writer
    6633            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6634            1 :             .await?;
    6635            1 :         new_writer.finish_write(Lsn(0x40));
    6636              : 
    6637              :         // Check page contents on both branches
    6638            1 :         assert_eq!(
    6639            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6640              :             "foo at 0x40"
    6641              :         );
    6642            1 :         assert_eq!(
    6643            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6644              :             "bar at 0x40"
    6645              :         );
    6646            1 :         assert_eq!(
    6647            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6648              :             "foobar at 0x20"
    6649              :         );
    6650              : 
    6651              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6652              : 
    6653            2 :         Ok(())
    6654            1 :     }
    6655              : 
    6656           10 :     async fn make_some_layers(
    6657           10 :         tline: &Timeline,
    6658           10 :         start_lsn: Lsn,
    6659           10 :         ctx: &RequestContext,
    6660           10 :     ) -> anyhow::Result<()> {
    6661           10 :         let mut lsn = start_lsn;
    6662              :         {
    6663           10 :             let mut writer = tline.writer().await;
    6664              :             // Create a relation on the timeline
    6665           10 :             writer
    6666           10 :                 .put(
    6667           10 :                     *TEST_KEY,
    6668           10 :                     lsn,
    6669           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6670           10 :                     ctx,
    6671           10 :                 )
    6672           10 :                 .await?;
    6673           10 :             writer.finish_write(lsn);
    6674           10 :             lsn += 0x10;
    6675           10 :             writer
    6676           10 :                 .put(
    6677           10 :                     *TEST_KEY,
    6678           10 :                     lsn,
    6679           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6680           10 :                     ctx,
    6681           10 :                 )
    6682           10 :                 .await?;
    6683           10 :             writer.finish_write(lsn);
    6684           10 :             lsn += 0x10;
    6685              :         }
    6686           10 :         tline.freeze_and_flush().await?;
    6687              :         {
    6688           10 :             let mut writer = tline.writer().await;
    6689           10 :             writer
    6690           10 :                 .put(
    6691           10 :                     *TEST_KEY,
    6692           10 :                     lsn,
    6693           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6694           10 :                     ctx,
    6695           10 :                 )
    6696           10 :                 .await?;
    6697           10 :             writer.finish_write(lsn);
    6698           10 :             lsn += 0x10;
    6699           10 :             writer
    6700           10 :                 .put(
    6701           10 :                     *TEST_KEY,
    6702           10 :                     lsn,
    6703           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6704           10 :                     ctx,
    6705           10 :                 )
    6706           10 :                 .await?;
    6707           10 :             writer.finish_write(lsn);
    6708              :         }
    6709           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6710           10 :     }
    6711              : 
    6712              :     #[tokio::test]
    6713            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6714            1 :         let (tenant, ctx) =
    6715            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6716            1 :                 .await?
    6717            1 :                 .load()
    6718            1 :                 .await;
    6719            1 :         let tline = tenant
    6720            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6721            1 :             .await?;
    6722            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6723              : 
    6724              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6725              :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6726              :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6727              :         // below should fail.
    6728            1 :         tenant
    6729            1 :             .gc_iteration(
    6730            1 :                 Some(TIMELINE_ID),
    6731            1 :                 0x10,
    6732            1 :                 Duration::ZERO,
    6733            1 :                 &CancellationToken::new(),
    6734            1 :                 &ctx,
    6735            1 :             )
    6736            1 :             .await?;
    6737              : 
    6738              :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6739            1 :         match tenant
    6740            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6741            1 :             .await
    6742            1 :         {
    6743            1 :             Ok(_) => panic!("branching should have failed"),
    6744            1 :             Err(err) => {
    6745            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6746            1 :                     panic!("wrong error type")
    6747            1 :                 };
    6748            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6749            1 :                 assert!(
    6750            1 :                     err.source()
    6751            1 :                         .unwrap()
    6752            1 :                         .to_string()
    6753            1 :                         .contains("we might've already garbage collected needed data")
    6754            1 :                 )
    6755            1 :             }
    6756            1 :         }
    6757            1 : 
    6758            1 :         Ok(())
    6759            1 :     }
    6760              : 
    6761              :     #[tokio::test]
    6762            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6763            1 :         let (tenant, ctx) =
    6764            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6765            1 :                 .await?
    6766            1 :                 .load()
    6767            1 :                 .await;
    6768              : 
    6769            1 :         let tline = tenant
    6770            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6771            1 :             .await?;
    6772              :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6773            1 :         match tenant
    6774            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6775            1 :             .await
    6776            1 :         {
    6777            1 :             Ok(_) => panic!("branching should have failed"),
    6778            1 :             Err(err) => {
    6779            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6780            1 :                     panic!("wrong error type");
    6781            1 :                 };
    6782            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6783            1 :                 assert!(
    6784            1 :                     &err.source()
    6785            1 :                         .unwrap()
    6786            1 :                         .to_string()
    6787            1 :                         .contains("is earlier than latest GC cutoff")
    6788            1 :                 );
    6789            1 :             }
    6790            1 :         }
    6791            1 : 
    6792            1 :         Ok(())
    6793            1 :     }
    6794              : 
    6795              :     /*
    6796              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6797              :     // remove the old value, we'd need to work a little harder
    6798              :     #[tokio::test]
    6799              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6800              :         let repo =
    6801              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6802              :             .load();
    6803              : 
    6804              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6805              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6806              : 
    6807              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6808              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6809              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6810              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6811              :             Ok(_) => panic!("request for page should have failed"),
    6812              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6813              :         }
    6814              :         Ok(())
    6815              :     }
    6816              :      */
    6817              : 
    6818              :     #[tokio::test]
    6819            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6820            1 :         let (tenant, ctx) =
    6821            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6822            1 :                 .await?
    6823            1 :                 .load()
    6824            1 :                 .await;
    6825            1 :         let tline = tenant
    6826            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6827            1 :             .await?;
    6828            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6829              : 
    6830            1 :         tenant
    6831            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6832            1 :             .await?;
    6833            1 :         let newtline = tenant
    6834            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6835            1 :             .expect("Should have a local timeline");
    6836              : 
    6837            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6838              : 
    6839            1 :         tline.set_broken("test".to_owned());
    6840              : 
    6841            1 :         tenant
    6842            1 :             .gc_iteration(
    6843            1 :                 Some(TIMELINE_ID),
    6844            1 :                 0x10,
    6845            1 :                 Duration::ZERO,
    6846            1 :                 &CancellationToken::new(),
    6847            1 :                 &ctx,
    6848            1 :             )
    6849            1 :             .await?;
    6850              : 
    6851              :         // The branchpoints should contain all timelines, even ones marked
    6852              :         // as Broken.
    6853              :         {
    6854            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6855            1 :             assert_eq!(branchpoints.len(), 1);
    6856            1 :             assert_eq!(
    6857            1 :                 branchpoints[0],
    6858              :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6859              :             );
    6860              :         }
    6861              : 
    6862              :         // You can read the key from the child branch even though the parent is
    6863              :         // Broken, as long as you don't need to access data from the parent.
    6864            1 :         assert_eq!(
    6865            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6866            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6867              :         );
    6868              : 
    6869              :         // This needs to traverse to the parent, and fails.
    6870            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6871            1 :         assert!(
    6872            1 :             err.to_string().starts_with(&format!(
    6873            1 :                 "bad state on timeline {}: Broken",
    6874            1 :                 tline.timeline_id
    6875            1 :             )),
    6876            0 :             "{err}"
    6877              :         );
    6878              : 
    6879            2 :         Ok(())
    6880            1 :     }
    6881              : 
    6882              :     #[tokio::test]
    6883            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6884            1 :         let (tenant, ctx) =
    6885            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6886            1 :                 .await?
    6887            1 :                 .load()
    6888            1 :                 .await;
    6889            1 :         let tline = tenant
    6890            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6891            1 :             .await?;
    6892            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6893              : 
    6894            1 :         tenant
    6895            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6896            1 :             .await?;
    6897            1 :         let newtline = tenant
    6898            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6899            1 :             .expect("Should have a local timeline");
    6900              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6901            1 :         tenant
    6902            1 :             .gc_iteration(
    6903            1 :                 Some(TIMELINE_ID),
    6904            1 :                 0x10,
    6905            1 :                 Duration::ZERO,
    6906            1 :                 &CancellationToken::new(),
    6907            1 :                 &ctx,
    6908            1 :             )
    6909            1 :             .await?;
    6910            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6911              : 
    6912            2 :         Ok(())
    6913            1 :     }
    6914              :     #[tokio::test]
    6915            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6916            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6917            1 :             .await?
    6918            1 :             .load()
    6919            1 :             .await;
    6920            1 :         let tline = tenant
    6921            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6922            1 :             .await?;
    6923            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6924              : 
    6925            1 :         tenant
    6926            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6927            1 :             .await?;
    6928            1 :         let newtline = tenant
    6929            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6930            1 :             .expect("Should have a local timeline");
    6931              : 
    6932            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6933              : 
    6934              :         // run gc on parent
    6935            1 :         tenant
    6936            1 :             .gc_iteration(
    6937            1 :                 Some(TIMELINE_ID),
    6938            1 :                 0x10,
    6939            1 :                 Duration::ZERO,
    6940            1 :                 &CancellationToken::new(),
    6941            1 :                 &ctx,
    6942            1 :             )
    6943            1 :             .await?;
    6944              : 
    6945              :         // Check that the data is still accessible on the branch.
    6946            1 :         assert_eq!(
    6947            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6948            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6949              :         );
    6950              : 
    6951            2 :         Ok(())
    6952            1 :     }
    6953              : 
    6954              :     #[tokio::test]
    6955            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6956              :         const TEST_NAME: &str = "timeline_load";
    6957            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6958              :         {
    6959            1 :             let (tenant, ctx) = harness.load().await;
    6960            1 :             let tline = tenant
    6961            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6962            1 :                 .await?;
    6963            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6964              :             // so that all uploads finish & we can call harness.load() below again
    6965            1 :             tenant
    6966            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6967            1 :                 .instrument(harness.span())
    6968            1 :                 .await
    6969            1 :                 .ok()
    6970            1 :                 .unwrap();
    6971              :         }
    6972              : 
    6973            1 :         let (tenant, _ctx) = harness.load().await;
    6974            1 :         tenant
    6975            1 :             .get_timeline(TIMELINE_ID, true)
    6976            1 :             .expect("cannot load timeline");
    6977              : 
    6978            2 :         Ok(())
    6979            1 :     }
    6980              : 
    6981              :     #[tokio::test]
    6982            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6983              :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6984            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6985              :         // create two timelines
    6986              :         {
    6987            1 :             let (tenant, ctx) = harness.load().await;
    6988            1 :             let tline = tenant
    6989            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6990            1 :                 .await?;
    6991              : 
    6992            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6993              : 
    6994            1 :             let child_tline = tenant
    6995            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6996            1 :                 .await?;
    6997            1 :             child_tline.set_state(TimelineState::Active);
    6998              : 
    6999            1 :             let newtline = tenant
    7000            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    7001            1 :                 .expect("Should have a local timeline");
    7002              : 
    7003            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    7004              : 
    7005              :             // so that all uploads finish & we can call harness.load() below again
    7006            1 :             tenant
    7007            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    7008            1 :                 .instrument(harness.span())
    7009            1 :                 .await
    7010            1 :                 .ok()
    7011            1 :                 .unwrap();
    7012              :         }
    7013              : 
    7014              :         // check that both of them are initially unloaded
    7015            1 :         let (tenant, _ctx) = harness.load().await;
    7016              : 
    7017              :         // check that both, child and ancestor are loaded
    7018            1 :         let _child_tline = tenant
    7019            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    7020            1 :             .expect("cannot get child timeline loaded");
    7021              : 
    7022            1 :         let _ancestor_tline = tenant
    7023            1 :             .get_timeline(TIMELINE_ID, true)
    7024            1 :             .expect("cannot get ancestor timeline loaded");
    7025              : 
    7026            2 :         Ok(())
    7027            1 :     }
    7028              : 
    7029              :     #[tokio::test]
    7030            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    7031              :         use storage_layer::AsLayerDesc;
    7032            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    7033            1 :             .await?
    7034            1 :             .load()
    7035            1 :             .await;
    7036            1 :         let tline = tenant
    7037            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7038            1 :             .await?;
    7039            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7040              : 
    7041            1 :         let layer_map = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7042            1 :         let level0_deltas = layer_map
    7043            1 :             .layer_map()?
    7044            1 :             .level0_deltas()
    7045            1 :             .iter()
    7046            2 :             .map(|desc| layer_map.get_from_desc(desc))
    7047            1 :             .collect::<Vec<_>>();
    7048              : 
    7049            1 :         assert!(!level0_deltas.is_empty());
    7050              : 
    7051            3 :         for delta in level0_deltas {
    7052            1 :             // Ensure we are dumping a delta layer here
    7053            2 :             assert!(delta.layer_desc().is_delta);
    7054            2 :             delta.dump(true, &ctx).await.unwrap();
    7055            1 :         }
    7056            1 : 
    7057            1 :         Ok(())
    7058            1 :     }
    7059              : 
    7060              :     #[tokio::test]
    7061            1 :     async fn test_images() -> anyhow::Result<()> {
    7062            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    7063            1 :         let tline = tenant
    7064            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7065            1 :             .await?;
    7066              : 
    7067            1 :         let mut writer = tline.writer().await;
    7068            1 :         writer
    7069            1 :             .put(
    7070            1 :                 *TEST_KEY,
    7071            1 :                 Lsn(0x10),
    7072            1 :                 &Value::Image(test_img("foo at 0x10")),
    7073            1 :                 &ctx,
    7074            1 :             )
    7075            1 :             .await?;
    7076            1 :         writer.finish_write(Lsn(0x10));
    7077            1 :         drop(writer);
    7078              : 
    7079            1 :         tline.freeze_and_flush().await?;
    7080            1 :         tline
    7081            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7082            1 :             .await?;
    7083              : 
    7084            1 :         let mut writer = tline.writer().await;
    7085            1 :         writer
    7086            1 :             .put(
    7087            1 :                 *TEST_KEY,
    7088            1 :                 Lsn(0x20),
    7089            1 :                 &Value::Image(test_img("foo at 0x20")),
    7090            1 :                 &ctx,
    7091            1 :             )
    7092            1 :             .await?;
    7093            1 :         writer.finish_write(Lsn(0x20));
    7094            1 :         drop(writer);
    7095              : 
    7096            1 :         tline.freeze_and_flush().await?;
    7097            1 :         tline
    7098            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7099            1 :             .await?;
    7100              : 
    7101            1 :         let mut writer = tline.writer().await;
    7102            1 :         writer
    7103            1 :             .put(
    7104            1 :                 *TEST_KEY,
    7105            1 :                 Lsn(0x30),
    7106            1 :                 &Value::Image(test_img("foo at 0x30")),
    7107            1 :                 &ctx,
    7108            1 :             )
    7109            1 :             .await?;
    7110            1 :         writer.finish_write(Lsn(0x30));
    7111            1 :         drop(writer);
    7112              : 
    7113            1 :         tline.freeze_and_flush().await?;
    7114            1 :         tline
    7115            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7116            1 :             .await?;
    7117              : 
    7118            1 :         let mut writer = tline.writer().await;
    7119            1 :         writer
    7120            1 :             .put(
    7121            1 :                 *TEST_KEY,
    7122            1 :                 Lsn(0x40),
    7123            1 :                 &Value::Image(test_img("foo at 0x40")),
    7124            1 :                 &ctx,
    7125            1 :             )
    7126            1 :             .await?;
    7127            1 :         writer.finish_write(Lsn(0x40));
    7128            1 :         drop(writer);
    7129              : 
    7130            1 :         tline.freeze_and_flush().await?;
    7131            1 :         tline
    7132            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7133            1 :             .await?;
    7134              : 
    7135            1 :         assert_eq!(
    7136            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    7137            1 :             test_img("foo at 0x10")
    7138              :         );
    7139            1 :         assert_eq!(
    7140            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    7141            1 :             test_img("foo at 0x10")
    7142              :         );
    7143            1 :         assert_eq!(
    7144            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    7145            1 :             test_img("foo at 0x20")
    7146              :         );
    7147            1 :         assert_eq!(
    7148            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    7149            1 :             test_img("foo at 0x30")
    7150              :         );
    7151            1 :         assert_eq!(
    7152            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    7153            1 :             test_img("foo at 0x40")
    7154              :         );
    7155              : 
    7156            2 :         Ok(())
    7157            1 :     }
    7158              : 
    7159            2 :     async fn bulk_insert_compact_gc(
    7160            2 :         tenant: &TenantShard,
    7161            2 :         timeline: &Arc<Timeline>,
    7162            2 :         ctx: &RequestContext,
    7163            2 :         lsn: Lsn,
    7164            2 :         repeat: usize,
    7165            2 :         key_count: usize,
    7166            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7167            2 :         let compact = true;
    7168            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    7169            2 :     }
    7170              : 
    7171            4 :     async fn bulk_insert_maybe_compact_gc(
    7172            4 :         tenant: &TenantShard,
    7173            4 :         timeline: &Arc<Timeline>,
    7174            4 :         ctx: &RequestContext,
    7175            4 :         mut lsn: Lsn,
    7176            4 :         repeat: usize,
    7177            4 :         key_count: usize,
    7178            4 :         compact: bool,
    7179            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7180            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    7181              : 
    7182            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7183            4 :         let mut blknum = 0;
    7184              : 
    7185              :         // Enforce that key range is monotonously increasing
    7186            4 :         let mut keyspace = KeySpaceAccum::new();
    7187              : 
    7188            4 :         let cancel = CancellationToken::new();
    7189              : 
    7190            4 :         for _ in 0..repeat {
    7191          200 :             for _ in 0..key_count {
    7192      2000000 :                 test_key.field6 = blknum;
    7193      2000000 :                 let mut writer = timeline.writer().await;
    7194      2000000 :                 writer
    7195      2000000 :                     .put(
    7196      2000000 :                         test_key,
    7197      2000000 :                         lsn,
    7198      2000000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7199      2000000 :                         ctx,
    7200      2000000 :                     )
    7201      2000000 :                     .await?;
    7202      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7203      2000000 :                 writer.finish_write(lsn);
    7204      2000000 :                 drop(writer);
    7205              : 
    7206      2000000 :                 keyspace.add_key(test_key);
    7207              : 
    7208      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7209      2000000 :                 blknum += 1;
    7210              :             }
    7211              : 
    7212          200 :             timeline.freeze_and_flush().await?;
    7213          200 :             if compact {
    7214              :                 // this requires timeline to be &Arc<Timeline>
    7215          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7216          100 :             }
    7217              : 
    7218              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7219              :             // originally was.
    7220          200 :             let res = tenant
    7221          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7222          200 :                 .await?;
    7223              : 
    7224          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7225              :         }
    7226              : 
    7227            4 :         Ok(inserted)
    7228            4 :     }
    7229              : 
    7230              :     //
    7231              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7232              :     // Repeat 50 times.
    7233              :     //
    7234              :     #[tokio::test]
    7235            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7236            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7237            1 :         let (tenant, ctx) = harness.load().await;
    7238            1 :         let tline = tenant
    7239            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7240            1 :             .await?;
    7241              : 
    7242            1 :         let lsn = Lsn(0x10);
    7243            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7244              : 
    7245            2 :         Ok(())
    7246            1 :     }
    7247              : 
    7248              :     // Test the vectored get real implementation against a simple sequential implementation.
    7249              :     //
    7250              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7251              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7252              :     // grow to the right on the X axis.
    7253              :     //                       [Delta]
    7254              :     //                 [Delta]
    7255              :     //           [Delta]
    7256              :     //    [Delta]
    7257              :     // ------------ Image ---------------
    7258              :     //
    7259              :     // After layer generation we pick the ranges to query as follows:
    7260              :     // 1. The beginning of each delta layer
    7261              :     // 2. At the seam between two adjacent delta layers
    7262              :     //
    7263              :     // There's one major downside to this test: delta layers only contains images,
    7264              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7265              :     #[tokio::test]
    7266            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7267            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7268            1 :         let (tenant, ctx) = harness.load().await;
    7269            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7270            1 :         let tline = tenant
    7271            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7272            1 :             .await?;
    7273              : 
    7274            1 :         let lsn = Lsn(0x10);
    7275            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7276              : 
    7277            1 :         let guard = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7278            1 :         let lm = guard.layer_map()?;
    7279              : 
    7280            1 :         lm.dump(true, &ctx).await?;
    7281              : 
    7282            1 :         let mut reads = Vec::new();
    7283            1 :         let mut prev = None;
    7284            6 :         lm.iter_historic_layers().for_each(|desc| {
    7285            6 :             if !desc.is_delta() {
    7286            1 :                 prev = Some(desc.clone());
    7287            1 :                 return;
    7288            5 :             }
    7289              : 
    7290            5 :             let start = desc.key_range.start;
    7291            5 :             let end = desc
    7292            5 :                 .key_range
    7293            5 :                 .start
    7294            5 :                 .add(tenant.conf.max_get_vectored_keys.get() as u32);
    7295            5 :             reads.push(KeySpace {
    7296            5 :                 ranges: vec![start..end],
    7297            5 :             });
    7298              : 
    7299            5 :             if let Some(prev) = &prev {
    7300            5 :                 if !prev.is_delta() {
    7301            5 :                     return;
    7302            0 :                 }
    7303              : 
    7304            0 :                 let first_range = Key {
    7305            0 :                     field6: prev.key_range.end.field6 - 4,
    7306            0 :                     ..prev.key_range.end
    7307            0 :                 }..prev.key_range.end;
    7308              : 
    7309            0 :                 let second_range = desc.key_range.start..Key {
    7310            0 :                     field6: desc.key_range.start.field6 + 4,
    7311            0 :                     ..desc.key_range.start
    7312            0 :                 };
    7313              : 
    7314            0 :                 reads.push(KeySpace {
    7315            0 :                     ranges: vec![first_range, second_range],
    7316            0 :                 });
    7317            0 :             };
    7318              : 
    7319            0 :             prev = Some(desc.clone());
    7320            6 :         });
    7321              : 
    7322            1 :         drop(guard);
    7323              : 
    7324              :         // Pick a big LSN such that we query over all the changes.
    7325            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7326              : 
    7327            6 :         for read in reads {
    7328            5 :             info!("Doing vectored read on {:?}", read);
    7329            1 : 
    7330            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7331            1 : 
    7332            5 :             let vectored_res = tline
    7333            5 :                 .get_vectored_impl(
    7334            5 :                     query,
    7335            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7336            5 :                     &ctx,
    7337            5 :                 )
    7338            5 :                 .await;
    7339            1 : 
    7340            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7341            5 :             let mut expect_missing = false;
    7342            5 :             let mut key = read.start().unwrap();
    7343          165 :             while key != read.end().unwrap() {
    7344          160 :                 if let Some(lsns) = inserted.get(&key) {
    7345          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7346          160 :                     match expected_lsn {
    7347          160 :                         Some(lsn) => {
    7348          160 :                             expected_lsns.insert(key, *lsn);
    7349          160 :                         }
    7350            1 :                         None => {
    7351            1 :                             expect_missing = true;
    7352            1 :                             break;
    7353            1 :                         }
    7354            1 :                     }
    7355            1 :                 } else {
    7356            1 :                     expect_missing = true;
    7357            1 :                     break;
    7358            1 :                 }
    7359            1 : 
    7360          160 :                 key = key.next();
    7361            1 :             }
    7362            1 : 
    7363            5 :             if expect_missing {
    7364            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7365            1 :             } else {
    7366          160 :                 for (key, image) in vectored_res? {
    7367          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7368          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7369          160 :                     assert_eq!(image?, expected_image);
    7370            1 :                 }
    7371            1 :             }
    7372            1 :         }
    7373            1 : 
    7374            1 :         Ok(())
    7375            1 :     }
    7376              : 
    7377              :     #[tokio::test]
    7378            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7379            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7380              : 
    7381            1 :         let (tenant, ctx) = harness.load().await;
    7382            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7383            1 :         let (tline, ctx) = tenant
    7384            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7385            1 :             .await?;
    7386            1 :         let tline = tline.raw_timeline().unwrap();
    7387              : 
    7388            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7389            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7390            1 :         modification.set_lsn(Lsn(0x1008))?;
    7391            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7392            1 :         modification.commit(&ctx).await?;
    7393              : 
    7394            1 :         let child_timeline_id = TimelineId::generate();
    7395            1 :         tenant
    7396            1 :             .branch_timeline_test(
    7397            1 :                 tline,
    7398            1 :                 child_timeline_id,
    7399            1 :                 Some(tline.get_last_record_lsn()),
    7400            1 :                 &ctx,
    7401            1 :             )
    7402            1 :             .await?;
    7403              : 
    7404            1 :         let child_timeline = tenant
    7405            1 :             .get_timeline(child_timeline_id, true)
    7406            1 :             .expect("Should have the branched timeline");
    7407              : 
    7408            1 :         let aux_keyspace = KeySpace {
    7409            1 :             ranges: vec![NON_INHERITED_RANGE],
    7410            1 :         };
    7411            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7412              : 
    7413            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7414              : 
    7415            1 :         let vectored_res = child_timeline
    7416            1 :             .get_vectored_impl(
    7417            1 :                 query,
    7418            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7419            1 :                 &ctx,
    7420            1 :             )
    7421            1 :             .await;
    7422              : 
    7423            1 :         let images = vectored_res?;
    7424            1 :         assert!(images.is_empty());
    7425            2 :         Ok(())
    7426            1 :     }
    7427              : 
    7428              :     // Test that vectored get handles layer gaps correctly
    7429              :     // by advancing into the next ancestor timeline if required.
    7430              :     //
    7431              :     // The test generates timelines that look like the diagram below.
    7432              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7433              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7434              :     //
    7435              :     // ```
    7436              :     //-------------------------------+
    7437              :     //                          ...  |
    7438              :     //               [   L1   ]      |
    7439              :     //     [ / L1   ]                | Child Timeline
    7440              :     // ...                           |
    7441              :     // ------------------------------+
    7442              :     //     [ X L1   ]                | Parent Timeline
    7443              :     // ------------------------------+
    7444              :     // ```
    7445              :     #[tokio::test]
    7446            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7447            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7448            1 :             // Make compaction deterministic
    7449            1 :             gc_period: Some(Duration::ZERO),
    7450            1 :             compaction_period: Some(Duration::ZERO),
    7451            1 :             // Encourage creation of L1 layers
    7452            1 :             checkpoint_distance: Some(16 * 1024),
    7453            1 :             compaction_target_size: Some(8 * 1024),
    7454            1 :             ..Default::default()
    7455            1 :         };
    7456              : 
    7457            1 :         let harness = TenantHarness::create_custom(
    7458            1 :             "test_get_vectored_key_gap",
    7459            1 :             tenant_conf,
    7460            1 :             TenantId::generate(),
    7461            1 :             ShardIdentity::unsharded(),
    7462            1 :             Generation::new(0xdeadbeef),
    7463            1 :         )
    7464            1 :         .await?;
    7465            1 :         let (tenant, ctx) = harness.load().await;
    7466            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7467              : 
    7468            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7469            1 :         let gap_at_key = current_key.add(100);
    7470            1 :         let mut current_lsn = Lsn(0x10);
    7471              : 
    7472              :         const KEY_COUNT: usize = 10_000;
    7473              : 
    7474            1 :         let timeline_id = TimelineId::generate();
    7475            1 :         let current_timeline = tenant
    7476            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7477            1 :             .await?;
    7478              : 
    7479            1 :         current_lsn += 0x100;
    7480              : 
    7481            1 :         let mut writer = current_timeline.writer().await;
    7482            1 :         writer
    7483            1 :             .put(
    7484            1 :                 gap_at_key,
    7485            1 :                 current_lsn,
    7486            1 :                 &Value::Image(test_img(&format!("{gap_at_key} at {current_lsn}"))),
    7487            1 :                 &ctx,
    7488            1 :             )
    7489            1 :             .await?;
    7490            1 :         writer.finish_write(current_lsn);
    7491            1 :         drop(writer);
    7492              : 
    7493            1 :         let mut latest_lsns = HashMap::new();
    7494            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7495              : 
    7496            1 :         current_timeline.freeze_and_flush().await?;
    7497              : 
    7498            1 :         let child_timeline_id = TimelineId::generate();
    7499              : 
    7500            1 :         tenant
    7501            1 :             .branch_timeline_test(
    7502            1 :                 &current_timeline,
    7503            1 :                 child_timeline_id,
    7504            1 :                 Some(current_lsn),
    7505            1 :                 &ctx,
    7506            1 :             )
    7507            1 :             .await?;
    7508            1 :         let child_timeline = tenant
    7509            1 :             .get_timeline(child_timeline_id, true)
    7510            1 :             .expect("Should have the branched timeline");
    7511              : 
    7512        10001 :         for i in 0..KEY_COUNT {
    7513        10000 :             if current_key == gap_at_key {
    7514            1 :                 current_key = current_key.next();
    7515            1 :                 continue;
    7516         9999 :             }
    7517              : 
    7518         9999 :             current_lsn += 0x10;
    7519              : 
    7520         9999 :             let mut writer = child_timeline.writer().await;
    7521         9999 :             writer
    7522         9999 :                 .put(
    7523         9999 :                     current_key,
    7524         9999 :                     current_lsn,
    7525         9999 :                     &Value::Image(test_img(&format!("{current_key} at {current_lsn}"))),
    7526         9999 :                     &ctx,
    7527         9999 :                 )
    7528         9999 :                 .await?;
    7529         9999 :             writer.finish_write(current_lsn);
    7530         9999 :             drop(writer);
    7531              : 
    7532         9999 :             latest_lsns.insert(current_key, current_lsn);
    7533         9999 :             current_key = current_key.next();
    7534              : 
    7535              :             // Flush every now and then to encourage layer file creation.
    7536         9999 :             if i % 500 == 0 {
    7537           20 :                 child_timeline.freeze_and_flush().await?;
    7538         9979 :             }
    7539              :         }
    7540              : 
    7541            1 :         child_timeline.freeze_and_flush().await?;
    7542            1 :         let mut flags = EnumSet::new();
    7543            1 :         flags.insert(CompactFlags::ForceRepartition);
    7544            1 :         child_timeline
    7545            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7546            1 :             .await?;
    7547              : 
    7548            1 :         let key_near_end = {
    7549            1 :             let mut tmp = current_key;
    7550            1 :             tmp.field6 -= 10;
    7551            1 :             tmp
    7552              :         };
    7553              : 
    7554            1 :         let key_near_gap = {
    7555            1 :             let mut tmp = gap_at_key;
    7556            1 :             tmp.field6 -= 10;
    7557            1 :             tmp
    7558              :         };
    7559              : 
    7560            1 :         let read = KeySpace {
    7561            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7562            1 :         };
    7563              : 
    7564            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7565              : 
    7566            1 :         let results = child_timeline
    7567            1 :             .get_vectored_impl(
    7568            1 :                 query,
    7569            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7570            1 :                 &ctx,
    7571            1 :             )
    7572            1 :             .await?;
    7573              : 
    7574           22 :         for (key, img_res) in results {
    7575           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7576           21 :             assert_eq!(img_res?, expected);
    7577            1 :         }
    7578            1 : 
    7579            1 :         Ok(())
    7580            1 :     }
    7581              : 
    7582              :     // Test that vectored get descends into ancestor timelines correctly and
    7583              :     // does not return an image that's newer than requested.
    7584              :     //
    7585              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7586              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7587              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7588              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7589              :     // order to avoid returning an image that's too new. The test below constructs such
    7590              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7591              :     // ```
    7592              :     //    LSN
    7593              :     //     ^
    7594              :     //     |
    7595              :     //     |
    7596              :     // 500 | --------------------------------------> branch point
    7597              :     // 400 |        X
    7598              :     // 300 |        X
    7599              :     // 200 | --------------------------------------> requested lsn
    7600              :     // 100 |        X
    7601              :     //     |---------------------------------------> Key
    7602              :     //              |
    7603              :     //              ------> requested key
    7604              :     //
    7605              :     // Legend:
    7606              :     // * X - page images
    7607              :     // ```
    7608              :     #[tokio::test]
    7609            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7610            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7611            1 :         let (tenant, ctx) = harness.load().await;
    7612            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7613              : 
    7614            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7615            1 :         let end_key = start_key.add(1000);
    7616            1 :         let child_gap_at_key = start_key.add(500);
    7617            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7618              : 
    7619            1 :         let mut current_lsn = Lsn(0x10);
    7620              : 
    7621            1 :         let timeline_id = TimelineId::generate();
    7622            1 :         let parent_timeline = tenant
    7623            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7624            1 :             .await?;
    7625              : 
    7626            1 :         current_lsn += 0x100;
    7627              : 
    7628            4 :         for _ in 0..3 {
    7629            3 :             let mut key = start_key;
    7630         3003 :             while key < end_key {
    7631         3000 :                 current_lsn += 0x10;
    7632              : 
    7633         3000 :                 let image_value = format!("{child_gap_at_key} at {current_lsn}");
    7634              : 
    7635         3000 :                 let mut writer = parent_timeline.writer().await;
    7636         3000 :                 writer
    7637         3000 :                     .put(
    7638         3000 :                         key,
    7639         3000 :                         current_lsn,
    7640         3000 :                         &Value::Image(test_img(&image_value)),
    7641         3000 :                         &ctx,
    7642         3000 :                     )
    7643         3000 :                     .await?;
    7644         3000 :                 writer.finish_write(current_lsn);
    7645              : 
    7646         3000 :                 if key == child_gap_at_key {
    7647            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7648         2997 :                 }
    7649              : 
    7650         3000 :                 key = key.next();
    7651              :             }
    7652              : 
    7653            3 :             parent_timeline.freeze_and_flush().await?;
    7654              :         }
    7655              : 
    7656            1 :         let child_timeline_id = TimelineId::generate();
    7657              : 
    7658            1 :         let child_timeline = tenant
    7659            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7660            1 :             .await?;
    7661              : 
    7662            1 :         let mut key = start_key;
    7663         1001 :         while key < end_key {
    7664         1000 :             if key == child_gap_at_key {
    7665            1 :                 key = key.next();
    7666            1 :                 continue;
    7667          999 :             }
    7668              : 
    7669          999 :             current_lsn += 0x10;
    7670              : 
    7671          999 :             let mut writer = child_timeline.writer().await;
    7672          999 :             writer
    7673          999 :                 .put(
    7674          999 :                     key,
    7675          999 :                     current_lsn,
    7676          999 :                     &Value::Image(test_img(&format!("{key} at {current_lsn}"))),
    7677          999 :                     &ctx,
    7678          999 :                 )
    7679          999 :                 .await?;
    7680          999 :             writer.finish_write(current_lsn);
    7681              : 
    7682          999 :             key = key.next();
    7683              :         }
    7684              : 
    7685            1 :         child_timeline.freeze_and_flush().await?;
    7686              : 
    7687            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7688            1 :         let mut query_lsns = Vec::new();
    7689            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7690           18 :             for offset in lsn_offsets {
    7691           15 :                 query_lsns.push(Lsn(image_lsn
    7692           15 :                     .0
    7693           15 :                     .checked_add_signed(offset)
    7694           15 :                     .expect("Shouldn't overflow")));
    7695           15 :             }
    7696            1 :         }
    7697            1 : 
    7698           16 :         for query_lsn in query_lsns {
    7699           15 :             let query = VersionedKeySpaceQuery::uniform(
    7700           15 :                 KeySpace {
    7701           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7702           15 :                 },
    7703           15 :                 query_lsn,
    7704            1 :             );
    7705            1 : 
    7706           15 :             let results = child_timeline
    7707           15 :                 .get_vectored_impl(
    7708           15 :                     query,
    7709           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7710           15 :                     &ctx,
    7711           15 :                 )
    7712           15 :                 .await;
    7713            1 : 
    7714           15 :             let expected_item = parent_gap_lsns
    7715           15 :                 .iter()
    7716           15 :                 .rev()
    7717           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7718            1 : 
    7719           15 :             info!(
    7720            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7721            1 :                 query_lsn, expected_item
    7722            1 :             );
    7723            1 : 
    7724           15 :             match expected_item {
    7725           13 :                 Some((_, img_value)) => {
    7726           13 :                     let key_results = results.expect("No vectored get error expected");
    7727           13 :                     let key_result = &key_results[&child_gap_at_key];
    7728           13 :                     let returned_img = key_result
    7729           13 :                         .as_ref()
    7730           13 :                         .expect("No page reconstruct error expected");
    7731            1 : 
    7732           13 :                     info!(
    7733            1 :                         "Vectored read at LSN {} returned image {}",
    7734            1 :                         query_lsn,
    7735            1 :                         std::str::from_utf8(returned_img)?
    7736            1 :                     );
    7737           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7738            1 :                 }
    7739            1 :                 None => {
    7740            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7741            1 :                 }
    7742            1 :             }
    7743            1 :         }
    7744            1 : 
    7745            1 :         Ok(())
    7746            1 :     }
    7747              : 
    7748              :     #[tokio::test]
    7749            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7750            1 :         let names_algorithms = [
    7751            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7752            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7753            1 :         ];
    7754            3 :         for (name, algorithm) in names_algorithms {
    7755            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7756            1 :         }
    7757            1 :         Ok(())
    7758            1 :     }
    7759              : 
    7760            2 :     async fn test_random_updates_algorithm(
    7761            2 :         name: &'static str,
    7762            2 :         compaction_algorithm: CompactionAlgorithm,
    7763            2 :     ) -> anyhow::Result<()> {
    7764            2 :         let mut harness = TenantHarness::create(name).await?;
    7765            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7766            2 :             kind: compaction_algorithm,
    7767            2 :         });
    7768            2 :         let (tenant, ctx) = harness.load().await;
    7769            2 :         let tline = tenant
    7770            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7771            2 :             .await?;
    7772              : 
    7773              :         const NUM_KEYS: usize = 1000;
    7774            2 :         let cancel = CancellationToken::new();
    7775              : 
    7776            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7777            2 :         let mut test_key_end = test_key;
    7778            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7779            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7780              : 
    7781            2 :         let mut keyspace = KeySpaceAccum::new();
    7782              : 
    7783              :         // Track when each page was last modified. Used to assert that
    7784              :         // a read sees the latest page version.
    7785            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7786              : 
    7787            2 :         let mut lsn = Lsn(0x10);
    7788              :         #[allow(clippy::needless_range_loop)]
    7789         2002 :         for blknum in 0..NUM_KEYS {
    7790         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7791         2000 :             test_key.field6 = blknum as u32;
    7792         2000 :             let mut writer = tline.writer().await;
    7793         2000 :             writer
    7794         2000 :                 .put(
    7795         2000 :                     test_key,
    7796         2000 :                     lsn,
    7797         2000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7798         2000 :                     &ctx,
    7799         2000 :                 )
    7800         2000 :                 .await?;
    7801         2000 :             writer.finish_write(lsn);
    7802         2000 :             updated[blknum] = lsn;
    7803         2000 :             drop(writer);
    7804              : 
    7805         2000 :             keyspace.add_key(test_key);
    7806              :         }
    7807              : 
    7808          102 :         for _ in 0..50 {
    7809       100100 :             for _ in 0..NUM_KEYS {
    7810       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7811       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7812       100000 :                 test_key.field6 = blknum as u32;
    7813       100000 :                 let mut writer = tline.writer().await;
    7814       100000 :                 writer
    7815       100000 :                     .put(
    7816       100000 :                         test_key,
    7817       100000 :                         lsn,
    7818       100000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7819       100000 :                         &ctx,
    7820       100000 :                     )
    7821       100000 :                     .await?;
    7822       100000 :                 writer.finish_write(lsn);
    7823       100000 :                 drop(writer);
    7824       100000 :                 updated[blknum] = lsn;
    7825              :             }
    7826              : 
    7827              :             // Read all the blocks
    7828       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7829       100000 :                 test_key.field6 = blknum as u32;
    7830       100000 :                 assert_eq!(
    7831       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7832       100000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7833              :                 );
    7834              :             }
    7835              : 
    7836              :             // Perform a cycle of flush, and GC
    7837          100 :             tline.freeze_and_flush().await?;
    7838          100 :             tenant
    7839          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7840          100 :                 .await?;
    7841              :         }
    7842              : 
    7843            2 :         Ok(())
    7844            2 :     }
    7845              : 
    7846              :     #[tokio::test]
    7847            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7848            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7849            1 :             .await?
    7850            1 :             .load()
    7851            1 :             .await;
    7852            1 :         let mut tline = tenant
    7853            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7854            1 :             .await?;
    7855              : 
    7856              :         const NUM_KEYS: usize = 1000;
    7857              : 
    7858            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7859              : 
    7860            1 :         let mut keyspace = KeySpaceAccum::new();
    7861              : 
    7862            1 :         let cancel = CancellationToken::new();
    7863              : 
    7864              :         // Track when each page was last modified. Used to assert that
    7865              :         // a read sees the latest page version.
    7866            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7867              : 
    7868            1 :         let mut lsn = Lsn(0x10);
    7869            1 :         #[allow(clippy::needless_range_loop)]
    7870         1001 :         for blknum in 0..NUM_KEYS {
    7871         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7872         1000 :             test_key.field6 = blknum as u32;
    7873         1000 :             let mut writer = tline.writer().await;
    7874         1000 :             writer
    7875         1000 :                 .put(
    7876         1000 :                     test_key,
    7877         1000 :                     lsn,
    7878         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7879         1000 :                     &ctx,
    7880         1000 :                 )
    7881         1000 :                 .await?;
    7882         1000 :             writer.finish_write(lsn);
    7883         1000 :             updated[blknum] = lsn;
    7884         1000 :             drop(writer);
    7885            1 : 
    7886         1000 :             keyspace.add_key(test_key);
    7887            1 :         }
    7888            1 : 
    7889           51 :         for _ in 0..50 {
    7890           50 :             let new_tline_id = TimelineId::generate();
    7891           50 :             tenant
    7892           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7893           50 :                 .await?;
    7894           50 :             tline = tenant
    7895           50 :                 .get_timeline(new_tline_id, true)
    7896           50 :                 .expect("Should have the branched timeline");
    7897            1 : 
    7898        50050 :             for _ in 0..NUM_KEYS {
    7899        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7900        50000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7901        50000 :                 test_key.field6 = blknum as u32;
    7902        50000 :                 let mut writer = tline.writer().await;
    7903        50000 :                 writer
    7904        50000 :                     .put(
    7905        50000 :                         test_key,
    7906        50000 :                         lsn,
    7907        50000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7908        50000 :                         &ctx,
    7909        50000 :                     )
    7910        50000 :                     .await?;
    7911        50000 :                 println!("updating {blknum} at {lsn}");
    7912        50000 :                 writer.finish_write(lsn);
    7913        50000 :                 drop(writer);
    7914        50000 :                 updated[blknum] = lsn;
    7915            1 :             }
    7916            1 : 
    7917            1 :             // Read all the blocks
    7918        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7919        50000 :                 test_key.field6 = blknum as u32;
    7920        50000 :                 assert_eq!(
    7921        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7922        50000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7923            1 :                 );
    7924            1 :             }
    7925            1 : 
    7926            1 :             // Perform a cycle of flush, compact, and GC
    7927           50 :             tline.freeze_and_flush().await?;
    7928           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7929           50 :             tenant
    7930           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7931           50 :                 .await?;
    7932            1 :         }
    7933            1 : 
    7934            1 :         Ok(())
    7935            1 :     }
    7936              : 
    7937              :     #[tokio::test]
    7938            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7939            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7940            1 :             .await?
    7941            1 :             .load()
    7942            1 :             .await;
    7943            1 :         let mut tline = tenant
    7944            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7945            1 :             .await?;
    7946              : 
    7947              :         const NUM_KEYS: usize = 100;
    7948              :         const NUM_TLINES: usize = 50;
    7949              : 
    7950            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7951              :         // Track page mutation lsns across different timelines.
    7952            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7953              : 
    7954            1 :         let mut lsn = Lsn(0x10);
    7955              : 
    7956            1 :         #[allow(clippy::needless_range_loop)]
    7957           51 :         for idx in 0..NUM_TLINES {
    7958           50 :             let new_tline_id = TimelineId::generate();
    7959           50 :             tenant
    7960           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7961           50 :                 .await?;
    7962           50 :             tline = tenant
    7963           50 :                 .get_timeline(new_tline_id, true)
    7964           50 :                 .expect("Should have the branched timeline");
    7965            1 : 
    7966         5050 :             for _ in 0..NUM_KEYS {
    7967         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7968         5000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7969         5000 :                 test_key.field6 = blknum as u32;
    7970         5000 :                 let mut writer = tline.writer().await;
    7971         5000 :                 writer
    7972         5000 :                     .put(
    7973         5000 :                         test_key,
    7974         5000 :                         lsn,
    7975         5000 :                         &Value::Image(test_img(&format!("{idx} {blknum} at {lsn}"))),
    7976         5000 :                         &ctx,
    7977         5000 :                     )
    7978         5000 :                     .await?;
    7979         5000 :                 println!("updating [{idx}][{blknum}] at {lsn}");
    7980         5000 :                 writer.finish_write(lsn);
    7981         5000 :                 drop(writer);
    7982         5000 :                 updated[idx][blknum] = lsn;
    7983            1 :             }
    7984            1 :         }
    7985            1 : 
    7986            1 :         // Read pages from leaf timeline across all ancestors.
    7987           50 :         for (idx, lsns) in updated.iter().enumerate() {
    7988         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7989            1 :                 // Skip empty mutations.
    7990         5000 :                 if lsn.0 == 0 {
    7991         1839 :                     continue;
    7992         3161 :                 }
    7993         3161 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7994         3161 :                 test_key.field6 = blknum as u32;
    7995         3161 :                 assert_eq!(
    7996         3161 :                     tline.get(test_key, *lsn, &ctx).await?,
    7997         3161 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7998            1 :                 );
    7999            1 :             }
    8000            1 :         }
    8001            1 :         Ok(())
    8002            1 :     }
    8003              : 
    8004              :     #[tokio::test]
    8005            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    8006            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    8007            1 :             .await?
    8008            1 :             .load()
    8009            1 :             .await;
    8010              : 
    8011            1 :         let initdb_lsn = Lsn(0x20);
    8012            1 :         let (utline, ctx) = tenant
    8013            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    8014            1 :             .await?;
    8015            1 :         let tline = utline.raw_timeline().unwrap();
    8016              : 
    8017              :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    8018            1 :         tline.maybe_spawn_flush_loop();
    8019              : 
    8020              :         // Make sure the timeline has the minimum set of required keys for operation.
    8021              :         // The only operation you can always do on an empty timeline is to `put` new data.
    8022              :         // Except if you `put` at `initdb_lsn`.
    8023              :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    8024              :         // It uses `repartition()`, which assumes some keys to be present.
    8025              :         // Let's make sure the test timeline can handle that case.
    8026              :         {
    8027            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    8028            1 :             assert_eq!(
    8029              :                 timeline::FlushLoopState::Running {
    8030              :                     expect_initdb_optimization: false,
    8031              :                     initdb_optimization_count: 0,
    8032              :                 },
    8033            1 :                 *state
    8034              :             );
    8035            1 :             *state = timeline::FlushLoopState::Running {
    8036            1 :                 expect_initdb_optimization: true,
    8037            1 :                 initdb_optimization_count: 0,
    8038            1 :             };
    8039              :         }
    8040              : 
    8041              :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    8042              :         // As explained above, the optimization requires some keys to be present.
    8043              :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    8044              :         // This is what `create_test_timeline` does, by the way.
    8045            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    8046            1 :         modification
    8047            1 :             .init_empty_test_timeline()
    8048            1 :             .context("init_empty_test_timeline")?;
    8049            1 :         modification
    8050            1 :             .commit(&ctx)
    8051            1 :             .await
    8052            1 :             .context("commit init_empty_test_timeline modification")?;
    8053              : 
    8054              :         // Do the flush. The flush code will check the expectations that we set above.
    8055            1 :         tline.freeze_and_flush().await?;
    8056              : 
    8057              :         // assert freeze_and_flush exercised the initdb optimization
    8058            1 :         {
    8059            1 :             let state = tline.flush_loop_state.lock().unwrap();
    8060            1 :             let timeline::FlushLoopState::Running {
    8061            1 :                 expect_initdb_optimization,
    8062            1 :                 initdb_optimization_count,
    8063            1 :             } = *state
    8064            1 :             else {
    8065            1 :                 panic!("unexpected state: {:?}", *state);
    8066            1 :             };
    8067            1 :             assert!(expect_initdb_optimization);
    8068            1 :             assert!(initdb_optimization_count > 0);
    8069            1 :         }
    8070            1 :         Ok(())
    8071            1 :     }
    8072              : 
    8073              :     #[tokio::test]
    8074            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    8075            1 :         let name = "test_create_guard_crash";
    8076            1 :         let harness = TenantHarness::create(name).await?;
    8077              :         {
    8078            1 :             let (tenant, ctx) = harness.load().await;
    8079            1 :             let (tline, _ctx) = tenant
    8080            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    8081            1 :                 .await?;
    8082              :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    8083            1 :             let raw_tline = tline.raw_timeline().unwrap();
    8084            1 :             raw_tline
    8085            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    8086            1 :                 .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))
    8087            1 :                 .await;
    8088            1 :             std::mem::forget(tline);
    8089              :         }
    8090              : 
    8091            1 :         let (tenant, _) = harness.load().await;
    8092            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    8093            0 :             Ok(_) => panic!("timeline should've been removed during load"),
    8094            1 :             Err(e) => {
    8095            1 :                 assert_eq!(
    8096              :                     e,
    8097            1 :                     GetTimelineError::NotFound {
    8098            1 :                         tenant_id: tenant.tenant_shard_id,
    8099            1 :                         timeline_id: TIMELINE_ID,
    8100            1 :                     }
    8101              :                 )
    8102              :             }
    8103              :         }
    8104              : 
    8105            1 :         assert!(
    8106            1 :             !harness
    8107            1 :                 .conf
    8108            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    8109            1 :                 .exists()
    8110              :         );
    8111              : 
    8112            2 :         Ok(())
    8113            1 :     }
    8114              : 
    8115              :     #[tokio::test]
    8116            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    8117            1 :         let names_algorithms = [
    8118            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    8119            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    8120            1 :         ];
    8121            3 :         for (name, algorithm) in names_algorithms {
    8122            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    8123            1 :         }
    8124            1 :         Ok(())
    8125            1 :     }
    8126              : 
    8127            2 :     async fn test_read_at_max_lsn_algorithm(
    8128            2 :         name: &'static str,
    8129            2 :         compaction_algorithm: CompactionAlgorithm,
    8130            2 :     ) -> anyhow::Result<()> {
    8131            2 :         let mut harness = TenantHarness::create(name).await?;
    8132            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    8133            2 :             kind: compaction_algorithm,
    8134            2 :         });
    8135            2 :         let (tenant, ctx) = harness.load().await;
    8136            2 :         let tline = tenant
    8137            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    8138            2 :             .await?;
    8139              : 
    8140            2 :         let lsn = Lsn(0x10);
    8141            2 :         let compact = false;
    8142            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    8143              : 
    8144            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8145            2 :         let read_lsn = Lsn(u64::MAX - 1);
    8146              : 
    8147            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    8148            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    8149              : 
    8150            2 :         Ok(())
    8151            2 :     }
    8152              : 
    8153              :     #[tokio::test]
    8154            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    8155            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    8156            1 :         let (tenant, ctx) = harness.load().await;
    8157            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8158            1 :         let tline = tenant
    8159            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8160            1 :             .await?;
    8161              : 
    8162              :         const NUM_KEYS: usize = 1000;
    8163              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8164              : 
    8165            1 :         let cancel = CancellationToken::new();
    8166              : 
    8167            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8168            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8169            1 :         let mut test_key = base_key;
    8170              : 
    8171              :         // Track when each page was last modified. Used to assert that
    8172              :         // a read sees the latest page version.
    8173            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    8174              : 
    8175            1 :         let mut lsn = Lsn(0x10);
    8176              :         #[allow(clippy::needless_range_loop)]
    8177         1001 :         for blknum in 0..NUM_KEYS {
    8178         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8179         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8180         1000 :             let mut writer = tline.writer().await;
    8181         1000 :             writer
    8182         1000 :                 .put(
    8183         1000 :                     test_key,
    8184         1000 :                     lsn,
    8185         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8186         1000 :                     &ctx,
    8187         1000 :                 )
    8188         1000 :                 .await?;
    8189         1000 :             writer.finish_write(lsn);
    8190         1000 :             updated[blknum] = lsn;
    8191         1000 :             drop(writer);
    8192              :         }
    8193              : 
    8194            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8195              : 
    8196           12 :         for iter in 0..=10 {
    8197            1 :             // Read all the blocks
    8198        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8199        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8200        11000 :                 assert_eq!(
    8201        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8202        11000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    8203            1 :                 );
    8204            1 :             }
    8205            1 : 
    8206           11 :             let mut cnt = 0;
    8207           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8208            1 : 
    8209        11000 :             for (key, value) in tline
    8210           11 :                 .get_vectored_impl(
    8211           11 :                     query,
    8212           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8213           11 :                     &ctx,
    8214           11 :                 )
    8215           11 :                 .await?
    8216            1 :             {
    8217        11000 :                 let blknum = key.field6 as usize;
    8218        11000 :                 let value = value?;
    8219        11000 :                 assert!(blknum % STEP == 0);
    8220        11000 :                 let blknum = blknum / STEP;
    8221        11000 :                 assert_eq!(
    8222            1 :                     value,
    8223        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8224            1 :                 );
    8225        11000 :                 cnt += 1;
    8226            1 :             }
    8227            1 : 
    8228           11 :             assert_eq!(cnt, NUM_KEYS);
    8229            1 : 
    8230        11011 :             for _ in 0..NUM_KEYS {
    8231        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8232        11000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8233        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8234        11000 :                 let mut writer = tline.writer().await;
    8235        11000 :                 writer
    8236        11000 :                     .put(
    8237        11000 :                         test_key,
    8238        11000 :                         lsn,
    8239        11000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8240        11000 :                         &ctx,
    8241        11000 :                     )
    8242        11000 :                     .await?;
    8243        11000 :                 writer.finish_write(lsn);
    8244        11000 :                 drop(writer);
    8245        11000 :                 updated[blknum] = lsn;
    8246            1 :             }
    8247            1 : 
    8248            1 :             // Perform two cycles of flush, compact, and GC
    8249           33 :             for round in 0..2 {
    8250           22 :                 tline.freeze_and_flush().await?;
    8251           22 :                 tline
    8252           22 :                     .compact(
    8253           22 :                         &cancel,
    8254           22 :                         if iter % 5 == 0 && round == 0 {
    8255            3 :                             let mut flags = EnumSet::new();
    8256            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8257            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8258            3 :                             flags
    8259            1 :                         } else {
    8260           19 :                             EnumSet::empty()
    8261            1 :                         },
    8262           22 :                         &ctx,
    8263            1 :                     )
    8264           22 :                     .await?;
    8265           22 :                 tenant
    8266           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8267           22 :                     .await?;
    8268            1 :             }
    8269            1 :         }
    8270            1 : 
    8271            1 :         Ok(())
    8272            1 :     }
    8273              : 
    8274              :     #[tokio::test]
    8275            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8276            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8277            1 :         let (tenant, ctx) = harness.load().await;
    8278            1 :         let tline = tenant
    8279            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8280            1 :             .await?;
    8281              : 
    8282            1 :         let cancel = CancellationToken::new();
    8283              : 
    8284            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8285            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8286            1 :         let test_key = base_key;
    8287            1 :         let mut lsn = Lsn(0x10);
    8288              : 
    8289           21 :         for _ in 0..20 {
    8290           20 :             lsn = Lsn(lsn.0 + 0x10);
    8291           20 :             let mut writer = tline.writer().await;
    8292           20 :             writer
    8293           20 :                 .put(
    8294           20 :                     test_key,
    8295           20 :                     lsn,
    8296           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8297           20 :                     &ctx,
    8298           20 :                 )
    8299           20 :                 .await?;
    8300           20 :             writer.finish_write(lsn);
    8301           20 :             drop(writer);
    8302           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8303              :         }
    8304              : 
    8305            1 :         let before_num_l0_delta_files = tline
    8306            1 :             .layers
    8307            1 :             .read(LayerManagerLockHolder::Testing)
    8308            1 :             .await
    8309            1 :             .layer_map()?
    8310            1 :             .level0_deltas()
    8311            1 :             .len();
    8312              : 
    8313            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8314              : 
    8315            1 :         let after_num_l0_delta_files = tline
    8316            1 :             .layers
    8317            1 :             .read(LayerManagerLockHolder::Testing)
    8318            1 :             .await
    8319            1 :             .layer_map()?
    8320            1 :             .level0_deltas()
    8321            1 :             .len();
    8322              : 
    8323            1 :         assert!(
    8324            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8325            0 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8326              :         );
    8327              : 
    8328            1 :         assert_eq!(
    8329            1 :             tline.get(test_key, lsn, &ctx).await?,
    8330            1 :             test_img(&format!("{} at {}", 0, lsn))
    8331              :         );
    8332              : 
    8333            2 :         Ok(())
    8334            1 :     }
    8335              : 
    8336              :     #[tokio::test]
    8337            1 :     async fn test_aux_file_e2e() {
    8338            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8339              : 
    8340            1 :         let (tenant, ctx) = harness.load().await;
    8341            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8342              : 
    8343            1 :         let mut lsn = Lsn(0x08);
    8344              : 
    8345            1 :         let tline: Arc<Timeline> = tenant
    8346            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8347            1 :             .await
    8348            1 :             .unwrap();
    8349              : 
    8350              :         {
    8351            1 :             lsn += 8;
    8352            1 :             let mut modification = tline.begin_modification(lsn);
    8353            1 :             modification
    8354            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8355            1 :                 .await
    8356            1 :                 .unwrap();
    8357            1 :             modification.commit(&ctx).await.unwrap();
    8358              :         }
    8359              : 
    8360              :         // we can read everything from the storage
    8361            1 :         let files = tline
    8362            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8363            1 :             .await
    8364            1 :             .unwrap();
    8365            1 :         assert_eq!(
    8366            1 :             files.get("pg_logical/mappings/test1"),
    8367            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8368              :         );
    8369              : 
    8370              :         {
    8371            1 :             lsn += 8;
    8372            1 :             let mut modification = tline.begin_modification(lsn);
    8373            1 :             modification
    8374            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8375            1 :                 .await
    8376            1 :                 .unwrap();
    8377            1 :             modification.commit(&ctx).await.unwrap();
    8378              :         }
    8379              : 
    8380            1 :         let files = tline
    8381            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8382            1 :             .await
    8383            1 :             .unwrap();
    8384            1 :         assert_eq!(
    8385            1 :             files.get("pg_logical/mappings/test2"),
    8386            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8387              :         );
    8388              : 
    8389            1 :         let child = tenant
    8390            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8391            1 :             .await
    8392            1 :             .unwrap();
    8393              : 
    8394            1 :         let files = child
    8395            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8396            1 :             .await
    8397            1 :             .unwrap();
    8398            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8399            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8400            1 :     }
    8401              : 
    8402              :     #[tokio::test]
    8403            1 :     async fn test_repl_origin_tombstones() {
    8404            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8405            1 :             .await
    8406            1 :             .unwrap();
    8407              : 
    8408            1 :         let (tenant, ctx) = harness.load().await;
    8409            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8410              : 
    8411            1 :         let mut lsn = Lsn(0x08);
    8412              : 
    8413            1 :         let tline: Arc<Timeline> = tenant
    8414            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8415            1 :             .await
    8416            1 :             .unwrap();
    8417              : 
    8418            1 :         let repl_lsn = Lsn(0x10);
    8419              :         {
    8420            1 :             lsn += 8;
    8421            1 :             let mut modification = tline.begin_modification(lsn);
    8422            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8423            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8424            1 :             modification.commit(&ctx).await.unwrap();
    8425              :         }
    8426              : 
    8427              :         // we can read everything from the storage
    8428            1 :         let repl_origins = tline
    8429            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8430            1 :             .await
    8431            1 :             .unwrap();
    8432            1 :         assert_eq!(repl_origins.len(), 1);
    8433            1 :         assert_eq!(repl_origins[&1], lsn);
    8434              : 
    8435              :         {
    8436            1 :             lsn += 8;
    8437            1 :             let mut modification = tline.begin_modification(lsn);
    8438            1 :             modification.put_for_unit_test(
    8439            1 :                 repl_origin_key(3),
    8440            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8441              :             );
    8442            1 :             modification.commit(&ctx).await.unwrap();
    8443              :         }
    8444            1 :         let result = tline
    8445            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8446            1 :             .await;
    8447            1 :         assert!(result.is_err());
    8448            1 :     }
    8449              : 
    8450              :     #[tokio::test]
    8451            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8452            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8453            1 :         let (tenant, ctx) = harness.load().await;
    8454            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8455            1 :         let tline = tenant
    8456            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8457            1 :             .await?;
    8458              : 
    8459              :         const NUM_KEYS: usize = 1000;
    8460              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8461              : 
    8462            1 :         let cancel = CancellationToken::new();
    8463              : 
    8464            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8465            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8466            1 :         let mut test_key = base_key;
    8467            1 :         let mut lsn = Lsn(0x10);
    8468              : 
    8469            4 :         async fn scan_with_statistics(
    8470            4 :             tline: &Timeline,
    8471            4 :             keyspace: &KeySpace,
    8472            4 :             lsn: Lsn,
    8473            4 :             ctx: &RequestContext,
    8474            4 :             io_concurrency: IoConcurrency,
    8475            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8476            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8477            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8478            4 :             let res = tline
    8479            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8480            4 :                 .await?;
    8481            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8482            4 :         }
    8483              : 
    8484         1001 :         for blknum in 0..NUM_KEYS {
    8485         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8486         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8487         1000 :             let mut writer = tline.writer().await;
    8488         1000 :             writer
    8489         1000 :                 .put(
    8490         1000 :                     test_key,
    8491         1000 :                     lsn,
    8492         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8493         1000 :                     &ctx,
    8494         1000 :                 )
    8495         1000 :                 .await?;
    8496         1000 :             writer.finish_write(lsn);
    8497         1000 :             drop(writer);
    8498              :         }
    8499              : 
    8500            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8501              : 
    8502           11 :         for iter in 1..=10 {
    8503        10010 :             for _ in 0..NUM_KEYS {
    8504        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8505        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8506        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8507        10000 :                 let mut writer = tline.writer().await;
    8508        10000 :                 writer
    8509        10000 :                     .put(
    8510        10000 :                         test_key,
    8511        10000 :                         lsn,
    8512        10000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8513        10000 :                         &ctx,
    8514        10000 :                     )
    8515        10000 :                     .await?;
    8516        10000 :                 writer.finish_write(lsn);
    8517        10000 :                 drop(writer);
    8518            1 :             }
    8519            1 : 
    8520           10 :             tline.freeze_and_flush().await?;
    8521            1 :             // Force layers to L1
    8522           10 :             tline
    8523           10 :                 .compact(
    8524           10 :                     &cancel,
    8525           10 :                     {
    8526           10 :                         let mut flags = EnumSet::new();
    8527           10 :                         flags.insert(CompactFlags::ForceL0Compaction);
    8528           10 :                         flags
    8529           10 :                     },
    8530           10 :                     &ctx,
    8531           10 :                 )
    8532           10 :                 .await?;
    8533            1 : 
    8534           10 :             if iter % 5 == 0 {
    8535            2 :                 let scan_lsn = Lsn(lsn.0 + 1);
    8536            2 :                 info!("scanning at {}", scan_lsn);
    8537            2 :                 let (_, before_delta_file_accessed) =
    8538            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8539            2 :                         .await?;
    8540            2 :                 tline
    8541            2 :                     .compact(
    8542            2 :                         &cancel,
    8543            2 :                         {
    8544            2 :                             let mut flags = EnumSet::new();
    8545            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8546            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8547            2 :                             flags.insert(CompactFlags::ForceL0Compaction);
    8548            2 :                             flags
    8549            2 :                         },
    8550            2 :                         &ctx,
    8551            2 :                     )
    8552            2 :                     .await?;
    8553            2 :                 let (_, after_delta_file_accessed) =
    8554            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8555            2 :                         .await?;
    8556            2 :                 assert!(
    8557            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8558            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8559            1 :                 );
    8560            1 :                 // 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.
    8561            2 :                 assert!(
    8562            2 :                     after_delta_file_accessed <= 2,
    8563            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8564            1 :                 );
    8565            8 :             }
    8566            1 :         }
    8567            1 : 
    8568            1 :         Ok(())
    8569            1 :     }
    8570              : 
    8571              :     #[tokio::test]
    8572            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8573            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8574            1 :         let (tenant, ctx) = harness.load().await;
    8575              : 
    8576            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8577            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8578            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8579              : 
    8580            1 :         let tline = tenant
    8581            1 :             .create_test_timeline_with_layers(
    8582            1 :                 TIMELINE_ID,
    8583            1 :                 Lsn(0x10),
    8584            1 :                 DEFAULT_PG_VERSION,
    8585            1 :                 &ctx,
    8586            1 :                 Vec::new(), // in-memory layers
    8587            1 :                 Vec::new(), // delta layers
    8588            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8589            1 :                 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
    8590            1 :             )
    8591            1 :             .await?;
    8592            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8593              : 
    8594            1 :         let child = tenant
    8595            1 :             .branch_timeline_test_with_layers(
    8596            1 :                 &tline,
    8597            1 :                 NEW_TIMELINE_ID,
    8598            1 :                 Some(Lsn(0x20)),
    8599            1 :                 &ctx,
    8600            1 :                 Vec::new(), // delta layers
    8601            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8602            1 :                 Lsn(0x30),
    8603            1 :             )
    8604            1 :             .await
    8605            1 :             .unwrap();
    8606              : 
    8607            1 :         let lsn = Lsn(0x30);
    8608              : 
    8609              :         // test vectored get on parent timeline
    8610            1 :         assert_eq!(
    8611            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8612            1 :             Some(test_img("data key 1"))
    8613              :         );
    8614            1 :         assert!(
    8615            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8616            1 :                 .await
    8617            1 :                 .unwrap_err()
    8618            1 :                 .is_missing_key_error()
    8619              :         );
    8620            1 :         assert!(
    8621            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8622            1 :                 .await
    8623            1 :                 .unwrap_err()
    8624            1 :                 .is_missing_key_error()
    8625              :         );
    8626              : 
    8627              :         // test vectored get on child timeline
    8628            1 :         assert_eq!(
    8629            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8630            1 :             Some(test_img("data key 1"))
    8631              :         );
    8632            1 :         assert_eq!(
    8633            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8634            1 :             Some(test_img("data key 2"))
    8635              :         );
    8636            1 :         assert!(
    8637            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8638            1 :                 .await
    8639            1 :                 .unwrap_err()
    8640            1 :                 .is_missing_key_error()
    8641              :         );
    8642              : 
    8643            2 :         Ok(())
    8644            1 :     }
    8645              : 
    8646              :     #[tokio::test]
    8647            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8648            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8649            1 :         let (tenant, ctx) = harness.load().await;
    8650            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8651              : 
    8652            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8653            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8654            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8655            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8656              : 
    8657            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8658            1 :         let base_inherited_key_child =
    8659            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8660            1 :         let base_inherited_key_nonexist =
    8661            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8662            1 :         let base_inherited_key_overwrite =
    8663            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8664              : 
    8665            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8666            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8667              : 
    8668            1 :         let tline = tenant
    8669            1 :             .create_test_timeline_with_layers(
    8670            1 :                 TIMELINE_ID,
    8671            1 :                 Lsn(0x10),
    8672            1 :                 DEFAULT_PG_VERSION,
    8673            1 :                 &ctx,
    8674            1 :                 Vec::new(), // in-memory layers
    8675            1 :                 Vec::new(), // delta layers
    8676            1 :                 vec![(
    8677            1 :                     Lsn(0x20),
    8678            1 :                     vec![
    8679            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8680            1 :                         (
    8681            1 :                             base_inherited_key_overwrite,
    8682            1 :                             test_img("metadata key overwrite 1a"),
    8683            1 :                         ),
    8684            1 :                         (base_key, test_img("metadata key 1")),
    8685            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8686            1 :                     ],
    8687            1 :                 )], // image layers
    8688            1 :                 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
    8689            1 :             )
    8690            1 :             .await?;
    8691              : 
    8692            1 :         let child = tenant
    8693            1 :             .branch_timeline_test_with_layers(
    8694            1 :                 &tline,
    8695            1 :                 NEW_TIMELINE_ID,
    8696            1 :                 Some(Lsn(0x20)),
    8697            1 :                 &ctx,
    8698            1 :                 Vec::new(), // delta layers
    8699            1 :                 vec![(
    8700            1 :                     Lsn(0x30),
    8701            1 :                     vec![
    8702            1 :                         (
    8703            1 :                             base_inherited_key_child,
    8704            1 :                             test_img("metadata inherited key 2"),
    8705            1 :                         ),
    8706            1 :                         (
    8707            1 :                             base_inherited_key_overwrite,
    8708            1 :                             test_img("metadata key overwrite 2a"),
    8709            1 :                         ),
    8710            1 :                         (base_key_child, test_img("metadata key 2")),
    8711            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8712            1 :                     ],
    8713            1 :                 )], // image layers
    8714            1 :                 Lsn(0x30),
    8715            1 :             )
    8716            1 :             .await
    8717            1 :             .unwrap();
    8718              : 
    8719            1 :         let lsn = Lsn(0x30);
    8720              : 
    8721              :         // test vectored get on parent timeline
    8722            1 :         assert_eq!(
    8723            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8724            1 :             Some(test_img("metadata key 1"))
    8725              :         );
    8726            1 :         assert_eq!(
    8727            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8728              :             None
    8729              :         );
    8730            1 :         assert_eq!(
    8731            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8732              :             None
    8733              :         );
    8734            1 :         assert_eq!(
    8735            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8736            1 :             Some(test_img("metadata key overwrite 1b"))
    8737              :         );
    8738            1 :         assert_eq!(
    8739            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8740            1 :             Some(test_img("metadata inherited key 1"))
    8741              :         );
    8742            1 :         assert_eq!(
    8743            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8744              :             None
    8745              :         );
    8746            1 :         assert_eq!(
    8747            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8748              :             None
    8749              :         );
    8750            1 :         assert_eq!(
    8751            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8752            1 :             Some(test_img("metadata key overwrite 1a"))
    8753              :         );
    8754              : 
    8755              :         // test vectored get on child timeline
    8756            1 :         assert_eq!(
    8757            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8758              :             None
    8759              :         );
    8760            1 :         assert_eq!(
    8761            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8762            1 :             Some(test_img("metadata key 2"))
    8763              :         );
    8764            1 :         assert_eq!(
    8765            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8766              :             None
    8767              :         );
    8768            1 :         assert_eq!(
    8769            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8770            1 :             Some(test_img("metadata inherited key 1"))
    8771              :         );
    8772            1 :         assert_eq!(
    8773            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8774            1 :             Some(test_img("metadata inherited key 2"))
    8775              :         );
    8776            1 :         assert_eq!(
    8777            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8778              :             None
    8779              :         );
    8780            1 :         assert_eq!(
    8781            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8782            1 :             Some(test_img("metadata key overwrite 2b"))
    8783              :         );
    8784            1 :         assert_eq!(
    8785            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8786            1 :             Some(test_img("metadata key overwrite 2a"))
    8787              :         );
    8788              : 
    8789              :         // test vectored scan on parent timeline
    8790            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8791            1 :         let query =
    8792            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8793            1 :         let res = tline
    8794            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8795            1 :             .await?;
    8796              : 
    8797            1 :         assert_eq!(
    8798            1 :             res.into_iter()
    8799            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8800            1 :                 .collect::<Vec<_>>(),
    8801            1 :             vec![
    8802            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8803            1 :                 (
    8804            1 :                     base_inherited_key_overwrite,
    8805            1 :                     test_img("metadata key overwrite 1a")
    8806            1 :                 ),
    8807            1 :                 (base_key, test_img("metadata key 1")),
    8808            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8809              :             ]
    8810              :         );
    8811              : 
    8812              :         // test vectored scan on child timeline
    8813            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8814            1 :         let query =
    8815            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8816            1 :         let res = child
    8817            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8818            1 :             .await?;
    8819              : 
    8820            1 :         assert_eq!(
    8821            1 :             res.into_iter()
    8822            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8823            1 :                 .collect::<Vec<_>>(),
    8824            1 :             vec![
    8825            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8826            1 :                 (
    8827            1 :                     base_inherited_key_child,
    8828            1 :                     test_img("metadata inherited key 2")
    8829            1 :                 ),
    8830            1 :                 (
    8831            1 :                     base_inherited_key_overwrite,
    8832            1 :                     test_img("metadata key overwrite 2a")
    8833            1 :                 ),
    8834            1 :                 (base_key_child, test_img("metadata key 2")),
    8835            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8836              :             ]
    8837              :         );
    8838              : 
    8839            2 :         Ok(())
    8840            1 :     }
    8841              : 
    8842           28 :     async fn get_vectored_impl_wrapper(
    8843           28 :         tline: &Arc<Timeline>,
    8844           28 :         key: Key,
    8845           28 :         lsn: Lsn,
    8846           28 :         ctx: &RequestContext,
    8847           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8848           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8849           28 :             tline.conf.get_vectored_concurrent_io,
    8850           28 :             tline.gate.enter().unwrap(),
    8851              :         );
    8852           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8853           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8854           28 :         let mut res = tline
    8855           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8856           28 :             .await?;
    8857           25 :         Ok(res.pop_last().map(|(k, v)| {
    8858           16 :             assert_eq!(k, key);
    8859           16 :             v.unwrap()
    8860           16 :         }))
    8861           28 :     }
    8862              : 
    8863              :     #[tokio::test]
    8864            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8865            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8866            1 :         let (tenant, ctx) = harness.load().await;
    8867            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8868            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8869            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8870            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8871              : 
    8872              :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8873              :         // Lsn 0x30 key0, key3, no key1+key2
    8874              :         // Lsn 0x20 key1+key2 tomestones
    8875              :         // Lsn 0x10 key1 in image, key2 in delta
    8876            1 :         let tline = tenant
    8877            1 :             .create_test_timeline_with_layers(
    8878            1 :                 TIMELINE_ID,
    8879            1 :                 Lsn(0x10),
    8880            1 :                 DEFAULT_PG_VERSION,
    8881            1 :                 &ctx,
    8882            1 :                 Vec::new(), // in-memory layers
    8883            1 :                 // delta layers
    8884            1 :                 vec![
    8885            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8886            1 :                         Lsn(0x10)..Lsn(0x20),
    8887            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8888            1 :                     ),
    8889            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8890            1 :                         Lsn(0x20)..Lsn(0x30),
    8891            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8892            1 :                     ),
    8893            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8894            1 :                         Lsn(0x20)..Lsn(0x30),
    8895            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8896            1 :                     ),
    8897            1 :                 ],
    8898            1 :                 // image layers
    8899            1 :                 vec![
    8900            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8901            1 :                     (
    8902            1 :                         Lsn(0x30),
    8903            1 :                         vec![
    8904            1 :                             (key0, test_img("metadata key 0")),
    8905            1 :                             (key3, test_img("metadata key 3")),
    8906            1 :                         ],
    8907            1 :                     ),
    8908            1 :                 ],
    8909            1 :                 Lsn(0x30),
    8910            1 :             )
    8911            1 :             .await?;
    8912              : 
    8913            1 :         let lsn = Lsn(0x30);
    8914            1 :         let old_lsn = Lsn(0x20);
    8915              : 
    8916            1 :         assert_eq!(
    8917            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8918            1 :             Some(test_img("metadata key 0"))
    8919              :         );
    8920            1 :         assert_eq!(
    8921            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8922              :             None,
    8923              :         );
    8924            1 :         assert_eq!(
    8925            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8926              :             None,
    8927              :         );
    8928            1 :         assert_eq!(
    8929            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8930            1 :             Some(Bytes::new()),
    8931              :         );
    8932            1 :         assert_eq!(
    8933            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8934            1 :             Some(Bytes::new()),
    8935              :         );
    8936            1 :         assert_eq!(
    8937            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8938            1 :             Some(test_img("metadata key 3"))
    8939              :         );
    8940              : 
    8941            2 :         Ok(())
    8942            1 :     }
    8943              : 
    8944              :     #[tokio::test]
    8945            1 :     async fn test_metadata_tombstone_image_creation() {
    8946            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8947            1 :             .await
    8948            1 :             .unwrap();
    8949            1 :         let (tenant, ctx) = harness.load().await;
    8950            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8951              : 
    8952            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8953            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8954            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8955            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8956              : 
    8957            1 :         let tline = tenant
    8958            1 :             .create_test_timeline_with_layers(
    8959            1 :                 TIMELINE_ID,
    8960            1 :                 Lsn(0x10),
    8961            1 :                 DEFAULT_PG_VERSION,
    8962            1 :                 &ctx,
    8963            1 :                 Vec::new(), // in-memory layers
    8964            1 :                 // delta layers
    8965            1 :                 vec![
    8966            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8967            1 :                         Lsn(0x10)..Lsn(0x20),
    8968            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8969            1 :                     ),
    8970            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8971            1 :                         Lsn(0x20)..Lsn(0x30),
    8972            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8973            1 :                     ),
    8974            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8975            1 :                         Lsn(0x20)..Lsn(0x30),
    8976            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8977            1 :                     ),
    8978            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8979            1 :                         Lsn(0x30)..Lsn(0x40),
    8980            1 :                         vec![
    8981            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8982            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8983            1 :                         ],
    8984            1 :                     ),
    8985            1 :                 ],
    8986            1 :                 // image layers
    8987            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8988            1 :                 Lsn(0x40),
    8989            1 :             )
    8990            1 :             .await
    8991            1 :             .unwrap();
    8992              : 
    8993            1 :         let cancel = CancellationToken::new();
    8994              : 
    8995              :         // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
    8996            1 :         tline.force_set_disk_consistent_lsn(Lsn(0x40));
    8997            1 :         tline
    8998            1 :             .compact(
    8999            1 :                 &cancel,
    9000            1 :                 {
    9001            1 :                     let mut flags = EnumSet::new();
    9002            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9003            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9004            1 :                     flags
    9005            1 :                 },
    9006            1 :                 &ctx,
    9007            1 :             )
    9008            1 :             .await
    9009            1 :             .unwrap();
    9010              :         // Image layers are created at repartition LSN
    9011            1 :         let images = tline
    9012            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    9013            1 :             .await
    9014            1 :             .unwrap()
    9015            1 :             .into_iter()
    9016            9 :             .filter(|(k, _)| k.is_metadata_key())
    9017            1 :             .collect::<Vec<_>>();
    9018            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    9019            1 :     }
    9020              : 
    9021              :     #[tokio::test]
    9022            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    9023            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    9024            1 :             .await
    9025            1 :             .unwrap();
    9026            1 :         let (tenant, ctx) = harness.load().await;
    9027            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9028              : 
    9029            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    9030            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    9031              : 
    9032            1 :         let tline = tenant
    9033            1 :             .create_test_timeline_with_layers(
    9034            1 :                 TIMELINE_ID,
    9035            1 :                 Lsn(0x10),
    9036            1 :                 DEFAULT_PG_VERSION,
    9037            1 :                 &ctx,
    9038            1 :                 Vec::new(), // in-memory layers
    9039            1 :                 // delta layers
    9040            1 :                 vec![
    9041            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9042            1 :                         Lsn(0x10)..Lsn(0x20),
    9043            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    9044            1 :                     ),
    9045            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9046            1 :                         Lsn(0x20)..Lsn(0x30),
    9047            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    9048            1 :                     ),
    9049            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9050            1 :                         Lsn(0x20)..Lsn(0x30),
    9051            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    9052            1 :                     ),
    9053            1 :                 ],
    9054            1 :                 // image layers
    9055            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9056            1 :                 Lsn(0x30),
    9057            1 :             )
    9058            1 :             .await
    9059            1 :             .unwrap();
    9060              : 
    9061            1 :         let cancel = CancellationToken::new();
    9062              : 
    9063            1 :         tline
    9064            1 :             .compact(
    9065            1 :                 &cancel,
    9066            1 :                 {
    9067            1 :                     let mut flags = EnumSet::new();
    9068            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9069            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9070            1 :                     flags
    9071            1 :                 },
    9072            1 :                 &ctx,
    9073            1 :             )
    9074            1 :             .await
    9075            1 :             .unwrap();
    9076              : 
    9077              :         // Image layers are created at last_record_lsn
    9078            1 :         let images = tline
    9079            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9080            1 :             .await
    9081            1 :             .unwrap()
    9082            1 :             .into_iter()
    9083            7 :             .filter(|(k, _)| k.is_metadata_key())
    9084            1 :             .collect::<Vec<_>>();
    9085            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    9086            1 :     }
    9087              : 
    9088              :     #[tokio::test]
    9089            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    9090            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    9091            1 :         let (tenant, ctx) = harness.load().await;
    9092            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9093              : 
    9094           51 :         fn get_key(id: u32) -> Key {
    9095              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9096           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9097           51 :             key.field6 = id;
    9098           51 :             key
    9099           51 :         }
    9100              : 
    9101              :         // We create
    9102              :         // - one bottom-most image layer,
    9103              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9104              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9105              :         // - a delta layer D3 above the horizon.
    9106              :         //
    9107              :         //                             | D3 |
    9108              :         //  | D1 |
    9109              :         // -|    |-- gc horizon -----------------
    9110              :         //  |    |                | D2 |
    9111              :         // --------- img layer ------------------
    9112              :         //
    9113              :         // What we should expact from this compaction is:
    9114              :         //                             | D3 |
    9115              :         //  | Part of D1 |
    9116              :         // --------- img layer with D1+D2 at GC horizon------------------
    9117              : 
    9118              :         // img layer at 0x10
    9119            1 :         let img_layer = (0..10)
    9120           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9121            1 :             .collect_vec();
    9122              : 
    9123            1 :         let delta1 = vec![
    9124            1 :             (
    9125            1 :                 get_key(1),
    9126            1 :                 Lsn(0x20),
    9127            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    9128            1 :             ),
    9129            1 :             (
    9130            1 :                 get_key(2),
    9131            1 :                 Lsn(0x30),
    9132            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    9133            1 :             ),
    9134            1 :             (
    9135            1 :                 get_key(3),
    9136            1 :                 Lsn(0x40),
    9137            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    9138            1 :             ),
    9139              :         ];
    9140            1 :         let delta2 = vec![
    9141            1 :             (
    9142            1 :                 get_key(5),
    9143            1 :                 Lsn(0x20),
    9144            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    9145            1 :             ),
    9146            1 :             (
    9147            1 :                 get_key(6),
    9148            1 :                 Lsn(0x20),
    9149            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    9150            1 :             ),
    9151              :         ];
    9152            1 :         let delta3 = vec![
    9153            1 :             (
    9154            1 :                 get_key(8),
    9155            1 :                 Lsn(0x48),
    9156            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    9157            1 :             ),
    9158            1 :             (
    9159            1 :                 get_key(9),
    9160            1 :                 Lsn(0x48),
    9161            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    9162            1 :             ),
    9163              :         ];
    9164              : 
    9165            1 :         let tline = tenant
    9166            1 :             .create_test_timeline_with_layers(
    9167            1 :                 TIMELINE_ID,
    9168            1 :                 Lsn(0x10),
    9169            1 :                 DEFAULT_PG_VERSION,
    9170            1 :                 &ctx,
    9171            1 :                 Vec::new(), // in-memory layers
    9172            1 :                 vec![
    9173            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9174            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9175            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9176            1 :                 ], // delta layers
    9177            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9178            1 :                 Lsn(0x50),
    9179            1 :             )
    9180            1 :             .await?;
    9181              :         {
    9182            1 :             tline
    9183            1 :                 .applied_gc_cutoff_lsn
    9184            1 :                 .lock_for_write()
    9185            1 :                 .store_and_unlock(Lsn(0x30))
    9186            1 :                 .wait()
    9187            1 :                 .await;
    9188              :             // Update GC info
    9189            1 :             let mut guard = tline.gc_info.write().unwrap();
    9190            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    9191            1 :             guard.cutoffs.space = Lsn(0x30);
    9192              :         }
    9193              : 
    9194            1 :         let expected_result = [
    9195            1 :             Bytes::from_static(b"value 0@0x10"),
    9196            1 :             Bytes::from_static(b"value 1@0x20"),
    9197            1 :             Bytes::from_static(b"value 2@0x30"),
    9198            1 :             Bytes::from_static(b"value 3@0x40"),
    9199            1 :             Bytes::from_static(b"value 4@0x10"),
    9200            1 :             Bytes::from_static(b"value 5@0x20"),
    9201            1 :             Bytes::from_static(b"value 6@0x20"),
    9202            1 :             Bytes::from_static(b"value 7@0x10"),
    9203            1 :             Bytes::from_static(b"value 8@0x48"),
    9204            1 :             Bytes::from_static(b"value 9@0x48"),
    9205            1 :         ];
    9206              : 
    9207           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9208           10 :             assert_eq!(
    9209           10 :                 tline
    9210           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9211           10 :                     .await
    9212           10 :                     .unwrap(),
    9213              :                 expected
    9214              :             );
    9215              :         }
    9216              : 
    9217            1 :         let cancel = CancellationToken::new();
    9218            1 :         tline
    9219            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9220            1 :             .await
    9221            1 :             .unwrap();
    9222              : 
    9223           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9224           10 :             assert_eq!(
    9225           10 :                 tline
    9226           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9227           10 :                     .await
    9228           10 :                     .unwrap(),
    9229              :                 expected
    9230              :             );
    9231              :         }
    9232              : 
    9233              :         // Check if the image layer at the GC horizon contains exactly what we want
    9234            1 :         let image_at_gc_horizon = tline
    9235            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9236            1 :             .await
    9237            1 :             .unwrap()
    9238            1 :             .into_iter()
    9239           17 :             .filter(|(k, _)| k.is_metadata_key())
    9240            1 :             .collect::<Vec<_>>();
    9241              : 
    9242            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9243            1 :         let expected_result = [
    9244            1 :             Bytes::from_static(b"value 0@0x10"),
    9245            1 :             Bytes::from_static(b"value 1@0x20"),
    9246            1 :             Bytes::from_static(b"value 2@0x30"),
    9247            1 :             Bytes::from_static(b"value 3@0x10"),
    9248            1 :             Bytes::from_static(b"value 4@0x10"),
    9249            1 :             Bytes::from_static(b"value 5@0x20"),
    9250            1 :             Bytes::from_static(b"value 6@0x20"),
    9251            1 :             Bytes::from_static(b"value 7@0x10"),
    9252            1 :             Bytes::from_static(b"value 8@0x10"),
    9253            1 :             Bytes::from_static(b"value 9@0x10"),
    9254            1 :         ];
    9255           11 :         for idx in 0..10 {
    9256           10 :             assert_eq!(
    9257           10 :                 image_at_gc_horizon[idx],
    9258           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9259              :             );
    9260              :         }
    9261              : 
    9262              :         // Check if old layers are removed / new layers have the expected LSN
    9263            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9264            1 :         assert_eq!(
    9265              :             all_layers,
    9266            1 :             vec![
    9267              :                 // Image layer at GC horizon
    9268            1 :                 PersistentLayerKey {
    9269            1 :                     key_range: Key::MIN..Key::MAX,
    9270            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9271            1 :                     is_delta: false
    9272            1 :                 },
    9273              :                 // The delta layer below the horizon
    9274            1 :                 PersistentLayerKey {
    9275            1 :                     key_range: get_key(3)..get_key(4),
    9276            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9277            1 :                     is_delta: true
    9278            1 :                 },
    9279              :                 // The delta3 layer that should not be picked for the compaction
    9280            1 :                 PersistentLayerKey {
    9281            1 :                     key_range: get_key(8)..get_key(10),
    9282            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9283            1 :                     is_delta: true
    9284            1 :                 }
    9285              :             ]
    9286              :         );
    9287              : 
    9288              :         // increase GC horizon and compact again
    9289              :         {
    9290            1 :             tline
    9291            1 :                 .applied_gc_cutoff_lsn
    9292            1 :                 .lock_for_write()
    9293            1 :                 .store_and_unlock(Lsn(0x40))
    9294            1 :                 .wait()
    9295            1 :                 .await;
    9296              :             // Update GC info
    9297            1 :             let mut guard = tline.gc_info.write().unwrap();
    9298            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9299            1 :             guard.cutoffs.space = Lsn(0x40);
    9300              :         }
    9301            1 :         tline
    9302            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9303            1 :             .await
    9304            1 :             .unwrap();
    9305              : 
    9306            2 :         Ok(())
    9307            1 :     }
    9308              : 
    9309              :     #[cfg(feature = "testing")]
    9310              :     #[tokio::test]
    9311            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9312            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9313            1 :         let (tenant, ctx) = harness.load().await;
    9314              : 
    9315           17 :         fn get_key(id: u32) -> Key {
    9316              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9317           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9318           17 :             key.field6 = id;
    9319           17 :             key
    9320           17 :         }
    9321              : 
    9322            1 :         let delta1 = vec![
    9323            1 :             (
    9324            1 :                 get_key(1),
    9325            1 :                 Lsn(0x20),
    9326            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9327            1 :             ),
    9328            1 :             (
    9329            1 :                 get_key(1),
    9330            1 :                 Lsn(0x30),
    9331            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9332            1 :             ),
    9333            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9334            1 :             (
    9335            1 :                 get_key(2),
    9336            1 :                 Lsn(0x20),
    9337            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9338            1 :             ),
    9339            1 :             (
    9340            1 :                 get_key(2),
    9341            1 :                 Lsn(0x30),
    9342            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9343            1 :             ),
    9344            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9345            1 :             (
    9346            1 :                 get_key(3),
    9347            1 :                 Lsn(0x20),
    9348            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9349            1 :             ),
    9350            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9351            1 :             (
    9352            1 :                 get_key(4),
    9353            1 :                 Lsn(0x20),
    9354            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9355            1 :             ),
    9356            1 :             (
    9357            1 :                 get_key(4),
    9358            1 :                 Lsn(0x30),
    9359            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9360            1 :             ),
    9361            1 :             (
    9362            1 :                 get_key(5),
    9363            1 :                 Lsn(0x20),
    9364            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9365            1 :             ),
    9366            1 :             (
    9367            1 :                 get_key(5),
    9368            1 :                 Lsn(0x30),
    9369            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9370            1 :             ),
    9371              :         ];
    9372            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9373              : 
    9374            1 :         let tline = tenant
    9375            1 :             .create_test_timeline_with_layers(
    9376            1 :                 TIMELINE_ID,
    9377            1 :                 Lsn(0x10),
    9378            1 :                 DEFAULT_PG_VERSION,
    9379            1 :                 &ctx,
    9380            1 :                 Vec::new(), // in-memory layers
    9381            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9382            1 :                     Lsn(0x10)..Lsn(0x40),
    9383            1 :                     delta1,
    9384            1 :                 )], // delta layers
    9385            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9386            1 :                 Lsn(0x50),
    9387            1 :             )
    9388            1 :             .await?;
    9389              : 
    9390            1 :         assert_eq!(
    9391            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9392            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9393              :         );
    9394            1 :         assert_eq!(
    9395            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9396            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9397              :         );
    9398              : 
    9399              :         // Need to remove the limit of "Neon WAL redo requires base image".
    9400              : 
    9401            1 :         assert_eq!(
    9402            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9403            1 :             Bytes::from_static(b"c")
    9404              :         );
    9405            1 :         assert_eq!(
    9406            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9407            1 :             Bytes::from_static(b"ij")
    9408              :         );
    9409              : 
    9410              :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9411              :         // cannot enable this assertion in the unit test.
    9412              :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9413              : 
    9414            2 :         Ok(())
    9415            1 :     }
    9416              : 
    9417              :     #[tokio::test]
    9418            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9419            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9420            1 :             .await
    9421            1 :             .unwrap()
    9422            1 :             .load()
    9423            1 :             .await;
    9424              :         // set a non-zero lease length to test the feature
    9425            1 :         tenant
    9426            1 :             .update_tenant_config(|mut conf| {
    9427            1 :                 conf.lsn_lease_length = Some(LsnLease::DEFAULT_LENGTH);
    9428            1 :                 Ok(conf)
    9429            1 :             })
    9430            1 :             .unwrap();
    9431              : 
    9432            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9433              : 
    9434            1 :         let end_lsn = Lsn(0x100);
    9435            1 :         let image_layers = (0x20..=0x90)
    9436            1 :             .step_by(0x10)
    9437            8 :             .map(|n| (Lsn(n), vec![(key, test_img(&format!("data key at {n:x}")))]))
    9438            1 :             .collect();
    9439              : 
    9440            1 :         let timeline = tenant
    9441            1 :             .create_test_timeline_with_layers(
    9442            1 :                 TIMELINE_ID,
    9443            1 :                 Lsn(0x10),
    9444            1 :                 DEFAULT_PG_VERSION,
    9445            1 :                 &ctx,
    9446            1 :                 Vec::new(), // in-memory layers
    9447            1 :                 Vec::new(),
    9448            1 :                 image_layers,
    9449            1 :                 end_lsn,
    9450            1 :             )
    9451            1 :             .await?;
    9452              : 
    9453            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9454            1 :         let mut leases = Vec::new();
    9455            3 :         leased_lsns.iter().for_each(|n| {
    9456            3 :             leases.push(
    9457            3 :                 timeline
    9458            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9459            3 :                     .expect("lease request should succeed"),
    9460              :             );
    9461            3 :         });
    9462              : 
    9463            1 :         let updated_lease_0 = timeline
    9464            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9465            1 :             .expect("lease renewal should succeed");
    9466            1 :         assert_eq!(
    9467            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9468            0 :             " Renewing with shorter lease should not change the lease."
    9469              :         );
    9470              : 
    9471            1 :         let updated_lease_1 = timeline
    9472            1 :             .renew_lsn_lease(
    9473            1 :                 Lsn(leased_lsns[1]),
    9474            1 :                 timeline.get_lsn_lease_length() * 2,
    9475            1 :                 &ctx,
    9476            1 :             )
    9477            1 :             .expect("lease renewal should succeed");
    9478            1 :         assert!(
    9479            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9480            0 :             "Renewing with a long lease should renew lease with later expiration time."
    9481              :         );
    9482              : 
    9483              :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9484            1 :         info!(
    9485            0 :             "applied_gc_cutoff_lsn: {}",
    9486            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9487              :         );
    9488            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9489              : 
    9490            1 :         let res = tenant
    9491            1 :             .gc_iteration(
    9492            1 :                 Some(TIMELINE_ID),
    9493            1 :                 0,
    9494            1 :                 Duration::ZERO,
    9495            1 :                 &CancellationToken::new(),
    9496            1 :                 &ctx,
    9497            1 :             )
    9498            1 :             .await
    9499            1 :             .unwrap();
    9500              : 
    9501              :         // Keeping everything <= Lsn(0x80) b/c leases:
    9502              :         // 0/10: initdb layer
    9503              :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9504            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9505              :         // Keeping 0/90 b/c it is the latest layer.
    9506            1 :         assert_eq!(res.layers_not_updated, 1);
    9507              :         // Removed 0/80.
    9508            1 :         assert_eq!(res.layers_removed, 1);
    9509              : 
    9510              :         // Make lease on a already GC-ed LSN.
    9511              :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9512            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9513            1 :         timeline
    9514            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9515            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9516              : 
    9517              :         // Should still be able to renew a currently valid lease
    9518              :         // Assumption: original lease to is still valid for 0/50.
    9519              :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9520            1 :         timeline
    9521            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9522            1 :             .expect("lease renewal with validation should succeed");
    9523              : 
    9524            2 :         Ok(())
    9525            1 :     }
    9526              : 
    9527              :     #[tokio::test]
    9528            1 :     async fn test_failed_flush_should_not_update_disk_consistent_lsn() -> anyhow::Result<()> {
    9529              :         //
    9530              :         // Setup
    9531              :         //
    9532            1 :         let harness = TenantHarness::create_custom(
    9533            1 :             "test_failed_flush_should_not_upload_disk_consistent_lsn",
    9534            1 :             pageserver_api::models::TenantConfig::default(),
    9535            1 :             TenantId::generate(),
    9536            1 :             ShardIdentity::new(ShardNumber(0), ShardCount(4), ShardStripeSize(128)).unwrap(),
    9537            1 :             Generation::new(1),
    9538            1 :         )
    9539            1 :         .await?;
    9540            1 :         let (tenant, ctx) = harness.load().await;
    9541              : 
    9542            1 :         let timeline = tenant
    9543            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9544            1 :             .await?;
    9545            1 :         assert_eq!(timeline.get_shard_identity().count, ShardCount(4));
    9546            1 :         let mut writer = timeline.writer().await;
    9547            1 :         writer
    9548            1 :             .put(
    9549            1 :                 *TEST_KEY,
    9550            1 :                 Lsn(0x20),
    9551            1 :                 &Value::Image(test_img("foo at 0x20")),
    9552            1 :                 &ctx,
    9553            1 :             )
    9554            1 :             .await?;
    9555            1 :         writer.finish_write(Lsn(0x20));
    9556            1 :         drop(writer);
    9557            1 :         timeline.freeze_and_flush().await.unwrap();
    9558              : 
    9559            1 :         timeline.remote_client.wait_completion().await.unwrap();
    9560            1 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    9561            1 :         let remote_consistent_lsn = timeline.get_remote_consistent_lsn_projected();
    9562            1 :         assert_eq!(Some(disk_consistent_lsn), remote_consistent_lsn);
    9563              : 
    9564              :         //
    9565              :         // Test
    9566              :         //
    9567              : 
    9568            1 :         let mut writer = timeline.writer().await;
    9569            1 :         writer
    9570            1 :             .put(
    9571            1 :                 *TEST_KEY,
    9572            1 :                 Lsn(0x30),
    9573            1 :                 &Value::Image(test_img("foo at 0x30")),
    9574            1 :                 &ctx,
    9575            1 :             )
    9576            1 :             .await?;
    9577            1 :         writer.finish_write(Lsn(0x30));
    9578            1 :         drop(writer);
    9579              : 
    9580            1 :         fail::cfg(
    9581              :             "flush-layer-before-update-remote-consistent-lsn",
    9582            1 :             "return()",
    9583              :         )
    9584            1 :         .unwrap();
    9585              : 
    9586            1 :         let flush_res = timeline.freeze_and_flush().await;
    9587              :         // if flush failed, the disk/remote consistent LSN should not be updated
    9588            1 :         assert!(flush_res.is_err());
    9589            1 :         assert_eq!(disk_consistent_lsn, timeline.get_disk_consistent_lsn());
    9590            1 :         assert_eq!(
    9591              :             remote_consistent_lsn,
    9592            1 :             timeline.get_remote_consistent_lsn_projected()
    9593              :         );
    9594              : 
    9595            2 :         Ok(())
    9596            1 :     }
    9597              : 
    9598              :     #[cfg(feature = "testing")]
    9599              :     #[tokio::test]
    9600            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9601            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9602            2 :             "test_simple_bottom_most_compaction_deltas_1",
    9603            2 :             false,
    9604            2 :         )
    9605            2 :         .await
    9606            1 :     }
    9607              : 
    9608              :     #[cfg(feature = "testing")]
    9609              :     #[tokio::test]
    9610            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9611            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9612            2 :             "test_simple_bottom_most_compaction_deltas_2",
    9613            2 :             true,
    9614            2 :         )
    9615            2 :         .await
    9616            1 :     }
    9617              : 
    9618              :     #[cfg(feature = "testing")]
    9619            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9620            2 :         test_name: &'static str,
    9621            2 :         use_delta_bottom_layer: bool,
    9622            2 :     ) -> anyhow::Result<()> {
    9623            2 :         let harness = TenantHarness::create(test_name).await?;
    9624            2 :         let (tenant, ctx) = harness.load().await;
    9625              : 
    9626          138 :         fn get_key(id: u32) -> Key {
    9627              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9628          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9629          138 :             key.field6 = id;
    9630          138 :             key
    9631          138 :         }
    9632              : 
    9633              :         // We create
    9634              :         // - one bottom-most image layer,
    9635              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9636              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9637              :         // - a delta layer D3 above the horizon.
    9638              :         //
    9639              :         //                             | D3 |
    9640              :         //  | D1 |
    9641              :         // -|    |-- gc horizon -----------------
    9642              :         //  |    |                | D2 |
    9643              :         // --------- img layer ------------------
    9644              :         //
    9645              :         // What we should expact from this compaction is:
    9646              :         //                             | D3 |
    9647              :         //  | Part of D1 |
    9648              :         // --------- img layer with D1+D2 at GC horizon------------------
    9649              : 
    9650              :         // img layer at 0x10
    9651            2 :         let img_layer = (0..10)
    9652           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9653            2 :             .collect_vec();
    9654              :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9655            2 :         let delta4 = (0..10)
    9656           20 :             .map(|id| {
    9657           20 :                 (
    9658           20 :                     get_key(id),
    9659           20 :                     Lsn(0x08),
    9660           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9661           20 :                 )
    9662           20 :             })
    9663            2 :             .collect_vec();
    9664              : 
    9665            2 :         let delta1 = vec![
    9666            2 :             (
    9667            2 :                 get_key(1),
    9668            2 :                 Lsn(0x20),
    9669            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9670            2 :             ),
    9671            2 :             (
    9672            2 :                 get_key(2),
    9673            2 :                 Lsn(0x30),
    9674            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9675            2 :             ),
    9676            2 :             (
    9677            2 :                 get_key(3),
    9678            2 :                 Lsn(0x28),
    9679            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9680            2 :             ),
    9681            2 :             (
    9682            2 :                 get_key(3),
    9683            2 :                 Lsn(0x30),
    9684            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9685            2 :             ),
    9686            2 :             (
    9687            2 :                 get_key(3),
    9688            2 :                 Lsn(0x40),
    9689            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9690            2 :             ),
    9691              :         ];
    9692            2 :         let delta2 = vec![
    9693            2 :             (
    9694            2 :                 get_key(5),
    9695            2 :                 Lsn(0x20),
    9696            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9697            2 :             ),
    9698            2 :             (
    9699            2 :                 get_key(6),
    9700            2 :                 Lsn(0x20),
    9701            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9702            2 :             ),
    9703              :         ];
    9704            2 :         let delta3 = vec![
    9705            2 :             (
    9706            2 :                 get_key(8),
    9707            2 :                 Lsn(0x48),
    9708            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9709            2 :             ),
    9710            2 :             (
    9711            2 :                 get_key(9),
    9712            2 :                 Lsn(0x48),
    9713            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9714            2 :             ),
    9715              :         ];
    9716              : 
    9717            2 :         let tline = if use_delta_bottom_layer {
    9718            1 :             tenant
    9719            1 :                 .create_test_timeline_with_layers(
    9720            1 :                     TIMELINE_ID,
    9721            1 :                     Lsn(0x08),
    9722            1 :                     DEFAULT_PG_VERSION,
    9723            1 :                     &ctx,
    9724            1 :                     Vec::new(), // in-memory layers
    9725            1 :                     vec![
    9726            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9727            1 :                             Lsn(0x08)..Lsn(0x10),
    9728            1 :                             delta4,
    9729            1 :                         ),
    9730            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9731            1 :                             Lsn(0x20)..Lsn(0x48),
    9732            1 :                             delta1,
    9733            1 :                         ),
    9734            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9735            1 :                             Lsn(0x20)..Lsn(0x48),
    9736            1 :                             delta2,
    9737            1 :                         ),
    9738            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9739            1 :                             Lsn(0x48)..Lsn(0x50),
    9740            1 :                             delta3,
    9741            1 :                         ),
    9742            1 :                     ], // delta layers
    9743            1 :                     vec![],     // image layers
    9744            1 :                     Lsn(0x50),
    9745            1 :                 )
    9746            1 :                 .await?
    9747              :         } else {
    9748            1 :             tenant
    9749            1 :                 .create_test_timeline_with_layers(
    9750            1 :                     TIMELINE_ID,
    9751            1 :                     Lsn(0x10),
    9752            1 :                     DEFAULT_PG_VERSION,
    9753            1 :                     &ctx,
    9754            1 :                     Vec::new(), // in-memory layers
    9755            1 :                     vec![
    9756            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9757            1 :                             Lsn(0x10)..Lsn(0x48),
    9758            1 :                             delta1,
    9759            1 :                         ),
    9760            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9761            1 :                             Lsn(0x10)..Lsn(0x48),
    9762            1 :                             delta2,
    9763            1 :                         ),
    9764            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9765            1 :                             Lsn(0x48)..Lsn(0x50),
    9766            1 :                             delta3,
    9767            1 :                         ),
    9768            1 :                     ], // delta layers
    9769            1 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9770            1 :                     Lsn(0x50),
    9771            1 :                 )
    9772            1 :                 .await?
    9773              :         };
    9774              :         {
    9775            2 :             tline
    9776            2 :                 .applied_gc_cutoff_lsn
    9777            2 :                 .lock_for_write()
    9778            2 :                 .store_and_unlock(Lsn(0x30))
    9779            2 :                 .wait()
    9780            2 :                 .await;
    9781              :             // Update GC info
    9782            2 :             let mut guard = tline.gc_info.write().unwrap();
    9783            2 :             *guard = GcInfo {
    9784            2 :                 retain_lsns: vec![],
    9785            2 :                 cutoffs: GcCutoffs {
    9786            2 :                     time: Some(Lsn(0x30)),
    9787            2 :                     space: Lsn(0x30),
    9788            2 :                 },
    9789            2 :                 leases: Default::default(),
    9790            2 :                 within_ancestor_pitr: false,
    9791            2 :             };
    9792              :         }
    9793              : 
    9794            2 :         let expected_result = [
    9795            2 :             Bytes::from_static(b"value 0@0x10"),
    9796            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9797            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9798            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9799            2 :             Bytes::from_static(b"value 4@0x10"),
    9800            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9801            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9802            2 :             Bytes::from_static(b"value 7@0x10"),
    9803            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9804            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9805            2 :         ];
    9806              : 
    9807            2 :         let expected_result_at_gc_horizon = [
    9808            2 :             Bytes::from_static(b"value 0@0x10"),
    9809            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9810            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9811            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9812            2 :             Bytes::from_static(b"value 4@0x10"),
    9813            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9814            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9815            2 :             Bytes::from_static(b"value 7@0x10"),
    9816            2 :             Bytes::from_static(b"value 8@0x10"),
    9817            2 :             Bytes::from_static(b"value 9@0x10"),
    9818            2 :         ];
    9819              : 
    9820           22 :         for idx in 0..10 {
    9821           20 :             assert_eq!(
    9822           20 :                 tline
    9823           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9824           20 :                     .await
    9825           20 :                     .unwrap(),
    9826           20 :                 &expected_result[idx]
    9827              :             );
    9828           20 :             assert_eq!(
    9829           20 :                 tline
    9830           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9831           20 :                     .await
    9832           20 :                     .unwrap(),
    9833           20 :                 &expected_result_at_gc_horizon[idx]
    9834              :             );
    9835              :         }
    9836              : 
    9837            2 :         let cancel = CancellationToken::new();
    9838            2 :         tline
    9839            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9840            2 :             .await
    9841            2 :             .unwrap();
    9842              : 
    9843           22 :         for idx in 0..10 {
    9844           20 :             assert_eq!(
    9845           20 :                 tline
    9846           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9847           20 :                     .await
    9848           20 :                     .unwrap(),
    9849           20 :                 &expected_result[idx]
    9850              :             );
    9851           20 :             assert_eq!(
    9852           20 :                 tline
    9853           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9854           20 :                     .await
    9855           20 :                     .unwrap(),
    9856           20 :                 &expected_result_at_gc_horizon[idx]
    9857              :             );
    9858              :         }
    9859              : 
    9860              :         // increase GC horizon and compact again
    9861              :         {
    9862            2 :             tline
    9863            2 :                 .applied_gc_cutoff_lsn
    9864            2 :                 .lock_for_write()
    9865            2 :                 .store_and_unlock(Lsn(0x40))
    9866            2 :                 .wait()
    9867            2 :                 .await;
    9868              :             // Update GC info
    9869            2 :             let mut guard = tline.gc_info.write().unwrap();
    9870            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9871            2 :             guard.cutoffs.space = Lsn(0x40);
    9872              :         }
    9873            2 :         tline
    9874            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9875            2 :             .await
    9876            2 :             .unwrap();
    9877              : 
    9878            2 :         Ok(())
    9879            2 :     }
    9880              : 
    9881              :     #[cfg(feature = "testing")]
    9882              :     #[tokio::test]
    9883            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9884            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9885            1 :         let (tenant, ctx) = harness.load().await;
    9886            1 :         let tline = tenant
    9887            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9888            1 :             .await?;
    9889            1 :         tline.force_advance_lsn(Lsn(0x70));
    9890            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9891            1 :         let history = vec![
    9892            1 :             (
    9893            1 :                 key,
    9894            1 :                 Lsn(0x10),
    9895            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9896            1 :             ),
    9897            1 :             (
    9898            1 :                 key,
    9899            1 :                 Lsn(0x20),
    9900            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9901            1 :             ),
    9902            1 :             (
    9903            1 :                 key,
    9904            1 :                 Lsn(0x30),
    9905            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9906            1 :             ),
    9907            1 :             (
    9908            1 :                 key,
    9909            1 :                 Lsn(0x40),
    9910            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9911            1 :             ),
    9912            1 :             (
    9913            1 :                 key,
    9914            1 :                 Lsn(0x50),
    9915            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9916            1 :             ),
    9917            1 :             (
    9918            1 :                 key,
    9919            1 :                 Lsn(0x60),
    9920            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9921            1 :             ),
    9922            1 :             (
    9923            1 :                 key,
    9924            1 :                 Lsn(0x70),
    9925            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9926            1 :             ),
    9927            1 :             (
    9928            1 :                 key,
    9929            1 :                 Lsn(0x80),
    9930            1 :                 Value::Image(Bytes::copy_from_slice(
    9931            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9932            1 :                 )),
    9933            1 :             ),
    9934            1 :             (
    9935            1 :                 key,
    9936            1 :                 Lsn(0x90),
    9937            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9938            1 :             ),
    9939              :         ];
    9940            1 :         let res = tline
    9941            1 :             .generate_key_retention(
    9942            1 :                 key,
    9943            1 :                 &history,
    9944            1 :                 Lsn(0x60),
    9945            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9946            1 :                 3,
    9947            1 :                 None,
    9948            1 :                 true,
    9949            1 :             )
    9950            1 :             .await
    9951            1 :             .unwrap();
    9952            1 :         let expected_res = KeyHistoryRetention {
    9953            1 :             below_horizon: vec![
    9954            1 :                 (
    9955            1 :                     Lsn(0x20),
    9956            1 :                     KeyLogAtLsn(vec![(
    9957            1 :                         Lsn(0x20),
    9958            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9959            1 :                     )]),
    9960            1 :                 ),
    9961            1 :                 (
    9962            1 :                     Lsn(0x40),
    9963            1 :                     KeyLogAtLsn(vec![
    9964            1 :                         (
    9965            1 :                             Lsn(0x30),
    9966            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9967            1 :                         ),
    9968            1 :                         (
    9969            1 :                             Lsn(0x40),
    9970            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9971            1 :                         ),
    9972            1 :                     ]),
    9973            1 :                 ),
    9974            1 :                 (
    9975            1 :                     Lsn(0x50),
    9976            1 :                     KeyLogAtLsn(vec![(
    9977            1 :                         Lsn(0x50),
    9978            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9979            1 :                     )]),
    9980            1 :                 ),
    9981            1 :                 (
    9982            1 :                     Lsn(0x60),
    9983            1 :                     KeyLogAtLsn(vec![(
    9984            1 :                         Lsn(0x60),
    9985            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9986            1 :                     )]),
    9987            1 :                 ),
    9988            1 :             ],
    9989            1 :             above_horizon: KeyLogAtLsn(vec![
    9990            1 :                 (
    9991            1 :                     Lsn(0x70),
    9992            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9993            1 :                 ),
    9994            1 :                 (
    9995            1 :                     Lsn(0x80),
    9996            1 :                     Value::Image(Bytes::copy_from_slice(
    9997            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9998            1 :                     )),
    9999            1 :                 ),
   10000            1 :                 (
   10001            1 :                     Lsn(0x90),
   10002            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10003            1 :                 ),
   10004            1 :             ]),
   10005            1 :         };
   10006            1 :         assert_eq!(res, expected_res);
   10007              : 
   10008              :         // We expect GC-compaction to run with the original GC. This would create a situation that
   10009              :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
   10010              :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
   10011              :         // For example, we have
   10012              :         // ```plain
   10013              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
   10014              :         // ```
   10015              :         // Now the GC horizon moves up, and we have
   10016              :         // ```plain
   10017              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
   10018              :         // ```
   10019              :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
   10020              :         // We will end up with
   10021              :         // ```plain
   10022              :         // delta @ 0x30, image @ 0x40 (gc_horizon)
   10023              :         // ```
   10024              :         // Now we run the GC-compaction, and this key does not have a full history.
   10025              :         // We should be able to handle this partial history and drop everything before the
   10026              :         // gc_horizon image.
   10027              : 
   10028            1 :         let history = vec![
   10029            1 :             (
   10030            1 :                 key,
   10031            1 :                 Lsn(0x20),
   10032            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10033            1 :             ),
   10034            1 :             (
   10035            1 :                 key,
   10036            1 :                 Lsn(0x30),
   10037            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10038            1 :             ),
   10039            1 :             (
   10040            1 :                 key,
   10041            1 :                 Lsn(0x40),
   10042            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10043            1 :             ),
   10044            1 :             (
   10045            1 :                 key,
   10046            1 :                 Lsn(0x50),
   10047            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10048            1 :             ),
   10049            1 :             (
   10050            1 :                 key,
   10051            1 :                 Lsn(0x60),
   10052            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10053            1 :             ),
   10054            1 :             (
   10055            1 :                 key,
   10056            1 :                 Lsn(0x70),
   10057            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10058            1 :             ),
   10059            1 :             (
   10060            1 :                 key,
   10061            1 :                 Lsn(0x80),
   10062            1 :                 Value::Image(Bytes::copy_from_slice(
   10063            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10064            1 :                 )),
   10065            1 :             ),
   10066            1 :             (
   10067            1 :                 key,
   10068            1 :                 Lsn(0x90),
   10069            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10070            1 :             ),
   10071              :         ];
   10072            1 :         let res = tline
   10073            1 :             .generate_key_retention(
   10074            1 :                 key,
   10075            1 :                 &history,
   10076            1 :                 Lsn(0x60),
   10077            1 :                 &[Lsn(0x40), Lsn(0x50)],
   10078            1 :                 3,
   10079            1 :                 None,
   10080            1 :                 true,
   10081            1 :             )
   10082            1 :             .await
   10083            1 :             .unwrap();
   10084            1 :         let expected_res = KeyHistoryRetention {
   10085            1 :             below_horizon: vec![
   10086            1 :                 (
   10087            1 :                     Lsn(0x40),
   10088            1 :                     KeyLogAtLsn(vec![(
   10089            1 :                         Lsn(0x40),
   10090            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10091            1 :                     )]),
   10092            1 :                 ),
   10093            1 :                 (
   10094            1 :                     Lsn(0x50),
   10095            1 :                     KeyLogAtLsn(vec![(
   10096            1 :                         Lsn(0x50),
   10097            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10098            1 :                     )]),
   10099            1 :                 ),
   10100            1 :                 (
   10101            1 :                     Lsn(0x60),
   10102            1 :                     KeyLogAtLsn(vec![(
   10103            1 :                         Lsn(0x60),
   10104            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10105            1 :                     )]),
   10106            1 :                 ),
   10107            1 :             ],
   10108            1 :             above_horizon: KeyLogAtLsn(vec![
   10109            1 :                 (
   10110            1 :                     Lsn(0x70),
   10111            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10112            1 :                 ),
   10113            1 :                 (
   10114            1 :                     Lsn(0x80),
   10115            1 :                     Value::Image(Bytes::copy_from_slice(
   10116            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10117            1 :                     )),
   10118            1 :                 ),
   10119            1 :                 (
   10120            1 :                     Lsn(0x90),
   10121            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10122            1 :                 ),
   10123            1 :             ]),
   10124            1 :         };
   10125            1 :         assert_eq!(res, expected_res);
   10126              : 
   10127              :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
   10128              :         // the ancestor image in the test case.
   10129              : 
   10130            1 :         let history = vec![
   10131            1 :             (
   10132            1 :                 key,
   10133            1 :                 Lsn(0x20),
   10134            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10135            1 :             ),
   10136            1 :             (
   10137            1 :                 key,
   10138            1 :                 Lsn(0x30),
   10139            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10140            1 :             ),
   10141            1 :             (
   10142            1 :                 key,
   10143            1 :                 Lsn(0x40),
   10144            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10145            1 :             ),
   10146            1 :             (
   10147            1 :                 key,
   10148            1 :                 Lsn(0x70),
   10149            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10150            1 :             ),
   10151              :         ];
   10152            1 :         let res = tline
   10153            1 :             .generate_key_retention(
   10154            1 :                 key,
   10155            1 :                 &history,
   10156            1 :                 Lsn(0x60),
   10157            1 :                 &[],
   10158            1 :                 3,
   10159            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10160            1 :                 true,
   10161            1 :             )
   10162            1 :             .await
   10163            1 :             .unwrap();
   10164            1 :         let expected_res = KeyHistoryRetention {
   10165            1 :             below_horizon: vec![(
   10166            1 :                 Lsn(0x60),
   10167            1 :                 KeyLogAtLsn(vec![(
   10168            1 :                     Lsn(0x60),
   10169            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
   10170            1 :                 )]),
   10171            1 :             )],
   10172            1 :             above_horizon: KeyLogAtLsn(vec![(
   10173            1 :                 Lsn(0x70),
   10174            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10175            1 :             )]),
   10176            1 :         };
   10177            1 :         assert_eq!(res, expected_res);
   10178              : 
   10179            1 :         let history = vec![
   10180            1 :             (
   10181            1 :                 key,
   10182            1 :                 Lsn(0x20),
   10183            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10184            1 :             ),
   10185            1 :             (
   10186            1 :                 key,
   10187            1 :                 Lsn(0x40),
   10188            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10189            1 :             ),
   10190            1 :             (
   10191            1 :                 key,
   10192            1 :                 Lsn(0x60),
   10193            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10194            1 :             ),
   10195            1 :             (
   10196            1 :                 key,
   10197            1 :                 Lsn(0x70),
   10198            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10199            1 :             ),
   10200              :         ];
   10201            1 :         let res = tline
   10202            1 :             .generate_key_retention(
   10203            1 :                 key,
   10204            1 :                 &history,
   10205            1 :                 Lsn(0x60),
   10206            1 :                 &[Lsn(0x30)],
   10207            1 :                 3,
   10208            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10209            1 :                 true,
   10210            1 :             )
   10211            1 :             .await
   10212            1 :             .unwrap();
   10213            1 :         let expected_res = KeyHistoryRetention {
   10214            1 :             below_horizon: vec![
   10215            1 :                 (
   10216            1 :                     Lsn(0x30),
   10217            1 :                     KeyLogAtLsn(vec![(
   10218            1 :                         Lsn(0x20),
   10219            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10220            1 :                     )]),
   10221            1 :                 ),
   10222            1 :                 (
   10223            1 :                     Lsn(0x60),
   10224            1 :                     KeyLogAtLsn(vec![(
   10225            1 :                         Lsn(0x60),
   10226            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
   10227            1 :                     )]),
   10228            1 :                 ),
   10229            1 :             ],
   10230            1 :             above_horizon: KeyLogAtLsn(vec![(
   10231            1 :                 Lsn(0x70),
   10232            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10233            1 :             )]),
   10234            1 :         };
   10235            1 :         assert_eq!(res, expected_res);
   10236              : 
   10237            2 :         Ok(())
   10238            1 :     }
   10239              : 
   10240              :     #[cfg(feature = "testing")]
   10241              :     #[tokio::test]
   10242            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
   10243            1 :         let harness =
   10244            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
   10245            1 :         let (tenant, ctx) = harness.load().await;
   10246              : 
   10247          259 :         fn get_key(id: u32) -> Key {
   10248              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10249          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10250          259 :             key.field6 = id;
   10251          259 :             key
   10252          259 :         }
   10253              : 
   10254            1 :         let img_layer = (0..10)
   10255           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10256            1 :             .collect_vec();
   10257              : 
   10258            1 :         let delta1 = vec![
   10259            1 :             (
   10260            1 :                 get_key(1),
   10261            1 :                 Lsn(0x20),
   10262            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10263            1 :             ),
   10264            1 :             (
   10265            1 :                 get_key(2),
   10266            1 :                 Lsn(0x30),
   10267            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10268            1 :             ),
   10269            1 :             (
   10270            1 :                 get_key(3),
   10271            1 :                 Lsn(0x28),
   10272            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10273            1 :             ),
   10274            1 :             (
   10275            1 :                 get_key(3),
   10276            1 :                 Lsn(0x30),
   10277            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10278            1 :             ),
   10279            1 :             (
   10280            1 :                 get_key(3),
   10281            1 :                 Lsn(0x40),
   10282            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10283            1 :             ),
   10284              :         ];
   10285            1 :         let delta2 = vec![
   10286            1 :             (
   10287            1 :                 get_key(5),
   10288            1 :                 Lsn(0x20),
   10289            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10290            1 :             ),
   10291            1 :             (
   10292            1 :                 get_key(6),
   10293            1 :                 Lsn(0x20),
   10294            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10295            1 :             ),
   10296              :         ];
   10297            1 :         let delta3 = vec![
   10298            1 :             (
   10299            1 :                 get_key(8),
   10300            1 :                 Lsn(0x48),
   10301            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10302            1 :             ),
   10303            1 :             (
   10304            1 :                 get_key(9),
   10305            1 :                 Lsn(0x48),
   10306            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10307            1 :             ),
   10308              :         ];
   10309              : 
   10310            1 :         let tline = tenant
   10311            1 :             .create_test_timeline_with_layers(
   10312            1 :                 TIMELINE_ID,
   10313            1 :                 Lsn(0x10),
   10314            1 :                 DEFAULT_PG_VERSION,
   10315            1 :                 &ctx,
   10316            1 :                 Vec::new(), // in-memory layers
   10317            1 :                 vec![
   10318            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10319            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10320            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10321            1 :                 ], // delta layers
   10322            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10323            1 :                 Lsn(0x50),
   10324            1 :             )
   10325            1 :             .await?;
   10326              :         {
   10327            1 :             tline
   10328            1 :                 .applied_gc_cutoff_lsn
   10329            1 :                 .lock_for_write()
   10330            1 :                 .store_and_unlock(Lsn(0x30))
   10331            1 :                 .wait()
   10332            1 :                 .await;
   10333              :             // Update GC info
   10334            1 :             let mut guard = tline.gc_info.write().unwrap();
   10335            1 :             *guard = GcInfo {
   10336            1 :                 retain_lsns: vec![
   10337            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10338            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10339            1 :                 ],
   10340            1 :                 cutoffs: GcCutoffs {
   10341            1 :                     time: Some(Lsn(0x30)),
   10342            1 :                     space: Lsn(0x30),
   10343            1 :                 },
   10344            1 :                 leases: Default::default(),
   10345            1 :                 within_ancestor_pitr: false,
   10346            1 :             };
   10347              :         }
   10348              : 
   10349            1 :         let expected_result = [
   10350            1 :             Bytes::from_static(b"value 0@0x10"),
   10351            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10352            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10353            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10354            1 :             Bytes::from_static(b"value 4@0x10"),
   10355            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10356            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10357            1 :             Bytes::from_static(b"value 7@0x10"),
   10358            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10359            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10360            1 :         ];
   10361              : 
   10362            1 :         let expected_result_at_gc_horizon = [
   10363            1 :             Bytes::from_static(b"value 0@0x10"),
   10364            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10365            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10366            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10367            1 :             Bytes::from_static(b"value 4@0x10"),
   10368            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10369            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10370            1 :             Bytes::from_static(b"value 7@0x10"),
   10371            1 :             Bytes::from_static(b"value 8@0x10"),
   10372            1 :             Bytes::from_static(b"value 9@0x10"),
   10373            1 :         ];
   10374              : 
   10375            1 :         let expected_result_at_lsn_20 = [
   10376            1 :             Bytes::from_static(b"value 0@0x10"),
   10377            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10378            1 :             Bytes::from_static(b"value 2@0x10"),
   10379            1 :             Bytes::from_static(b"value 3@0x10"),
   10380            1 :             Bytes::from_static(b"value 4@0x10"),
   10381            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10382            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10383            1 :             Bytes::from_static(b"value 7@0x10"),
   10384            1 :             Bytes::from_static(b"value 8@0x10"),
   10385            1 :             Bytes::from_static(b"value 9@0x10"),
   10386            1 :         ];
   10387              : 
   10388            1 :         let expected_result_at_lsn_10 = [
   10389            1 :             Bytes::from_static(b"value 0@0x10"),
   10390            1 :             Bytes::from_static(b"value 1@0x10"),
   10391            1 :             Bytes::from_static(b"value 2@0x10"),
   10392            1 :             Bytes::from_static(b"value 3@0x10"),
   10393            1 :             Bytes::from_static(b"value 4@0x10"),
   10394            1 :             Bytes::from_static(b"value 5@0x10"),
   10395            1 :             Bytes::from_static(b"value 6@0x10"),
   10396            1 :             Bytes::from_static(b"value 7@0x10"),
   10397            1 :             Bytes::from_static(b"value 8@0x10"),
   10398            1 :             Bytes::from_static(b"value 9@0x10"),
   10399            1 :         ];
   10400              : 
   10401            6 :         let verify_result = || async {
   10402            6 :             let gc_horizon = {
   10403            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10404            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10405              :             };
   10406           66 :             for idx in 0..10 {
   10407           60 :                 assert_eq!(
   10408           60 :                     tline
   10409           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10410           60 :                         .await
   10411           60 :                         .unwrap(),
   10412           60 :                     &expected_result[idx]
   10413              :                 );
   10414           60 :                 assert_eq!(
   10415           60 :                     tline
   10416           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10417           60 :                         .await
   10418           60 :                         .unwrap(),
   10419           60 :                     &expected_result_at_gc_horizon[idx]
   10420              :                 );
   10421           60 :                 assert_eq!(
   10422           60 :                     tline
   10423           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10424           60 :                         .await
   10425           60 :                         .unwrap(),
   10426           60 :                     &expected_result_at_lsn_20[idx]
   10427              :                 );
   10428           60 :                 assert_eq!(
   10429           60 :                     tline
   10430           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10431           60 :                         .await
   10432           60 :                         .unwrap(),
   10433           60 :                     &expected_result_at_lsn_10[idx]
   10434              :                 );
   10435              :             }
   10436           12 :         };
   10437              : 
   10438            1 :         verify_result().await;
   10439              : 
   10440            1 :         let cancel = CancellationToken::new();
   10441            1 :         let mut dryrun_flags = EnumSet::new();
   10442            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10443              : 
   10444            1 :         tline
   10445            1 :             .compact_with_gc(
   10446            1 :                 &cancel,
   10447            1 :                 CompactOptions {
   10448            1 :                     flags: dryrun_flags,
   10449            1 :                     ..Default::default()
   10450            1 :                 },
   10451            1 :                 &ctx,
   10452            1 :             )
   10453            1 :             .await
   10454            1 :             .unwrap();
   10455              :         // 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
   10456              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10457            1 :         verify_result().await;
   10458              : 
   10459            1 :         tline
   10460            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10461            1 :             .await
   10462            1 :             .unwrap();
   10463            1 :         verify_result().await;
   10464              : 
   10465              :         // compact again
   10466            1 :         tline
   10467            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10468            1 :             .await
   10469            1 :             .unwrap();
   10470            1 :         verify_result().await;
   10471              : 
   10472              :         // increase GC horizon and compact again
   10473              :         {
   10474            1 :             tline
   10475            1 :                 .applied_gc_cutoff_lsn
   10476            1 :                 .lock_for_write()
   10477            1 :                 .store_and_unlock(Lsn(0x38))
   10478            1 :                 .wait()
   10479            1 :                 .await;
   10480              :             // Update GC info
   10481            1 :             let mut guard = tline.gc_info.write().unwrap();
   10482            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10483            1 :             guard.cutoffs.space = Lsn(0x38);
   10484              :         }
   10485            1 :         tline
   10486            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10487            1 :             .await
   10488            1 :             .unwrap();
   10489            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10490              : 
   10491              :         // not increasing the GC horizon and compact again
   10492            1 :         tline
   10493            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10494            1 :             .await
   10495            1 :             .unwrap();
   10496            1 :         verify_result().await;
   10497              : 
   10498            2 :         Ok(())
   10499            1 :     }
   10500              : 
   10501              :     #[cfg(feature = "testing")]
   10502              :     #[tokio::test]
   10503            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10504            1 :     {
   10505            1 :         let harness =
   10506            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10507            1 :                 .await?;
   10508            1 :         let (tenant, ctx) = harness.load().await;
   10509              : 
   10510          176 :         fn get_key(id: u32) -> Key {
   10511              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10512          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10513          176 :             key.field6 = id;
   10514          176 :             key
   10515          176 :         }
   10516              : 
   10517            1 :         let img_layer = (0..10)
   10518           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10519            1 :             .collect_vec();
   10520              : 
   10521            1 :         let delta1 = vec![
   10522            1 :             (
   10523            1 :                 get_key(1),
   10524            1 :                 Lsn(0x20),
   10525            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10526            1 :             ),
   10527            1 :             (
   10528            1 :                 get_key(1),
   10529            1 :                 Lsn(0x28),
   10530            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10531            1 :             ),
   10532              :         ];
   10533            1 :         let delta2 = vec![
   10534            1 :             (
   10535            1 :                 get_key(1),
   10536            1 :                 Lsn(0x30),
   10537            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10538            1 :             ),
   10539            1 :             (
   10540            1 :                 get_key(1),
   10541            1 :                 Lsn(0x38),
   10542            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10543            1 :             ),
   10544              :         ];
   10545            1 :         let delta3 = vec![
   10546            1 :             (
   10547            1 :                 get_key(8),
   10548            1 :                 Lsn(0x48),
   10549            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10550            1 :             ),
   10551            1 :             (
   10552            1 :                 get_key(9),
   10553            1 :                 Lsn(0x48),
   10554            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10555            1 :             ),
   10556              :         ];
   10557              : 
   10558            1 :         let tline = tenant
   10559            1 :             .create_test_timeline_with_layers(
   10560            1 :                 TIMELINE_ID,
   10561            1 :                 Lsn(0x10),
   10562            1 :                 DEFAULT_PG_VERSION,
   10563            1 :                 &ctx,
   10564            1 :                 Vec::new(), // in-memory layers
   10565            1 :                 vec![
   10566            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10567            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10568            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10569            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10570            1 :                 ], // delta layers
   10571            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10572            1 :                 Lsn(0x50),
   10573            1 :             )
   10574            1 :             .await?;
   10575              :         {
   10576            1 :             tline
   10577            1 :                 .applied_gc_cutoff_lsn
   10578            1 :                 .lock_for_write()
   10579            1 :                 .store_and_unlock(Lsn(0x30))
   10580            1 :                 .wait()
   10581            1 :                 .await;
   10582              :             // Update GC info
   10583            1 :             let mut guard = tline.gc_info.write().unwrap();
   10584            1 :             *guard = GcInfo {
   10585            1 :                 retain_lsns: vec![
   10586            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10587            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10588            1 :                 ],
   10589            1 :                 cutoffs: GcCutoffs {
   10590            1 :                     time: Some(Lsn(0x30)),
   10591            1 :                     space: Lsn(0x30),
   10592            1 :                 },
   10593            1 :                 leases: Default::default(),
   10594            1 :                 within_ancestor_pitr: false,
   10595            1 :             };
   10596              :         }
   10597              : 
   10598            1 :         let expected_result = [
   10599            1 :             Bytes::from_static(b"value 0@0x10"),
   10600            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10601            1 :             Bytes::from_static(b"value 2@0x10"),
   10602            1 :             Bytes::from_static(b"value 3@0x10"),
   10603            1 :             Bytes::from_static(b"value 4@0x10"),
   10604            1 :             Bytes::from_static(b"value 5@0x10"),
   10605            1 :             Bytes::from_static(b"value 6@0x10"),
   10606            1 :             Bytes::from_static(b"value 7@0x10"),
   10607            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10608            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10609            1 :         ];
   10610              : 
   10611            1 :         let expected_result_at_gc_horizon = [
   10612            1 :             Bytes::from_static(b"value 0@0x10"),
   10613            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10614            1 :             Bytes::from_static(b"value 2@0x10"),
   10615            1 :             Bytes::from_static(b"value 3@0x10"),
   10616            1 :             Bytes::from_static(b"value 4@0x10"),
   10617            1 :             Bytes::from_static(b"value 5@0x10"),
   10618            1 :             Bytes::from_static(b"value 6@0x10"),
   10619            1 :             Bytes::from_static(b"value 7@0x10"),
   10620            1 :             Bytes::from_static(b"value 8@0x10"),
   10621            1 :             Bytes::from_static(b"value 9@0x10"),
   10622            1 :         ];
   10623              : 
   10624            1 :         let expected_result_at_lsn_20 = [
   10625            1 :             Bytes::from_static(b"value 0@0x10"),
   10626            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10627            1 :             Bytes::from_static(b"value 2@0x10"),
   10628            1 :             Bytes::from_static(b"value 3@0x10"),
   10629            1 :             Bytes::from_static(b"value 4@0x10"),
   10630            1 :             Bytes::from_static(b"value 5@0x10"),
   10631            1 :             Bytes::from_static(b"value 6@0x10"),
   10632            1 :             Bytes::from_static(b"value 7@0x10"),
   10633            1 :             Bytes::from_static(b"value 8@0x10"),
   10634            1 :             Bytes::from_static(b"value 9@0x10"),
   10635            1 :         ];
   10636              : 
   10637            1 :         let expected_result_at_lsn_10 = [
   10638            1 :             Bytes::from_static(b"value 0@0x10"),
   10639            1 :             Bytes::from_static(b"value 1@0x10"),
   10640            1 :             Bytes::from_static(b"value 2@0x10"),
   10641            1 :             Bytes::from_static(b"value 3@0x10"),
   10642            1 :             Bytes::from_static(b"value 4@0x10"),
   10643            1 :             Bytes::from_static(b"value 5@0x10"),
   10644            1 :             Bytes::from_static(b"value 6@0x10"),
   10645            1 :             Bytes::from_static(b"value 7@0x10"),
   10646            1 :             Bytes::from_static(b"value 8@0x10"),
   10647            1 :             Bytes::from_static(b"value 9@0x10"),
   10648            1 :         ];
   10649              : 
   10650            4 :         let verify_result = || async {
   10651            4 :             let gc_horizon = {
   10652            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10653            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10654              :             };
   10655           44 :             for idx in 0..10 {
   10656           40 :                 assert_eq!(
   10657           40 :                     tline
   10658           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10659           40 :                         .await
   10660           40 :                         .unwrap(),
   10661           40 :                     &expected_result[idx]
   10662              :                 );
   10663           40 :                 assert_eq!(
   10664           40 :                     tline
   10665           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10666           40 :                         .await
   10667           40 :                         .unwrap(),
   10668           40 :                     &expected_result_at_gc_horizon[idx]
   10669              :                 );
   10670           40 :                 assert_eq!(
   10671           40 :                     tline
   10672           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10673           40 :                         .await
   10674           40 :                         .unwrap(),
   10675           40 :                     &expected_result_at_lsn_20[idx]
   10676              :                 );
   10677           40 :                 assert_eq!(
   10678           40 :                     tline
   10679           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10680           40 :                         .await
   10681           40 :                         .unwrap(),
   10682           40 :                     &expected_result_at_lsn_10[idx]
   10683              :                 );
   10684              :             }
   10685            8 :         };
   10686              : 
   10687            1 :         verify_result().await;
   10688              : 
   10689            1 :         let cancel = CancellationToken::new();
   10690            1 :         let mut dryrun_flags = EnumSet::new();
   10691            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10692              : 
   10693            1 :         tline
   10694            1 :             .compact_with_gc(
   10695            1 :                 &cancel,
   10696            1 :                 CompactOptions {
   10697            1 :                     flags: dryrun_flags,
   10698            1 :                     ..Default::default()
   10699            1 :                 },
   10700            1 :                 &ctx,
   10701            1 :             )
   10702            1 :             .await
   10703            1 :             .unwrap();
   10704              :         // 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
   10705              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10706            1 :         verify_result().await;
   10707              : 
   10708            1 :         tline
   10709            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10710            1 :             .await
   10711            1 :             .unwrap();
   10712            1 :         verify_result().await;
   10713              : 
   10714              :         // compact again
   10715            1 :         tline
   10716            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10717            1 :             .await
   10718            1 :             .unwrap();
   10719            1 :         verify_result().await;
   10720              : 
   10721            2 :         Ok(())
   10722            1 :     }
   10723              : 
   10724              :     #[cfg(feature = "testing")]
   10725              :     #[tokio::test]
   10726            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10727              :         use models::CompactLsnRange;
   10728              : 
   10729            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10730            1 :         let (tenant, ctx) = harness.load().await;
   10731              : 
   10732           83 :         fn get_key(id: u32) -> Key {
   10733           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10734           83 :             key.field6 = id;
   10735           83 :             key
   10736           83 :         }
   10737              : 
   10738            1 :         let img_layer = (0..10)
   10739           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10740            1 :             .collect_vec();
   10741              : 
   10742            1 :         let delta1 = vec![
   10743            1 :             (
   10744            1 :                 get_key(1),
   10745            1 :                 Lsn(0x20),
   10746            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10747            1 :             ),
   10748            1 :             (
   10749            1 :                 get_key(2),
   10750            1 :                 Lsn(0x30),
   10751            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10752            1 :             ),
   10753            1 :             (
   10754            1 :                 get_key(3),
   10755            1 :                 Lsn(0x28),
   10756            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10757            1 :             ),
   10758            1 :             (
   10759            1 :                 get_key(3),
   10760            1 :                 Lsn(0x30),
   10761            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10762            1 :             ),
   10763            1 :             (
   10764            1 :                 get_key(3),
   10765            1 :                 Lsn(0x40),
   10766            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10767            1 :             ),
   10768              :         ];
   10769            1 :         let delta2 = vec![
   10770            1 :             (
   10771            1 :                 get_key(5),
   10772            1 :                 Lsn(0x20),
   10773            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10774            1 :             ),
   10775            1 :             (
   10776            1 :                 get_key(6),
   10777            1 :                 Lsn(0x20),
   10778            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10779            1 :             ),
   10780              :         ];
   10781            1 :         let delta3 = vec![
   10782            1 :             (
   10783            1 :                 get_key(8),
   10784            1 :                 Lsn(0x48),
   10785            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10786            1 :             ),
   10787            1 :             (
   10788            1 :                 get_key(9),
   10789            1 :                 Lsn(0x48),
   10790            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10791            1 :             ),
   10792              :         ];
   10793              : 
   10794            1 :         let parent_tline = tenant
   10795            1 :             .create_test_timeline_with_layers(
   10796            1 :                 TIMELINE_ID,
   10797            1 :                 Lsn(0x10),
   10798            1 :                 DEFAULT_PG_VERSION,
   10799            1 :                 &ctx,
   10800            1 :                 vec![],                       // in-memory layers
   10801            1 :                 vec![],                       // delta layers
   10802            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10803            1 :                 Lsn(0x18),
   10804            1 :             )
   10805            1 :             .await?;
   10806              : 
   10807            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10808              : 
   10809            1 :         let branch_tline = tenant
   10810            1 :             .branch_timeline_test_with_layers(
   10811            1 :                 &parent_tline,
   10812            1 :                 NEW_TIMELINE_ID,
   10813            1 :                 Some(Lsn(0x18)),
   10814            1 :                 &ctx,
   10815            1 :                 vec![
   10816            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10817            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10818            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10819            1 :                 ], // delta layers
   10820            1 :                 vec![], // image layers
   10821            1 :                 Lsn(0x50),
   10822            1 :             )
   10823            1 :             .await?;
   10824              : 
   10825            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10826              : 
   10827              :         {
   10828            1 :             parent_tline
   10829            1 :                 .applied_gc_cutoff_lsn
   10830            1 :                 .lock_for_write()
   10831            1 :                 .store_and_unlock(Lsn(0x10))
   10832            1 :                 .wait()
   10833            1 :                 .await;
   10834              :             // Update GC info
   10835            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10836            1 :             *guard = GcInfo {
   10837            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10838            1 :                 cutoffs: GcCutoffs {
   10839            1 :                     time: Some(Lsn(0x10)),
   10840            1 :                     space: Lsn(0x10),
   10841            1 :                 },
   10842            1 :                 leases: Default::default(),
   10843            1 :                 within_ancestor_pitr: false,
   10844            1 :             };
   10845              :         }
   10846              : 
   10847              :         {
   10848            1 :             branch_tline
   10849            1 :                 .applied_gc_cutoff_lsn
   10850            1 :                 .lock_for_write()
   10851            1 :                 .store_and_unlock(Lsn(0x50))
   10852            1 :                 .wait()
   10853            1 :                 .await;
   10854              :             // Update GC info
   10855            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10856            1 :             *guard = GcInfo {
   10857            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10858            1 :                 cutoffs: GcCutoffs {
   10859            1 :                     time: Some(Lsn(0x50)),
   10860            1 :                     space: Lsn(0x50),
   10861            1 :                 },
   10862            1 :                 leases: Default::default(),
   10863            1 :                 within_ancestor_pitr: false,
   10864            1 :             };
   10865              :         }
   10866              : 
   10867            1 :         let expected_result_at_gc_horizon = [
   10868            1 :             Bytes::from_static(b"value 0@0x10"),
   10869            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10870            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10871            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10872            1 :             Bytes::from_static(b"value 4@0x10"),
   10873            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10874            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10875            1 :             Bytes::from_static(b"value 7@0x10"),
   10876            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10877            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10878            1 :         ];
   10879              : 
   10880            1 :         let expected_result_at_lsn_40 = [
   10881            1 :             Bytes::from_static(b"value 0@0x10"),
   10882            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10883            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10884            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10885            1 :             Bytes::from_static(b"value 4@0x10"),
   10886            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10887            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10888            1 :             Bytes::from_static(b"value 7@0x10"),
   10889            1 :             Bytes::from_static(b"value 8@0x10"),
   10890            1 :             Bytes::from_static(b"value 9@0x10"),
   10891            1 :         ];
   10892              : 
   10893            3 :         let verify_result = || async {
   10894           33 :             for idx in 0..10 {
   10895           30 :                 assert_eq!(
   10896           30 :                     branch_tline
   10897           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10898           30 :                         .await
   10899           30 :                         .unwrap(),
   10900           30 :                     &expected_result_at_gc_horizon[idx]
   10901              :                 );
   10902           30 :                 assert_eq!(
   10903           30 :                     branch_tline
   10904           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10905           30 :                         .await
   10906           30 :                         .unwrap(),
   10907           30 :                     &expected_result_at_lsn_40[idx]
   10908              :                 );
   10909              :             }
   10910            6 :         };
   10911              : 
   10912            1 :         verify_result().await;
   10913              : 
   10914            1 :         let cancel = CancellationToken::new();
   10915            1 :         branch_tline
   10916            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10917            1 :             .await
   10918            1 :             .unwrap();
   10919              : 
   10920            1 :         verify_result().await;
   10921              : 
   10922              :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10923              :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10924            1 :         branch_tline
   10925            1 :             .compact_with_gc(
   10926            1 :                 &cancel,
   10927            1 :                 CompactOptions {
   10928            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10929            1 :                     ..Default::default()
   10930            1 :                 },
   10931            1 :                 &ctx,
   10932            1 :             )
   10933            1 :             .await
   10934            1 :             .unwrap();
   10935              : 
   10936            1 :         verify_result().await;
   10937              : 
   10938            2 :         Ok(())
   10939            1 :     }
   10940              : 
   10941              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10942              :     // Create an image arrangement where we have to read at different LSN ranges
   10943              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10944              :     // a delta layer. Like so:
   10945              :     //
   10946              :     //     A      B
   10947              :     // +----------------+ -> delta_layer
   10948              :     // |                |                           ^ lsn
   10949              :     // |       =========|-> nested_image_layer      |
   10950              :     // |       C        |                           |
   10951              :     // +----------------+                           |
   10952              :     // ======== -> baseline_image_layer             +-------> key
   10953              :     //
   10954              :     //
   10955              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10956              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10957              :     #[cfg(feature = "testing")]
   10958              :     #[tokio::test]
   10959            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10960            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10961            1 :         let (tenant, ctx) = harness.load().await;
   10962              : 
   10963            1 :         let will_init_keys = [2, 6];
   10964           22 :         fn get_key(id: u32) -> Key {
   10965           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10966           22 :             key.field6 = id;
   10967           22 :             key
   10968           22 :         }
   10969              : 
   10970            1 :         let mut expected_key_values = HashMap::new();
   10971              : 
   10972            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10973            1 :         let mut baseline_img_layer = Vec::new();
   10974            6 :         for i in 0..5 {
   10975            5 :             let key = get_key(i);
   10976            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10977              : 
   10978            5 :             let removed = expected_key_values.insert(key, value.clone());
   10979            5 :             assert!(removed.is_none());
   10980              : 
   10981            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10982              :         }
   10983              : 
   10984            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10985            1 :         let mut nested_img_layer = Vec::new();
   10986            6 :         for i in 5..10 {
   10987            5 :             let key = get_key(i);
   10988            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10989              : 
   10990            5 :             let removed = expected_key_values.insert(key, value.clone());
   10991            5 :             assert!(removed.is_none());
   10992              : 
   10993            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10994              :         }
   10995              : 
   10996            1 :         let mut delta_layer_spec = Vec::default();
   10997            1 :         let delta_layer_start_lsn = Lsn(0x20);
   10998            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10999              : 
   11000           11 :         for i in 0..10 {
   11001           10 :             let key = get_key(i);
   11002           10 :             let key_in_nested = nested_img_layer
   11003           10 :                 .iter()
   11004           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   11005           10 :             let lsn = {
   11006           10 :                 if key_in_nested {
   11007            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   11008              :                 } else {
   11009            5 :                     delta_layer_start_lsn
   11010              :                 }
   11011              :             };
   11012              : 
   11013           10 :             let will_init = will_init_keys.contains(&i);
   11014           10 :             if will_init {
   11015            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11016            2 : 
   11017            2 :                 expected_key_values.insert(key, "".to_string());
   11018            8 :             } else {
   11019            8 :                 let delta = format!("@{lsn}");
   11020            8 :                 delta_layer_spec.push((
   11021            8 :                     key,
   11022            8 :                     lsn,
   11023            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11024            8 :                 ));
   11025            8 : 
   11026            8 :                 expected_key_values
   11027            8 :                     .get_mut(&key)
   11028            8 :                     .expect("An image exists for each key")
   11029            8 :                     .push_str(delta.as_str());
   11030            8 :             }
   11031           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   11032              :         }
   11033              : 
   11034            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   11035              : 
   11036            1 :         assert!(
   11037            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   11038            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   11039              :         );
   11040              : 
   11041            1 :         let tline = tenant
   11042            1 :             .create_test_timeline_with_layers(
   11043            1 :                 TIMELINE_ID,
   11044            1 :                 baseline_image_layer_lsn,
   11045            1 :                 DEFAULT_PG_VERSION,
   11046            1 :                 &ctx,
   11047            1 :                 vec![], // in-memory layers
   11048            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   11049            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   11050            1 :                     delta_layer_spec,
   11051            1 :                 )], // delta layers
   11052            1 :                 vec![
   11053            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11054            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11055            1 :                 ], // image layers
   11056            1 :                 delta_layer_end_lsn,
   11057            1 :             )
   11058            1 :             .await?;
   11059              : 
   11060            1 :         let query = VersionedKeySpaceQuery::uniform(
   11061            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11062            1 :             delta_layer_end_lsn,
   11063              :         );
   11064              : 
   11065            1 :         let results = tline
   11066            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11067            1 :             .await
   11068            1 :             .expect("No vectored errors");
   11069           11 :         for (key, res) in results {
   11070           10 :             let value = res.expect("No key errors");
   11071           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11072           10 :             assert_eq!(value, Bytes::from(expected_value));
   11073            1 :         }
   11074            1 : 
   11075            1 :         Ok(())
   11076            1 :     }
   11077              : 
   11078              :     #[cfg(feature = "testing")]
   11079              :     #[tokio::test]
   11080            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   11081            1 :         let harness =
   11082            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   11083            1 :         let (tenant, ctx) = harness.load().await;
   11084              : 
   11085            1 :         let will_init_keys = [2, 6];
   11086           32 :         fn get_key(id: u32) -> Key {
   11087           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11088           32 :             key.field6 = id;
   11089           32 :             key
   11090           32 :         }
   11091              : 
   11092            1 :         let mut expected_key_values = HashMap::new();
   11093              : 
   11094            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11095            1 :         let mut baseline_img_layer = Vec::new();
   11096            6 :         for i in 0..5 {
   11097            5 :             let key = get_key(i);
   11098            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11099              : 
   11100            5 :             let removed = expected_key_values.insert(key, value.clone());
   11101            5 :             assert!(removed.is_none());
   11102              : 
   11103            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11104              :         }
   11105              : 
   11106            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11107            1 :         let mut nested_img_layer = Vec::new();
   11108            6 :         for i in 5..10 {
   11109            5 :             let key = get_key(i);
   11110            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11111              : 
   11112            5 :             let removed = expected_key_values.insert(key, value.clone());
   11113            5 :             assert!(removed.is_none());
   11114              : 
   11115            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11116              :         }
   11117              : 
   11118            1 :         let frozen_layer = {
   11119            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   11120            1 :             let mut data = Vec::new();
   11121           11 :             for i in 0..10 {
   11122           10 :                 let key = get_key(i);
   11123           10 :                 let key_in_nested = nested_img_layer
   11124           10 :                     .iter()
   11125           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   11126           10 :                 let lsn = {
   11127           10 :                     if key_in_nested {
   11128            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   11129              :                     } else {
   11130            5 :                         lsn_range.start
   11131              :                     }
   11132              :                 };
   11133              : 
   11134           10 :                 let will_init = will_init_keys.contains(&i);
   11135           10 :                 if will_init {
   11136            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11137            2 : 
   11138            2 :                     expected_key_values.insert(key, "".to_string());
   11139            8 :                 } else {
   11140            8 :                     let delta = format!("@{lsn}");
   11141            8 :                     data.push((
   11142            8 :                         key,
   11143            8 :                         lsn,
   11144            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11145            8 :                     ));
   11146            8 : 
   11147            8 :                     expected_key_values
   11148            8 :                         .get_mut(&key)
   11149            8 :                         .expect("An image exists for each key")
   11150            8 :                         .push_str(delta.as_str());
   11151            8 :                 }
   11152              :             }
   11153              : 
   11154            1 :             InMemoryLayerTestDesc {
   11155            1 :                 lsn_range,
   11156            1 :                 is_open: false,
   11157            1 :                 data,
   11158            1 :             }
   11159              :         };
   11160              : 
   11161            1 :         let (open_layer, last_record_lsn) = {
   11162            1 :             let start_lsn = Lsn(0x70);
   11163            1 :             let mut data = Vec::new();
   11164            1 :             let mut end_lsn = Lsn(0);
   11165           11 :             for i in 0..10 {
   11166           10 :                 let key = get_key(i);
   11167           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   11168           10 :                 let delta = format!("@{lsn}");
   11169           10 :                 data.push((
   11170           10 :                     key,
   11171           10 :                     lsn,
   11172           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11173           10 :                 ));
   11174           10 : 
   11175           10 :                 expected_key_values
   11176           10 :                     .get_mut(&key)
   11177           10 :                     .expect("An image exists for each key")
   11178           10 :                     .push_str(delta.as_str());
   11179           10 : 
   11180           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   11181           10 :             }
   11182              : 
   11183            1 :             (
   11184            1 :                 InMemoryLayerTestDesc {
   11185            1 :                     lsn_range: start_lsn..Lsn::MAX,
   11186            1 :                     is_open: true,
   11187            1 :                     data,
   11188            1 :                 },
   11189            1 :                 end_lsn,
   11190            1 :             )
   11191              :         };
   11192              : 
   11193            1 :         assert!(
   11194            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   11195            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   11196              :         );
   11197              : 
   11198            1 :         let tline = tenant
   11199            1 :             .create_test_timeline_with_layers(
   11200            1 :                 TIMELINE_ID,
   11201            1 :                 baseline_image_layer_lsn,
   11202            1 :                 DEFAULT_PG_VERSION,
   11203            1 :                 &ctx,
   11204            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   11205            1 :                 Vec::new(),                     // delta layers
   11206            1 :                 vec![
   11207            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11208            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11209            1 :                 ], // image layers
   11210            1 :                 last_record_lsn,
   11211            1 :             )
   11212            1 :             .await?;
   11213              : 
   11214            1 :         let query = VersionedKeySpaceQuery::uniform(
   11215            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11216            1 :             last_record_lsn,
   11217              :         );
   11218              : 
   11219            1 :         let results = tline
   11220            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11221            1 :             .await
   11222            1 :             .expect("No vectored errors");
   11223           11 :         for (key, res) in results {
   11224           10 :             let value = res.expect("No key errors");
   11225           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11226           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   11227            1 : 
   11228           10 :             tracing::info!("key={key} value={expected_value}");
   11229            1 :         }
   11230            1 : 
   11231            1 :         Ok(())
   11232            1 :     }
   11233              : 
   11234              :     // A randomized read path test. Generates a layer map according to a deterministic
   11235              :     // specification. Fills the (key, LSN) space in random manner and then performs
   11236              :     // random scattered queries validating the results against in-memory storage.
   11237              :     //
   11238              :     // See this internal Notion page for a diagram of the layer map:
   11239              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   11240              :     //
   11241              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   11242              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   11243              :     // to run multiple instances in parallel:
   11244              :     //
   11245              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   11246              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   11247              :     #[cfg(feature = "testing")]
   11248              :     #[tokio::test]
   11249            1 :     async fn test_read_path() -> anyhow::Result<()> {
   11250              :         use rand::seq::SliceRandom;
   11251              : 
   11252            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   11253            0 :             let seed: u64 = thread_rng().r#gen();
   11254            0 :             seed
   11255              :         } else {
   11256              :             // Use a hard-coded seed when not in fuzzing mode.
   11257              :             // Note that with the current approach results are not reproducible
   11258              :             // accross platforms and Rust releases.
   11259              :             const SEED: u64 = 0;
   11260            1 :             SEED
   11261              :         };
   11262              : 
   11263            1 :         let mut random = StdRng::seed_from_u64(seed);
   11264              : 
   11265            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   11266              :             const QUERIES: u64 = 5000;
   11267            0 :             let will_init_chance: u8 = random.gen_range(0..=10);
   11268            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   11269              : 
   11270            0 :             (QUERIES, will_init_chance, gap_chance)
   11271              :         } else {
   11272              :             const QUERIES: u64 = 1000;
   11273              :             const WILL_INIT_CHANCE: u8 = 1;
   11274              :             const GAP_CHANCE: u8 = 5;
   11275              : 
   11276            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   11277              :         };
   11278              : 
   11279            1 :         let harness = TenantHarness::create("test_read_path").await?;
   11280            1 :         let (tenant, ctx) = harness.load().await;
   11281              : 
   11282            1 :         tracing::info!("Using random seed: {seed}");
   11283            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   11284              : 
   11285              :         // Define the layer map shape. Note that this part is not randomized.
   11286              : 
   11287              :         const KEY_DIMENSION_SIZE: u32 = 99;
   11288            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11289            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11290            1 :         let total_key_range = start_key..end_key;
   11291            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11292            1 :         let total_start_lsn = Lsn(104);
   11293            1 :         let last_record_lsn = Lsn(504);
   11294              : 
   11295            1 :         assert!(total_key_range_size % 3 == 0);
   11296              : 
   11297            1 :         let in_memory_layers_shape = vec![
   11298            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11299            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11300              :         ];
   11301              : 
   11302            1 :         let delta_layers_shape = vec![
   11303            1 :             (
   11304            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11305            1 :                 Lsn(200)..Lsn(304),
   11306            1 :             ),
   11307            1 :             (
   11308            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11309            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11310            1 :                 Lsn(200)..Lsn(304),
   11311            1 :             ),
   11312            1 :             (
   11313            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11314            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11315            1 :                 Lsn(200)..Lsn(304),
   11316            1 :             ),
   11317              :         ];
   11318              : 
   11319            1 :         let image_layers_shape = vec![
   11320            1 :             (
   11321            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11322            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11323            1 :                 Lsn(456),
   11324            1 :             ),
   11325            1 :             (
   11326            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11327            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11328            1 :                 Lsn(256),
   11329            1 :             ),
   11330            1 :             (total_key_range.clone(), total_start_lsn),
   11331              :         ];
   11332              : 
   11333            1 :         let specification = TestTimelineSpecification {
   11334            1 :             start_lsn: total_start_lsn,
   11335            1 :             last_record_lsn,
   11336            1 :             in_memory_layers_shape,
   11337            1 :             delta_layers_shape,
   11338            1 :             image_layers_shape,
   11339            1 :             gap_chance,
   11340            1 :             will_init_chance,
   11341            1 :         };
   11342              : 
   11343              :         // Create and randomly fill in the layers according to the specification
   11344            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11345            1 :             &tenant,
   11346            1 :             TIMELINE_ID,
   11347            1 :             DEFAULT_PG_VERSION,
   11348            1 :             specification,
   11349            1 :             &mut random,
   11350            1 :             &ctx,
   11351            1 :         )
   11352            1 :         .await?;
   11353              : 
   11354              :         // Now generate queries based on the interesting lsns that we've collected.
   11355              :         //
   11356              :         // While there's still room in the query, pick and interesting LSN and a random
   11357              :         // key. Then roll the dice to see if the next key should also be included in
   11358              :         // the query. When the roll fails, break the "batch" and pick another point in the
   11359              :         // (key, LSN) space.
   11360              : 
   11361              :         const PICK_NEXT_CHANCE: u8 = 50;
   11362            1 :         for _ in 0..queries {
   11363         1000 :             let query = {
   11364         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11365         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11366            1 : 
   11367        22536 :                 while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11368        21536 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11369        21536 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11370            1 : 
   11371        37614 :                     while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11372        37093 :                         if used_keys.contains(&selected_key)
   11373        32154 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11374            1 :                         {
   11375         5093 :                             break;
   11376        32000 :                         }
   11377            1 : 
   11378        32000 :                         keyspaces_at_lsn
   11379        32000 :                             .entry(*selected_lsn)
   11380        32000 :                             .or_default()
   11381        32000 :                             .add_key(selected_key);
   11382        32000 :                         used_keys.insert(selected_key);
   11383            1 : 
   11384        32000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11385        32000 :                         if pick_next {
   11386        16078 :                             selected_key = selected_key.next();
   11387        16078 :                         } else {
   11388        15922 :                             break;
   11389            1 :                         }
   11390            1 :                     }
   11391            1 :                 }
   11392            1 : 
   11393         1000 :                 VersionedKeySpaceQuery::scattered(
   11394         1000 :                     keyspaces_at_lsn
   11395         1000 :                         .into_iter()
   11396        11917 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11397         1000 :                         .collect(),
   11398            1 :                 )
   11399            1 :             };
   11400            1 : 
   11401            1 :             // Run the query and validate the results
   11402            1 : 
   11403         1000 :             let results = tline
   11404         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11405         1000 :                 .await;
   11406            1 : 
   11407         1000 :             let blobs = match results {
   11408         1000 :                 Ok(ok) => ok,
   11409            1 :                 Err(err) => {
   11410            1 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11411            1 :                 }
   11412            1 :             };
   11413            1 : 
   11414        32000 :             for (key, key_res) in blobs.into_iter() {
   11415        32000 :                 match key_res {
   11416        32000 :                     Ok(blob) => {
   11417        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11418        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11419            1 : 
   11420        32000 :                         if blob != expected {
   11421            1 :                             tracing::error!(
   11422            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11423            1 :                             );
   11424        32000 :                         }
   11425            1 : 
   11426        32000 :                         assert_eq!(blob, expected);
   11427            1 :                     }
   11428            1 :                     Err(err) => {
   11429            1 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11430            1 : 
   11431            1 :                         panic!(
   11432            1 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11433            1 :                         );
   11434            1 :                     }
   11435            1 :                 }
   11436            1 :             }
   11437            1 :         }
   11438            1 : 
   11439            1 :         Ok(())
   11440            1 :     }
   11441              : 
   11442          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11443          107 :         (
   11444          107 :             k1.is_delta,
   11445          107 :             k1.key_range.start,
   11446          107 :             k1.key_range.end,
   11447          107 :             k1.lsn_range.start,
   11448          107 :             k1.lsn_range.end,
   11449          107 :         )
   11450          107 :             .cmp(&(
   11451          107 :                 k2.is_delta,
   11452          107 :                 k2.key_range.start,
   11453          107 :                 k2.key_range.end,
   11454          107 :                 k2.lsn_range.start,
   11455          107 :                 k2.lsn_range.end,
   11456          107 :             ))
   11457          107 :     }
   11458              : 
   11459           12 :     async fn inspect_and_sort(
   11460           12 :         tline: &Arc<Timeline>,
   11461           12 :         filter: Option<std::ops::Range<Key>>,
   11462           12 :     ) -> Vec<PersistentLayerKey> {
   11463           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11464           12 :         if let Some(filter) = filter {
   11465           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11466            1 :         }
   11467           12 :         all_layers.sort_by(sort_layer_key);
   11468           12 :         all_layers
   11469           12 :     }
   11470              : 
   11471              :     #[cfg(feature = "testing")]
   11472           11 :     fn check_layer_map_key_eq(
   11473           11 :         mut left: Vec<PersistentLayerKey>,
   11474           11 :         mut right: Vec<PersistentLayerKey>,
   11475           11 :     ) {
   11476           11 :         left.sort_by(sort_layer_key);
   11477           11 :         right.sort_by(sort_layer_key);
   11478           11 :         if left != right {
   11479            0 :             eprintln!("---LEFT---");
   11480            0 :             for left in left.iter() {
   11481            0 :                 eprintln!("{left}");
   11482            0 :             }
   11483            0 :             eprintln!("---RIGHT---");
   11484            0 :             for right in right.iter() {
   11485            0 :                 eprintln!("{right}");
   11486            0 :             }
   11487            0 :             assert_eq!(left, right);
   11488           11 :         }
   11489           11 :     }
   11490              : 
   11491              :     #[cfg(feature = "testing")]
   11492              :     #[tokio::test]
   11493            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11494            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11495            1 :         let (tenant, ctx) = harness.load().await;
   11496              : 
   11497           91 :         fn get_key(id: u32) -> Key {
   11498              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11499           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11500           91 :             key.field6 = id;
   11501           91 :             key
   11502           91 :         }
   11503              : 
   11504              :         // img layer at 0x10
   11505            1 :         let img_layer = (0..10)
   11506           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11507            1 :             .collect_vec();
   11508              : 
   11509            1 :         let delta1 = vec![
   11510            1 :             (
   11511            1 :                 get_key(1),
   11512            1 :                 Lsn(0x20),
   11513            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11514            1 :             ),
   11515            1 :             (
   11516            1 :                 get_key(2),
   11517            1 :                 Lsn(0x30),
   11518            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11519            1 :             ),
   11520            1 :             (
   11521            1 :                 get_key(3),
   11522            1 :                 Lsn(0x40),
   11523            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11524            1 :             ),
   11525              :         ];
   11526            1 :         let delta2 = vec![
   11527            1 :             (
   11528            1 :                 get_key(5),
   11529            1 :                 Lsn(0x20),
   11530            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11531            1 :             ),
   11532            1 :             (
   11533            1 :                 get_key(6),
   11534            1 :                 Lsn(0x20),
   11535            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11536            1 :             ),
   11537              :         ];
   11538            1 :         let delta3 = vec![
   11539            1 :             (
   11540            1 :                 get_key(8),
   11541            1 :                 Lsn(0x48),
   11542            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11543            1 :             ),
   11544            1 :             (
   11545            1 :                 get_key(9),
   11546            1 :                 Lsn(0x48),
   11547            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11548            1 :             ),
   11549              :         ];
   11550              : 
   11551            1 :         let tline = tenant
   11552            1 :             .create_test_timeline_with_layers(
   11553            1 :                 TIMELINE_ID,
   11554            1 :                 Lsn(0x10),
   11555            1 :                 DEFAULT_PG_VERSION,
   11556            1 :                 &ctx,
   11557            1 :                 vec![], // in-memory layers
   11558            1 :                 vec![
   11559            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11560            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11561            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11562            1 :                 ], // delta layers
   11563            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11564            1 :                 Lsn(0x50),
   11565            1 :             )
   11566            1 :             .await?;
   11567              : 
   11568              :         {
   11569            1 :             tline
   11570            1 :                 .applied_gc_cutoff_lsn
   11571            1 :                 .lock_for_write()
   11572            1 :                 .store_and_unlock(Lsn(0x30))
   11573            1 :                 .wait()
   11574            1 :                 .await;
   11575              :             // Update GC info
   11576            1 :             let mut guard = tline.gc_info.write().unwrap();
   11577            1 :             *guard = GcInfo {
   11578            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11579            1 :                 cutoffs: GcCutoffs {
   11580            1 :                     time: Some(Lsn(0x30)),
   11581            1 :                     space: Lsn(0x30),
   11582            1 :                 },
   11583            1 :                 leases: Default::default(),
   11584            1 :                 within_ancestor_pitr: false,
   11585            1 :             };
   11586              :         }
   11587              : 
   11588            1 :         let cancel = CancellationToken::new();
   11589              : 
   11590              :         // Do a partial compaction on key range 0..2
   11591            1 :         tline
   11592            1 :             .compact_with_gc(
   11593            1 :                 &cancel,
   11594            1 :                 CompactOptions {
   11595            1 :                     flags: EnumSet::new(),
   11596            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11597            1 :                     ..Default::default()
   11598            1 :                 },
   11599            1 :                 &ctx,
   11600            1 :             )
   11601            1 :             .await
   11602            1 :             .unwrap();
   11603            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11604            1 :         check_layer_map_key_eq(
   11605            1 :             all_layers,
   11606            1 :             vec![
   11607              :                 // newly-generated image layer for the partial compaction range 0-2
   11608            1 :                 PersistentLayerKey {
   11609            1 :                     key_range: get_key(0)..get_key(2),
   11610            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11611            1 :                     is_delta: false,
   11612            1 :                 },
   11613            1 :                 PersistentLayerKey {
   11614            1 :                     key_range: get_key(0)..get_key(10),
   11615            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11616            1 :                     is_delta: false,
   11617            1 :                 },
   11618              :                 // delta1 is split and the second part is rewritten
   11619            1 :                 PersistentLayerKey {
   11620            1 :                     key_range: get_key(2)..get_key(4),
   11621            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11622            1 :                     is_delta: true,
   11623            1 :                 },
   11624            1 :                 PersistentLayerKey {
   11625            1 :                     key_range: get_key(5)..get_key(7),
   11626            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11627            1 :                     is_delta: true,
   11628            1 :                 },
   11629            1 :                 PersistentLayerKey {
   11630            1 :                     key_range: get_key(8)..get_key(10),
   11631            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11632            1 :                     is_delta: true,
   11633            1 :                 },
   11634              :             ],
   11635              :         );
   11636              : 
   11637              :         // Do a partial compaction on key range 2..4
   11638            1 :         tline
   11639            1 :             .compact_with_gc(
   11640            1 :                 &cancel,
   11641            1 :                 CompactOptions {
   11642            1 :                     flags: EnumSet::new(),
   11643            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11644            1 :                     ..Default::default()
   11645            1 :                 },
   11646            1 :                 &ctx,
   11647            1 :             )
   11648            1 :             .await
   11649            1 :             .unwrap();
   11650            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11651            1 :         check_layer_map_key_eq(
   11652            1 :             all_layers,
   11653            1 :             vec![
   11654            1 :                 PersistentLayerKey {
   11655            1 :                     key_range: get_key(0)..get_key(2),
   11656            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11657            1 :                     is_delta: false,
   11658            1 :                 },
   11659            1 :                 PersistentLayerKey {
   11660            1 :                     key_range: get_key(0)..get_key(10),
   11661            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11662            1 :                     is_delta: false,
   11663            1 :                 },
   11664              :                 // image layer generated for the compaction range 2-4
   11665            1 :                 PersistentLayerKey {
   11666            1 :                     key_range: get_key(2)..get_key(4),
   11667            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11668            1 :                     is_delta: false,
   11669            1 :                 },
   11670              :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11671            1 :                 PersistentLayerKey {
   11672            1 :                     key_range: get_key(2)..get_key(4),
   11673            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11674            1 :                     is_delta: true,
   11675            1 :                 },
   11676            1 :                 PersistentLayerKey {
   11677            1 :                     key_range: get_key(5)..get_key(7),
   11678            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11679            1 :                     is_delta: true,
   11680            1 :                 },
   11681            1 :                 PersistentLayerKey {
   11682            1 :                     key_range: get_key(8)..get_key(10),
   11683            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11684            1 :                     is_delta: true,
   11685            1 :                 },
   11686              :             ],
   11687              :         );
   11688              : 
   11689              :         // Do a partial compaction on key range 4..9
   11690            1 :         tline
   11691            1 :             .compact_with_gc(
   11692            1 :                 &cancel,
   11693            1 :                 CompactOptions {
   11694            1 :                     flags: EnumSet::new(),
   11695            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11696            1 :                     ..Default::default()
   11697            1 :                 },
   11698            1 :                 &ctx,
   11699            1 :             )
   11700            1 :             .await
   11701            1 :             .unwrap();
   11702            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11703            1 :         check_layer_map_key_eq(
   11704            1 :             all_layers,
   11705            1 :             vec![
   11706            1 :                 PersistentLayerKey {
   11707            1 :                     key_range: get_key(0)..get_key(2),
   11708            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11709            1 :                     is_delta: false,
   11710            1 :                 },
   11711            1 :                 PersistentLayerKey {
   11712            1 :                     key_range: get_key(0)..get_key(10),
   11713            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11714            1 :                     is_delta: false,
   11715            1 :                 },
   11716            1 :                 PersistentLayerKey {
   11717            1 :                     key_range: get_key(2)..get_key(4),
   11718            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11719            1 :                     is_delta: false,
   11720            1 :                 },
   11721            1 :                 PersistentLayerKey {
   11722            1 :                     key_range: get_key(2)..get_key(4),
   11723            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11724            1 :                     is_delta: true,
   11725            1 :                 },
   11726              :                 // image layer generated for this compaction range
   11727            1 :                 PersistentLayerKey {
   11728            1 :                     key_range: get_key(4)..get_key(9),
   11729            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11730            1 :                     is_delta: false,
   11731            1 :                 },
   11732            1 :                 PersistentLayerKey {
   11733            1 :                     key_range: get_key(8)..get_key(10),
   11734            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11735            1 :                     is_delta: true,
   11736            1 :                 },
   11737              :             ],
   11738              :         );
   11739              : 
   11740              :         // Do a partial compaction on key range 9..10
   11741            1 :         tline
   11742            1 :             .compact_with_gc(
   11743            1 :                 &cancel,
   11744            1 :                 CompactOptions {
   11745            1 :                     flags: EnumSet::new(),
   11746            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11747            1 :                     ..Default::default()
   11748            1 :                 },
   11749            1 :                 &ctx,
   11750            1 :             )
   11751            1 :             .await
   11752            1 :             .unwrap();
   11753            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11754            1 :         check_layer_map_key_eq(
   11755            1 :             all_layers,
   11756            1 :             vec![
   11757            1 :                 PersistentLayerKey {
   11758            1 :                     key_range: get_key(0)..get_key(2),
   11759            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11760            1 :                     is_delta: false,
   11761            1 :                 },
   11762            1 :                 PersistentLayerKey {
   11763            1 :                     key_range: get_key(0)..get_key(10),
   11764            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11765            1 :                     is_delta: false,
   11766            1 :                 },
   11767            1 :                 PersistentLayerKey {
   11768            1 :                     key_range: get_key(2)..get_key(4),
   11769            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11770            1 :                     is_delta: false,
   11771            1 :                 },
   11772            1 :                 PersistentLayerKey {
   11773            1 :                     key_range: get_key(2)..get_key(4),
   11774            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11775            1 :                     is_delta: true,
   11776            1 :                 },
   11777            1 :                 PersistentLayerKey {
   11778            1 :                     key_range: get_key(4)..get_key(9),
   11779            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11780            1 :                     is_delta: false,
   11781            1 :                 },
   11782              :                 // image layer generated for the compaction range
   11783            1 :                 PersistentLayerKey {
   11784            1 :                     key_range: get_key(9)..get_key(10),
   11785            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11786            1 :                     is_delta: false,
   11787            1 :                 },
   11788            1 :                 PersistentLayerKey {
   11789            1 :                     key_range: get_key(8)..get_key(10),
   11790            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11791            1 :                     is_delta: true,
   11792            1 :                 },
   11793              :             ],
   11794              :         );
   11795              : 
   11796              :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11797            1 :         tline
   11798            1 :             .compact_with_gc(
   11799            1 :                 &cancel,
   11800            1 :                 CompactOptions {
   11801            1 :                     flags: EnumSet::new(),
   11802            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11803            1 :                     ..Default::default()
   11804            1 :                 },
   11805            1 :                 &ctx,
   11806            1 :             )
   11807            1 :             .await
   11808            1 :             .unwrap();
   11809            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11810            1 :         check_layer_map_key_eq(
   11811            1 :             all_layers,
   11812            1 :             vec![
   11813              :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11814            1 :                 PersistentLayerKey {
   11815            1 :                     key_range: get_key(0)..get_key(10),
   11816            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11817            1 :                     is_delta: false,
   11818            1 :                 },
   11819            1 :                 PersistentLayerKey {
   11820            1 :                     key_range: get_key(2)..get_key(4),
   11821            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11822            1 :                     is_delta: true,
   11823            1 :                 },
   11824            1 :                 PersistentLayerKey {
   11825            1 :                     key_range: get_key(8)..get_key(10),
   11826            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11827            1 :                     is_delta: true,
   11828            1 :                 },
   11829              :             ],
   11830              :         );
   11831            2 :         Ok(())
   11832            1 :     }
   11833              : 
   11834              :     #[cfg(feature = "testing")]
   11835              :     #[tokio::test]
   11836            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11837            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11838            1 :             .await
   11839            1 :             .unwrap();
   11840            1 :         let (tenant, ctx) = harness.load().await;
   11841            1 :         let tline_parent = tenant
   11842            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11843            1 :             .await
   11844            1 :             .unwrap();
   11845            1 :         let tline_child = tenant
   11846            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11847            1 :             .await
   11848            1 :             .unwrap();
   11849              :         {
   11850            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11851            1 :             assert_eq!(
   11852            1 :                 gc_info_parent.retain_lsns,
   11853            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11854              :             );
   11855              :         }
   11856              :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11857            1 :         tline_child
   11858            1 :             .remote_client
   11859            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11860            1 :             .unwrap();
   11861            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11862            1 :         offload_timeline(&tenant, &tline_child)
   11863            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11864            1 :             .await.unwrap();
   11865            1 :         let child_timeline_id = tline_child.timeline_id;
   11866            1 :         Arc::try_unwrap(tline_child).unwrap();
   11867              : 
   11868              :         {
   11869            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11870            1 :             assert_eq!(
   11871            1 :                 gc_info_parent.retain_lsns,
   11872            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11873              :             );
   11874              :         }
   11875              : 
   11876            1 :         tenant
   11877            1 :             .get_offloaded_timeline(child_timeline_id)
   11878            1 :             .unwrap()
   11879            1 :             .defuse_for_tenant_drop();
   11880              : 
   11881            2 :         Ok(())
   11882            1 :     }
   11883              : 
   11884              :     #[cfg(feature = "testing")]
   11885              :     #[tokio::test]
   11886            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11887            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11888            1 :         let (tenant, ctx) = harness.load().await;
   11889              : 
   11890          148 :         fn get_key(id: u32) -> Key {
   11891              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11892          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11893          148 :             key.field6 = id;
   11894          148 :             key
   11895          148 :         }
   11896              : 
   11897            1 :         let img_layer = (0..10)
   11898           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11899            1 :             .collect_vec();
   11900              : 
   11901            1 :         let delta1 = vec![(
   11902            1 :             get_key(1),
   11903            1 :             Lsn(0x20),
   11904            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11905            1 :         )];
   11906            1 :         let delta4 = vec![(
   11907            1 :             get_key(1),
   11908            1 :             Lsn(0x28),
   11909            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11910            1 :         )];
   11911            1 :         let delta2 = vec![
   11912            1 :             (
   11913            1 :                 get_key(1),
   11914            1 :                 Lsn(0x30),
   11915            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11916            1 :             ),
   11917            1 :             (
   11918            1 :                 get_key(1),
   11919            1 :                 Lsn(0x38),
   11920            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11921            1 :             ),
   11922              :         ];
   11923            1 :         let delta3 = vec![
   11924            1 :             (
   11925            1 :                 get_key(8),
   11926            1 :                 Lsn(0x48),
   11927            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11928            1 :             ),
   11929            1 :             (
   11930            1 :                 get_key(9),
   11931            1 :                 Lsn(0x48),
   11932            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11933            1 :             ),
   11934              :         ];
   11935              : 
   11936            1 :         let tline = tenant
   11937            1 :             .create_test_timeline_with_layers(
   11938            1 :                 TIMELINE_ID,
   11939            1 :                 Lsn(0x10),
   11940            1 :                 DEFAULT_PG_VERSION,
   11941            1 :                 &ctx,
   11942            1 :                 vec![], // in-memory layers
   11943            1 :                 vec![
   11944            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11945            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11946            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11947            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11948            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11949            1 :                 ], // delta layers
   11950            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11951            1 :                 Lsn(0x50),
   11952            1 :             )
   11953            1 :             .await?;
   11954              :         {
   11955            1 :             tline
   11956            1 :                 .applied_gc_cutoff_lsn
   11957            1 :                 .lock_for_write()
   11958            1 :                 .store_and_unlock(Lsn(0x30))
   11959            1 :                 .wait()
   11960            1 :                 .await;
   11961              :             // Update GC info
   11962            1 :             let mut guard = tline.gc_info.write().unwrap();
   11963            1 :             *guard = GcInfo {
   11964            1 :                 retain_lsns: vec![
   11965            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11966            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11967            1 :                 ],
   11968            1 :                 cutoffs: GcCutoffs {
   11969            1 :                     time: Some(Lsn(0x30)),
   11970            1 :                     space: Lsn(0x30),
   11971            1 :                 },
   11972            1 :                 leases: Default::default(),
   11973            1 :                 within_ancestor_pitr: false,
   11974            1 :             };
   11975              :         }
   11976              : 
   11977            1 :         let expected_result = [
   11978            1 :             Bytes::from_static(b"value 0@0x10"),
   11979            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11980            1 :             Bytes::from_static(b"value 2@0x10"),
   11981            1 :             Bytes::from_static(b"value 3@0x10"),
   11982            1 :             Bytes::from_static(b"value 4@0x10"),
   11983            1 :             Bytes::from_static(b"value 5@0x10"),
   11984            1 :             Bytes::from_static(b"value 6@0x10"),
   11985            1 :             Bytes::from_static(b"value 7@0x10"),
   11986            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11987            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11988            1 :         ];
   11989              : 
   11990            1 :         let expected_result_at_gc_horizon = [
   11991            1 :             Bytes::from_static(b"value 0@0x10"),
   11992            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11993            1 :             Bytes::from_static(b"value 2@0x10"),
   11994            1 :             Bytes::from_static(b"value 3@0x10"),
   11995            1 :             Bytes::from_static(b"value 4@0x10"),
   11996            1 :             Bytes::from_static(b"value 5@0x10"),
   11997            1 :             Bytes::from_static(b"value 6@0x10"),
   11998            1 :             Bytes::from_static(b"value 7@0x10"),
   11999            1 :             Bytes::from_static(b"value 8@0x10"),
   12000            1 :             Bytes::from_static(b"value 9@0x10"),
   12001            1 :         ];
   12002              : 
   12003            1 :         let expected_result_at_lsn_20 = [
   12004            1 :             Bytes::from_static(b"value 0@0x10"),
   12005            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12006            1 :             Bytes::from_static(b"value 2@0x10"),
   12007            1 :             Bytes::from_static(b"value 3@0x10"),
   12008            1 :             Bytes::from_static(b"value 4@0x10"),
   12009            1 :             Bytes::from_static(b"value 5@0x10"),
   12010            1 :             Bytes::from_static(b"value 6@0x10"),
   12011            1 :             Bytes::from_static(b"value 7@0x10"),
   12012            1 :             Bytes::from_static(b"value 8@0x10"),
   12013            1 :             Bytes::from_static(b"value 9@0x10"),
   12014            1 :         ];
   12015              : 
   12016            1 :         let expected_result_at_lsn_10 = [
   12017            1 :             Bytes::from_static(b"value 0@0x10"),
   12018            1 :             Bytes::from_static(b"value 1@0x10"),
   12019            1 :             Bytes::from_static(b"value 2@0x10"),
   12020            1 :             Bytes::from_static(b"value 3@0x10"),
   12021            1 :             Bytes::from_static(b"value 4@0x10"),
   12022            1 :             Bytes::from_static(b"value 5@0x10"),
   12023            1 :             Bytes::from_static(b"value 6@0x10"),
   12024            1 :             Bytes::from_static(b"value 7@0x10"),
   12025            1 :             Bytes::from_static(b"value 8@0x10"),
   12026            1 :             Bytes::from_static(b"value 9@0x10"),
   12027            1 :         ];
   12028              : 
   12029            3 :         let verify_result = || async {
   12030            3 :             let gc_horizon = {
   12031            3 :                 let gc_info = tline.gc_info.read().unwrap();
   12032            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   12033              :             };
   12034           33 :             for idx in 0..10 {
   12035           30 :                 assert_eq!(
   12036           30 :                     tline
   12037           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12038           30 :                         .await
   12039           30 :                         .unwrap(),
   12040           30 :                     &expected_result[idx]
   12041              :                 );
   12042           30 :                 assert_eq!(
   12043           30 :                     tline
   12044           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12045           30 :                         .await
   12046           30 :                         .unwrap(),
   12047           30 :                     &expected_result_at_gc_horizon[idx]
   12048              :                 );
   12049           30 :                 assert_eq!(
   12050           30 :                     tline
   12051           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12052           30 :                         .await
   12053           30 :                         .unwrap(),
   12054           30 :                     &expected_result_at_lsn_20[idx]
   12055              :                 );
   12056           30 :                 assert_eq!(
   12057           30 :                     tline
   12058           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12059           30 :                         .await
   12060           30 :                         .unwrap(),
   12061           30 :                     &expected_result_at_lsn_10[idx]
   12062              :                 );
   12063              :             }
   12064            6 :         };
   12065              : 
   12066            1 :         verify_result().await;
   12067              : 
   12068            1 :         let cancel = CancellationToken::new();
   12069            1 :         tline
   12070            1 :             .compact_with_gc(
   12071            1 :                 &cancel,
   12072            1 :                 CompactOptions {
   12073            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   12074            1 :                     ..Default::default()
   12075            1 :                 },
   12076            1 :                 &ctx,
   12077            1 :             )
   12078            1 :             .await
   12079            1 :             .unwrap();
   12080            1 :         verify_result().await;
   12081              : 
   12082            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12083            1 :         check_layer_map_key_eq(
   12084            1 :             all_layers,
   12085            1 :             vec![
   12086              :                 // The original image layer, not compacted
   12087            1 :                 PersistentLayerKey {
   12088            1 :                     key_range: get_key(0)..get_key(10),
   12089            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12090            1 :                     is_delta: false,
   12091            1 :                 },
   12092              :                 // Delta layer below the specified above_lsn not compacted
   12093            1 :                 PersistentLayerKey {
   12094            1 :                     key_range: get_key(1)..get_key(2),
   12095            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   12096            1 :                     is_delta: true,
   12097            1 :                 },
   12098              :                 // Delta layer compacted above the LSN
   12099            1 :                 PersistentLayerKey {
   12100            1 :                     key_range: get_key(1)..get_key(10),
   12101            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   12102            1 :                     is_delta: true,
   12103            1 :                 },
   12104              :             ],
   12105              :         );
   12106              : 
   12107              :         // compact again
   12108            1 :         tline
   12109            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12110            1 :             .await
   12111            1 :             .unwrap();
   12112            1 :         verify_result().await;
   12113              : 
   12114            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12115            1 :         check_layer_map_key_eq(
   12116            1 :             all_layers,
   12117            1 :             vec![
   12118              :                 // The compacted image layer (full key range)
   12119            1 :                 PersistentLayerKey {
   12120            1 :                     key_range: Key::MIN..Key::MAX,
   12121            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12122            1 :                     is_delta: false,
   12123            1 :                 },
   12124              :                 // All other data in the delta layer
   12125            1 :                 PersistentLayerKey {
   12126            1 :                     key_range: get_key(1)..get_key(10),
   12127            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12128            1 :                     is_delta: true,
   12129            1 :                 },
   12130              :             ],
   12131              :         );
   12132              : 
   12133            2 :         Ok(())
   12134            1 :     }
   12135              : 
   12136              :     #[cfg(feature = "testing")]
   12137              :     #[tokio::test]
   12138            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   12139            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   12140            1 :         let (tenant, ctx) = harness.load().await;
   12141              : 
   12142          254 :         fn get_key(id: u32) -> Key {
   12143              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12144          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12145          254 :             key.field6 = id;
   12146          254 :             key
   12147          254 :         }
   12148              : 
   12149            1 :         let img_layer = (0..10)
   12150           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12151            1 :             .collect_vec();
   12152              : 
   12153            1 :         let delta1 = vec![(
   12154            1 :             get_key(1),
   12155            1 :             Lsn(0x20),
   12156            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12157            1 :         )];
   12158            1 :         let delta4 = vec![(
   12159            1 :             get_key(1),
   12160            1 :             Lsn(0x28),
   12161            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   12162            1 :         )];
   12163            1 :         let delta2 = vec![
   12164            1 :             (
   12165            1 :                 get_key(1),
   12166            1 :                 Lsn(0x30),
   12167            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   12168            1 :             ),
   12169            1 :             (
   12170            1 :                 get_key(1),
   12171            1 :                 Lsn(0x38),
   12172            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   12173            1 :             ),
   12174              :         ];
   12175            1 :         let delta3 = vec![
   12176            1 :             (
   12177            1 :                 get_key(8),
   12178            1 :                 Lsn(0x48),
   12179            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12180            1 :             ),
   12181            1 :             (
   12182            1 :                 get_key(9),
   12183            1 :                 Lsn(0x48),
   12184            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12185            1 :             ),
   12186              :         ];
   12187              : 
   12188            1 :         let tline = tenant
   12189            1 :             .create_test_timeline_with_layers(
   12190            1 :                 TIMELINE_ID,
   12191            1 :                 Lsn(0x10),
   12192            1 :                 DEFAULT_PG_VERSION,
   12193            1 :                 &ctx,
   12194            1 :                 vec![], // in-memory layers
   12195            1 :                 vec![
   12196            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12197            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12198            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12199            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12200            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12201            1 :                 ], // delta layers
   12202            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12203            1 :                 Lsn(0x50),
   12204            1 :             )
   12205            1 :             .await?;
   12206              :         {
   12207            1 :             tline
   12208            1 :                 .applied_gc_cutoff_lsn
   12209            1 :                 .lock_for_write()
   12210            1 :                 .store_and_unlock(Lsn(0x30))
   12211            1 :                 .wait()
   12212            1 :                 .await;
   12213              :             // Update GC info
   12214            1 :             let mut guard = tline.gc_info.write().unwrap();
   12215            1 :             *guard = GcInfo {
   12216            1 :                 retain_lsns: vec![
   12217            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12218            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12219            1 :                 ],
   12220            1 :                 cutoffs: GcCutoffs {
   12221            1 :                     time: Some(Lsn(0x30)),
   12222            1 :                     space: Lsn(0x30),
   12223            1 :                 },
   12224            1 :                 leases: Default::default(),
   12225            1 :                 within_ancestor_pitr: false,
   12226            1 :             };
   12227              :         }
   12228              : 
   12229            1 :         let expected_result = [
   12230            1 :             Bytes::from_static(b"value 0@0x10"),
   12231            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12232            1 :             Bytes::from_static(b"value 2@0x10"),
   12233            1 :             Bytes::from_static(b"value 3@0x10"),
   12234            1 :             Bytes::from_static(b"value 4@0x10"),
   12235            1 :             Bytes::from_static(b"value 5@0x10"),
   12236            1 :             Bytes::from_static(b"value 6@0x10"),
   12237            1 :             Bytes::from_static(b"value 7@0x10"),
   12238            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12239            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12240            1 :         ];
   12241              : 
   12242            1 :         let expected_result_at_gc_horizon = [
   12243            1 :             Bytes::from_static(b"value 0@0x10"),
   12244            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12245            1 :             Bytes::from_static(b"value 2@0x10"),
   12246            1 :             Bytes::from_static(b"value 3@0x10"),
   12247            1 :             Bytes::from_static(b"value 4@0x10"),
   12248            1 :             Bytes::from_static(b"value 5@0x10"),
   12249            1 :             Bytes::from_static(b"value 6@0x10"),
   12250            1 :             Bytes::from_static(b"value 7@0x10"),
   12251            1 :             Bytes::from_static(b"value 8@0x10"),
   12252            1 :             Bytes::from_static(b"value 9@0x10"),
   12253            1 :         ];
   12254              : 
   12255            1 :         let expected_result_at_lsn_20 = [
   12256            1 :             Bytes::from_static(b"value 0@0x10"),
   12257            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12258            1 :             Bytes::from_static(b"value 2@0x10"),
   12259            1 :             Bytes::from_static(b"value 3@0x10"),
   12260            1 :             Bytes::from_static(b"value 4@0x10"),
   12261            1 :             Bytes::from_static(b"value 5@0x10"),
   12262            1 :             Bytes::from_static(b"value 6@0x10"),
   12263            1 :             Bytes::from_static(b"value 7@0x10"),
   12264            1 :             Bytes::from_static(b"value 8@0x10"),
   12265            1 :             Bytes::from_static(b"value 9@0x10"),
   12266            1 :         ];
   12267              : 
   12268            1 :         let expected_result_at_lsn_10 = [
   12269            1 :             Bytes::from_static(b"value 0@0x10"),
   12270            1 :             Bytes::from_static(b"value 1@0x10"),
   12271            1 :             Bytes::from_static(b"value 2@0x10"),
   12272            1 :             Bytes::from_static(b"value 3@0x10"),
   12273            1 :             Bytes::from_static(b"value 4@0x10"),
   12274            1 :             Bytes::from_static(b"value 5@0x10"),
   12275            1 :             Bytes::from_static(b"value 6@0x10"),
   12276            1 :             Bytes::from_static(b"value 7@0x10"),
   12277            1 :             Bytes::from_static(b"value 8@0x10"),
   12278            1 :             Bytes::from_static(b"value 9@0x10"),
   12279            1 :         ];
   12280              : 
   12281            5 :         let verify_result = || async {
   12282            5 :             let gc_horizon = {
   12283            5 :                 let gc_info = tline.gc_info.read().unwrap();
   12284            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   12285              :             };
   12286           55 :             for idx in 0..10 {
   12287           50 :                 assert_eq!(
   12288           50 :                     tline
   12289           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12290           50 :                         .await
   12291           50 :                         .unwrap(),
   12292           50 :                     &expected_result[idx]
   12293              :                 );
   12294           50 :                 assert_eq!(
   12295           50 :                     tline
   12296           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12297           50 :                         .await
   12298           50 :                         .unwrap(),
   12299           50 :                     &expected_result_at_gc_horizon[idx]
   12300              :                 );
   12301           50 :                 assert_eq!(
   12302           50 :                     tline
   12303           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12304           50 :                         .await
   12305           50 :                         .unwrap(),
   12306           50 :                     &expected_result_at_lsn_20[idx]
   12307              :                 );
   12308           50 :                 assert_eq!(
   12309           50 :                     tline
   12310           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12311           50 :                         .await
   12312           50 :                         .unwrap(),
   12313           50 :                     &expected_result_at_lsn_10[idx]
   12314              :                 );
   12315              :             }
   12316           10 :         };
   12317              : 
   12318            1 :         verify_result().await;
   12319              : 
   12320            1 :         let cancel = CancellationToken::new();
   12321              : 
   12322            1 :         tline
   12323            1 :             .compact_with_gc(
   12324            1 :                 &cancel,
   12325            1 :                 CompactOptions {
   12326            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12327            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12328            1 :                     ..Default::default()
   12329            1 :                 },
   12330            1 :                 &ctx,
   12331            1 :             )
   12332            1 :             .await
   12333            1 :             .unwrap();
   12334            1 :         verify_result().await;
   12335              : 
   12336            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12337            1 :         check_layer_map_key_eq(
   12338            1 :             all_layers,
   12339            1 :             vec![
   12340              :                 // The original image layer, not compacted
   12341            1 :                 PersistentLayerKey {
   12342            1 :                     key_range: get_key(0)..get_key(10),
   12343            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12344            1 :                     is_delta: false,
   12345            1 :                 },
   12346              :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12347              :                 // the layer 0x28-0x30 into one.
   12348            1 :                 PersistentLayerKey {
   12349            1 :                     key_range: get_key(1)..get_key(2),
   12350            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12351            1 :                     is_delta: true,
   12352            1 :                 },
   12353              :                 // Above the upper bound and untouched
   12354            1 :                 PersistentLayerKey {
   12355            1 :                     key_range: get_key(1)..get_key(2),
   12356            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12357            1 :                     is_delta: true,
   12358            1 :                 },
   12359              :                 // This layer is untouched
   12360            1 :                 PersistentLayerKey {
   12361            1 :                     key_range: get_key(8)..get_key(10),
   12362            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12363            1 :                     is_delta: true,
   12364            1 :                 },
   12365              :             ],
   12366              :         );
   12367              : 
   12368            1 :         tline
   12369            1 :             .compact_with_gc(
   12370            1 :                 &cancel,
   12371            1 :                 CompactOptions {
   12372            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12373            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12374            1 :                     ..Default::default()
   12375            1 :                 },
   12376            1 :                 &ctx,
   12377            1 :             )
   12378            1 :             .await
   12379            1 :             .unwrap();
   12380            1 :         verify_result().await;
   12381              : 
   12382            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12383            1 :         check_layer_map_key_eq(
   12384            1 :             all_layers,
   12385            1 :             vec![
   12386              :                 // The original image layer, not compacted
   12387            1 :                 PersistentLayerKey {
   12388            1 :                     key_range: get_key(0)..get_key(10),
   12389            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12390            1 :                     is_delta: false,
   12391            1 :                 },
   12392              :                 // Not in the compaction key range, uncompacted
   12393            1 :                 PersistentLayerKey {
   12394            1 :                     key_range: get_key(1)..get_key(2),
   12395            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12396            1 :                     is_delta: true,
   12397            1 :                 },
   12398              :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12399            1 :                 PersistentLayerKey {
   12400            1 :                     key_range: get_key(1)..get_key(2),
   12401            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12402            1 :                     is_delta: true,
   12403            1 :                 },
   12404              :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12405              :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12406              :                 // becomes 0x50.
   12407            1 :                 PersistentLayerKey {
   12408            1 :                     key_range: get_key(8)..get_key(10),
   12409            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12410            1 :                     is_delta: true,
   12411            1 :                 },
   12412              :             ],
   12413              :         );
   12414              : 
   12415              :         // compact again
   12416            1 :         tline
   12417            1 :             .compact_with_gc(
   12418            1 :                 &cancel,
   12419            1 :                 CompactOptions {
   12420            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12421            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12422            1 :                     ..Default::default()
   12423            1 :                 },
   12424            1 :                 &ctx,
   12425            1 :             )
   12426            1 :             .await
   12427            1 :             .unwrap();
   12428            1 :         verify_result().await;
   12429              : 
   12430            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12431            1 :         check_layer_map_key_eq(
   12432            1 :             all_layers,
   12433            1 :             vec![
   12434              :                 // The original image layer, not compacted
   12435            1 :                 PersistentLayerKey {
   12436            1 :                     key_range: get_key(0)..get_key(10),
   12437            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12438            1 :                     is_delta: false,
   12439            1 :                 },
   12440              :                 // The range gets compacted
   12441            1 :                 PersistentLayerKey {
   12442            1 :                     key_range: get_key(1)..get_key(2),
   12443            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12444            1 :                     is_delta: true,
   12445            1 :                 },
   12446              :                 // Not touched during this iteration of compaction
   12447            1 :                 PersistentLayerKey {
   12448            1 :                     key_range: get_key(8)..get_key(10),
   12449            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12450            1 :                     is_delta: true,
   12451            1 :                 },
   12452              :             ],
   12453              :         );
   12454              : 
   12455              :         // final full compaction
   12456            1 :         tline
   12457            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12458            1 :             .await
   12459            1 :             .unwrap();
   12460            1 :         verify_result().await;
   12461              : 
   12462            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12463            1 :         check_layer_map_key_eq(
   12464            1 :             all_layers,
   12465            1 :             vec![
   12466              :                 // The compacted image layer (full key range)
   12467            1 :                 PersistentLayerKey {
   12468            1 :                     key_range: Key::MIN..Key::MAX,
   12469            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12470            1 :                     is_delta: false,
   12471            1 :                 },
   12472              :                 // All other data in the delta layer
   12473            1 :                 PersistentLayerKey {
   12474            1 :                     key_range: get_key(1)..get_key(10),
   12475            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12476            1 :                     is_delta: true,
   12477            1 :                 },
   12478              :             ],
   12479              :         );
   12480              : 
   12481            2 :         Ok(())
   12482            1 :     }
   12483              : 
   12484              :     #[cfg(feature = "testing")]
   12485              :     #[tokio::test]
   12486            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12487            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12488            1 :         let (tenant, ctx) = harness.load().await;
   12489              : 
   12490           13 :         fn get_key(id: u32) -> Key {
   12491              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12492           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12493           13 :             key.field6 = id;
   12494           13 :             key
   12495           13 :         }
   12496              : 
   12497            1 :         let img_layer = (0..10)
   12498           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12499            1 :             .collect_vec();
   12500              : 
   12501            1 :         let delta1 = vec![
   12502            1 :             (
   12503            1 :                 get_key(1),
   12504            1 :                 Lsn(0x20),
   12505            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12506            1 :             ),
   12507            1 :             (
   12508            1 :                 get_key(1),
   12509            1 :                 Lsn(0x24),
   12510            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12511            1 :             ),
   12512            1 :             (
   12513            1 :                 get_key(1),
   12514            1 :                 Lsn(0x28),
   12515            1 :                 // This record will fail to redo
   12516            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12517            1 :             ),
   12518              :         ];
   12519              : 
   12520            1 :         let tline = tenant
   12521            1 :             .create_test_timeline_with_layers(
   12522            1 :                 TIMELINE_ID,
   12523            1 :                 Lsn(0x10),
   12524            1 :                 DEFAULT_PG_VERSION,
   12525            1 :                 &ctx,
   12526            1 :                 vec![], // in-memory layers
   12527            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12528            1 :                     Lsn(0x20)..Lsn(0x30),
   12529            1 :                     delta1,
   12530            1 :                 )], // delta layers
   12531            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12532            1 :                 Lsn(0x50),
   12533            1 :             )
   12534            1 :             .await?;
   12535              :         {
   12536            1 :             tline
   12537            1 :                 .applied_gc_cutoff_lsn
   12538            1 :                 .lock_for_write()
   12539            1 :                 .store_and_unlock(Lsn(0x30))
   12540            1 :                 .wait()
   12541            1 :                 .await;
   12542              :             // Update GC info
   12543            1 :             let mut guard = tline.gc_info.write().unwrap();
   12544            1 :             *guard = GcInfo {
   12545            1 :                 retain_lsns: vec![],
   12546            1 :                 cutoffs: GcCutoffs {
   12547            1 :                     time: Some(Lsn(0x30)),
   12548            1 :                     space: Lsn(0x30),
   12549            1 :                 },
   12550            1 :                 leases: Default::default(),
   12551            1 :                 within_ancestor_pitr: false,
   12552            1 :             };
   12553              :         }
   12554              : 
   12555            1 :         let cancel = CancellationToken::new();
   12556              : 
   12557              :         // Compaction will fail, but should not fire any critical error.
   12558              :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12559              :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12560              :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12561            1 :         let res = tline
   12562            1 :             .compact_with_gc(
   12563            1 :                 &cancel,
   12564            1 :                 CompactOptions {
   12565            1 :                     compact_key_range: None,
   12566            1 :                     compact_lsn_range: None,
   12567            1 :                     ..Default::default()
   12568            1 :                 },
   12569            1 :                 &ctx,
   12570            1 :             )
   12571            1 :             .await;
   12572            1 :         assert!(res.is_err());
   12573              : 
   12574            2 :         Ok(())
   12575            1 :     }
   12576              : 
   12577              :     #[cfg(feature = "testing")]
   12578              :     #[tokio::test]
   12579            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12580              :         use pageserver_api::models::TimelineVisibilityState;
   12581              : 
   12582              :         use crate::tenant::size::gather_inputs;
   12583              : 
   12584            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12585            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12586            1 :             pitr_interval: Some(Duration::ZERO),
   12587            1 :             ..Default::default()
   12588            1 :         };
   12589            1 :         let harness = TenantHarness::create_custom(
   12590            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12591            1 :             tenant_conf,
   12592            1 :             TenantId::generate(),
   12593            1 :             ShardIdentity::unsharded(),
   12594            1 :             Generation::new(0xdeadbeef),
   12595            1 :         )
   12596            1 :         .await?;
   12597            1 :         let (tenant, ctx) = harness.load().await;
   12598            1 :         let main_tline = tenant
   12599            1 :             .create_test_timeline_with_layers(
   12600            1 :                 TIMELINE_ID,
   12601            1 :                 Lsn(0x10),
   12602            1 :                 DEFAULT_PG_VERSION,
   12603            1 :                 &ctx,
   12604            1 :                 vec![],
   12605            1 :                 vec![],
   12606            1 :                 vec![],
   12607            1 :                 Lsn(0x100),
   12608            1 :             )
   12609            1 :             .await?;
   12610              : 
   12611            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12612            1 :         tenant
   12613            1 :             .branch_timeline_test_with_layers(
   12614            1 :                 &main_tline,
   12615            1 :                 snapshot1,
   12616            1 :                 Some(Lsn(0x20)),
   12617            1 :                 &ctx,
   12618            1 :                 vec![],
   12619            1 :                 vec![],
   12620            1 :                 Lsn(0x50),
   12621            1 :             )
   12622            1 :             .await?;
   12623            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12624            1 :         tenant
   12625            1 :             .branch_timeline_test_with_layers(
   12626            1 :                 &main_tline,
   12627            1 :                 snapshot2,
   12628            1 :                 Some(Lsn(0x30)),
   12629            1 :                 &ctx,
   12630            1 :                 vec![],
   12631            1 :                 vec![],
   12632            1 :                 Lsn(0x50),
   12633            1 :             )
   12634            1 :             .await?;
   12635            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12636            1 :         tenant
   12637            1 :             .branch_timeline_test_with_layers(
   12638            1 :                 &main_tline,
   12639            1 :                 snapshot3,
   12640            1 :                 Some(Lsn(0x40)),
   12641            1 :                 &ctx,
   12642            1 :                 vec![],
   12643            1 :                 vec![],
   12644            1 :                 Lsn(0x50),
   12645            1 :             )
   12646            1 :             .await?;
   12647            1 :         let limit = Arc::new(Semaphore::new(1));
   12648            1 :         let max_retention_period = None;
   12649            1 :         let mut logical_size_cache = HashMap::new();
   12650            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12651            1 :         let cancel = CancellationToken::new();
   12652              : 
   12653            1 :         let inputs = gather_inputs(
   12654            1 :             &tenant,
   12655            1 :             &limit,
   12656            1 :             max_retention_period,
   12657            1 :             &mut logical_size_cache,
   12658            1 :             cause,
   12659            1 :             &cancel,
   12660            1 :             &ctx,
   12661              :         )
   12662            1 :         .instrument(info_span!(
   12663              :             "gather_inputs",
   12664              :             tenant_id = "unknown",
   12665              :             shard_id = "unknown",
   12666              :         ))
   12667            1 :         .await?;
   12668              :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12669              :         use LsnKind::*;
   12670              :         use tenant_size_model::Segment;
   12671            1 :         let ModelInputs { mut segments, .. } = inputs;
   12672           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12673            6 :         for segment in segments.iter_mut() {
   12674            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12675            6 :             segment.segment.size = None; // We don't care about the size for the test
   12676            6 :         }
   12677            1 :         assert_eq!(
   12678              :             segments,
   12679              :             [
   12680              :                 SegmentMeta {
   12681              :                     segment: Segment {
   12682              :                         parent: None,
   12683              :                         lsn: 0x10,
   12684              :                         size: None,
   12685              :                         needed: false,
   12686              :                     },
   12687              :                     timeline_id: TIMELINE_ID,
   12688              :                     kind: BranchStart,
   12689              :                 },
   12690              :                 SegmentMeta {
   12691              :                     segment: Segment {
   12692              :                         parent: None,
   12693              :                         lsn: 0x20,
   12694              :                         size: None,
   12695              :                         needed: false,
   12696              :                     },
   12697              :                     timeline_id: TIMELINE_ID,
   12698              :                     kind: BranchPoint,
   12699              :                 },
   12700              :                 SegmentMeta {
   12701              :                     segment: Segment {
   12702              :                         parent: None,
   12703              :                         lsn: 0x30,
   12704              :                         size: None,
   12705              :                         needed: false,
   12706              :                     },
   12707              :                     timeline_id: TIMELINE_ID,
   12708              :                     kind: BranchPoint,
   12709              :                 },
   12710              :                 SegmentMeta {
   12711              :                     segment: Segment {
   12712              :                         parent: None,
   12713              :                         lsn: 0x40,
   12714              :                         size: None,
   12715              :                         needed: false,
   12716              :                     },
   12717              :                     timeline_id: TIMELINE_ID,
   12718              :                     kind: BranchPoint,
   12719              :                 },
   12720              :                 SegmentMeta {
   12721              :                     segment: Segment {
   12722              :                         parent: None,
   12723              :                         lsn: 0x100,
   12724              :                         size: None,
   12725              :                         needed: false,
   12726              :                     },
   12727              :                     timeline_id: TIMELINE_ID,
   12728              :                     kind: GcCutOff,
   12729              :                 }, // we need to retain everything above the last branch point
   12730              :                 SegmentMeta {
   12731              :                     segment: Segment {
   12732              :                         parent: None,
   12733              :                         lsn: 0x100,
   12734              :                         size: None,
   12735              :                         needed: true,
   12736              :                     },
   12737              :                     timeline_id: TIMELINE_ID,
   12738              :                     kind: BranchEnd,
   12739              :                 },
   12740              :             ]
   12741              :         );
   12742              : 
   12743            1 :         main_tline
   12744            1 :             .remote_client
   12745            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12746            1 :                 TimelineVisibilityState::Invisible,
   12747            0 :             )?;
   12748            1 :         main_tline.remote_client.wait_completion().await?;
   12749            1 :         let inputs = gather_inputs(
   12750            1 :             &tenant,
   12751            1 :             &limit,
   12752            1 :             max_retention_period,
   12753            1 :             &mut logical_size_cache,
   12754            1 :             cause,
   12755            1 :             &cancel,
   12756            1 :             &ctx,
   12757              :         )
   12758            1 :         .instrument(info_span!(
   12759              :             "gather_inputs",
   12760              :             tenant_id = "unknown",
   12761              :             shard_id = "unknown",
   12762              :         ))
   12763            1 :         .await?;
   12764            1 :         let ModelInputs { mut segments, .. } = inputs;
   12765           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12766            5 :         for segment in segments.iter_mut() {
   12767            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12768            5 :             segment.segment.size = None; // We don't care about the size for the test
   12769            5 :         }
   12770            1 :         assert_eq!(
   12771              :             segments,
   12772              :             [
   12773              :                 SegmentMeta {
   12774              :                     segment: Segment {
   12775              :                         parent: None,
   12776              :                         lsn: 0x10,
   12777              :                         size: None,
   12778              :                         needed: false,
   12779              :                     },
   12780              :                     timeline_id: TIMELINE_ID,
   12781              :                     kind: BranchStart,
   12782              :                 },
   12783              :                 SegmentMeta {
   12784              :                     segment: Segment {
   12785              :                         parent: None,
   12786              :                         lsn: 0x20,
   12787              :                         size: None,
   12788              :                         needed: false,
   12789              :                     },
   12790              :                     timeline_id: TIMELINE_ID,
   12791              :                     kind: BranchPoint,
   12792              :                 },
   12793              :                 SegmentMeta {
   12794              :                     segment: Segment {
   12795              :                         parent: None,
   12796              :                         lsn: 0x30,
   12797              :                         size: None,
   12798              :                         needed: false,
   12799              :                     },
   12800              :                     timeline_id: TIMELINE_ID,
   12801              :                     kind: BranchPoint,
   12802              :                 },
   12803              :                 SegmentMeta {
   12804              :                     segment: Segment {
   12805              :                         parent: None,
   12806              :                         lsn: 0x40,
   12807              :                         size: None,
   12808              :                         needed: false,
   12809              :                     },
   12810              :                     timeline_id: TIMELINE_ID,
   12811              :                     kind: BranchPoint,
   12812              :                 },
   12813              :                 SegmentMeta {
   12814              :                     segment: Segment {
   12815              :                         parent: None,
   12816              :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12817              :                         size: None,
   12818              :                         needed: true,
   12819              :                     },
   12820              :                     timeline_id: TIMELINE_ID,
   12821              :                     kind: BranchEnd,
   12822              :                 },
   12823              :             ]
   12824              :         );
   12825              : 
   12826            2 :         Ok(())
   12827            1 :     }
   12828              : 
   12829              :     #[tokio::test]
   12830            1 :     async fn test_get_force_image_creation_lsn() -> anyhow::Result<()> {
   12831            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12832            1 :             pitr_interval: Some(Duration::from_secs(7 * 3600)),
   12833            1 :             image_layer_force_creation_period: Some(Duration::from_secs(3600)),
   12834            1 :             ..Default::default()
   12835            1 :         };
   12836              : 
   12837            1 :         let tenant_id = TenantId::generate();
   12838              : 
   12839            1 :         let harness = TenantHarness::create_custom(
   12840            1 :             "test_get_force_image_creation_lsn",
   12841            1 :             tenant_conf,
   12842            1 :             tenant_id,
   12843            1 :             ShardIdentity::unsharded(),
   12844            1 :             Generation::new(1),
   12845            1 :         )
   12846            1 :         .await?;
   12847            1 :         let (tenant, ctx) = harness.load().await;
   12848            1 :         let timeline = tenant
   12849            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   12850            1 :             .await?;
   12851            1 :         timeline.gc_info.write().unwrap().cutoffs.time = Some(Lsn(100));
   12852              :         {
   12853            1 :             let writer = timeline.writer().await;
   12854            1 :             writer.finish_write(Lsn(5000));
   12855              :         }
   12856              : 
   12857            1 :         let image_creation_lsn = timeline.get_force_image_creation_lsn().unwrap();
   12858            1 :         assert_eq!(image_creation_lsn, Lsn(4300));
   12859            2 :         Ok(())
   12860            1 :     }
   12861              : }
        

Generated by: LCOV version 2.1-beta