LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: c8f8d331b83562868d9054d9e0e68f866772aeaa.info Lines: 77.8 % 8510 6623
Test Date: 2025-07-26 17:20:05 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        26649 :     pub async fn request_redo(
     501        26649 :         &self,
     502        26649 :         key: pageserver_api::key::Key,
     503        26649 :         lsn: Lsn,
     504        26649 :         base_img: Option<(Lsn, bytes::Bytes)>,
     505        26649 :         records: Vec<(Lsn, wal_decoder::models::record::NeonWalRecord)>,
     506        26649 :         pg_version: PgMajorVersion,
     507        26649 :         redo_attempt_type: RedoAttemptType,
     508        26649 :     ) -> Result<bytes::Bytes, walredo::Error> {
     509        26649 :         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        26649 :             Self::Test(mgr) => {
     516        26649 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     517        26649 :                     .await
     518              :             }
     519              :         }
     520        26649 :     }
     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 :             index_part.rel_size_migrated_at,
    1209            3 :             ctx,
    1210            3 :         )?;
    1211            3 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1212              : 
    1213            3 :         if !disk_consistent_lsn.is_valid() {
    1214              :             // As opposed to normal timelines which get initialised with a disk consitent LSN
    1215              :             // via initdb, imported timelines start from 0. If the import task stops before
    1216              :             // it advances disk consitent LSN, allow it to resume.
    1217            0 :             let in_progress_import = import_pgdata
    1218            0 :                 .as_ref()
    1219            0 :                 .map(|import| !import.is_done())
    1220            0 :                 .unwrap_or(false);
    1221            0 :             if !in_progress_import {
    1222            0 :                 anyhow::bail!("Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn");
    1223            0 :             }
    1224            3 :         }
    1225              : 
    1226            3 :         assert_eq!(
    1227              :             disk_consistent_lsn,
    1228            3 :             metadata.disk_consistent_lsn(),
    1229            0 :             "these are used interchangeably"
    1230              :         );
    1231              : 
    1232            3 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1233              : 
    1234            3 :         timeline
    1235            3 :             .load_layer_map(disk_consistent_lsn, index_part)
    1236            3 :             .await
    1237            3 :             .with_context(|| {
    1238            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1239            0 :             })?;
    1240              : 
    1241              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1242              :         // to the archival operation. To allow warming this timeline up, generate
    1243              :         // a previous heatmap which contains all visible layers in the layer map.
    1244              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1245              :         // for the timeline.
    1246            3 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1247            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1248            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1249            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1250              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1251              :                 // If the current branch point greater than the previous one use the the heatmap
    1252              :                 // we just generated - it should include more layers.
    1253            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1254            0 :                     tline
    1255            0 :                         .previous_heatmap
    1256            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1257            0 :                 } else {
    1258            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1259              :                 }
    1260              : 
    1261            0 :                 match tline.ancestor_timeline() {
    1262            0 :                     Some(ancestor) => {
    1263            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1264              :                             // Ancestor timeline is shutting down.
    1265            0 :                             break;
    1266            0 :                         }
    1267              : 
    1268            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1269              :                     }
    1270            0 :                     None => {
    1271            0 :                         tline_ending_at = None;
    1272            0 :                     }
    1273              :                 }
    1274              :             }
    1275            3 :         }
    1276              : 
    1277            0 :         match import_pgdata {
    1278            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1279            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1280            0 :                 if !guard.insert(timeline_id) {
    1281              :                     // We should never try and load the same timeline twice during startup
    1282            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1283            0 :                 }
    1284            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1285            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1286            0 :                     owning_tenant: self.clone(),
    1287            0 :                     timeline_id,
    1288            0 :                     idempotency,
    1289              :                     // The users of this specific return value don't need the timline_path in there.
    1290            0 :                     timeline_path: timeline
    1291            0 :                         .conf
    1292            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1293              :                 };
    1294            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1295            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1296            0 :                         timeline,
    1297            0 :                         import_pgdata,
    1298            0 :                         guard: timeline_create_guard,
    1299            0 :                     },
    1300            0 :                 ))
    1301              :             }
    1302              :             Some(_) | None => {
    1303              :                 {
    1304            3 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1305            3 :                     match timelines_accessor.entry(timeline_id) {
    1306              :                         // We should never try and load the same timeline twice during startup
    1307              :                         Entry::Occupied(_) => {
    1308            0 :                             unreachable!(
    1309              :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1310              :                             );
    1311              :                         }
    1312            3 :                         Entry::Vacant(v) => {
    1313            3 :                             v.insert(Arc::clone(&timeline));
    1314            3 :                             timeline.maybe_spawn_flush_loop();
    1315            3 :                         }
    1316              :                     }
    1317              :                 }
    1318              : 
    1319            3 :                 if disk_consistent_lsn.is_valid() {
    1320              :                     // Sanity check: a timeline should have some content.
    1321              :                     // Exception: importing timelines might not yet have any
    1322            3 :                     anyhow::ensure!(
    1323            3 :                         ancestor.is_some()
    1324            2 :                             || timeline
    1325            2 :                                 .layers
    1326            2 :                                 .read(LayerManagerLockHolder::LoadLayerMap)
    1327            2 :                                 .await
    1328            2 :                                 .layer_map()
    1329            2 :                                 .expect(
    1330            2 :                                     "currently loading, layer manager cannot be shutdown already"
    1331              :                                 )
    1332            2 :                                 .iter_historic_layers()
    1333            2 :                                 .next()
    1334            2 :                                 .is_some(),
    1335            0 :                         "Timeline has no ancestor and no layer files"
    1336              :                     );
    1337            0 :                 }
    1338              : 
    1339            3 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate)
    1340              :             }
    1341              :         }
    1342            3 :     }
    1343              : 
    1344              :     /// Attach a tenant that's available in cloud storage.
    1345              :     ///
    1346              :     /// This returns quickly, after just creating the in-memory object
    1347              :     /// Tenant struct and launching a background task to download
    1348              :     /// the remote index files.  On return, the tenant is most likely still in
    1349              :     /// Attaching state, and it will become Active once the background task
    1350              :     /// finishes. You can use wait_until_active() to wait for the task to
    1351              :     /// complete.
    1352              :     ///
    1353              :     #[allow(clippy::too_many_arguments)]
    1354            0 :     pub(crate) fn spawn(
    1355            0 :         conf: &'static PageServerConf,
    1356            0 :         tenant_shard_id: TenantShardId,
    1357            0 :         resources: TenantSharedResources,
    1358            0 :         attached_conf: AttachedTenantConf,
    1359            0 :         shard_identity: ShardIdentity,
    1360            0 :         init_order: Option<InitializationOrder>,
    1361            0 :         mode: SpawnMode,
    1362            0 :         ctx: &RequestContext,
    1363            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1364            0 :         let wal_redo_manager =
    1365            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1366              : 
    1367              :         let TenantSharedResources {
    1368            0 :             broker_client,
    1369            0 :             remote_storage,
    1370            0 :             deletion_queue_client,
    1371            0 :             l0_flush_global_state,
    1372            0 :             basebackup_cache,
    1373            0 :             feature_resolver,
    1374            0 :         } = resources;
    1375              : 
    1376            0 :         let attach_mode = attached_conf.location.attach_mode;
    1377            0 :         let generation = attached_conf.location.generation;
    1378              : 
    1379            0 :         let tenant = Arc::new(TenantShard::new(
    1380            0 :             TenantState::Attaching,
    1381            0 :             conf,
    1382            0 :             attached_conf,
    1383            0 :             shard_identity,
    1384            0 :             Some(wal_redo_manager),
    1385            0 :             tenant_shard_id,
    1386            0 :             remote_storage.clone(),
    1387            0 :             deletion_queue_client,
    1388            0 :             l0_flush_global_state,
    1389            0 :             basebackup_cache,
    1390            0 :             feature_resolver,
    1391              :         ));
    1392              : 
    1393              :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1394              :         // we shut down while attaching.
    1395            0 :         let attach_gate_guard = tenant
    1396            0 :             .gate
    1397            0 :             .enter()
    1398            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1399              : 
    1400              :         // Do all the hard work in the background
    1401            0 :         let tenant_clone = Arc::clone(&tenant);
    1402            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1403            0 :         task_mgr::spawn(
    1404            0 :             &tokio::runtime::Handle::current(),
    1405            0 :             TaskKind::Attach,
    1406            0 :             tenant_shard_id,
    1407            0 :             None,
    1408            0 :             "attach tenant",
    1409            0 :             async move {
    1410              : 
    1411            0 :                 info!(
    1412              :                     ?attach_mode,
    1413            0 :                     "Attaching tenant"
    1414              :                 );
    1415              : 
    1416            0 :                 let _gate_guard = attach_gate_guard;
    1417              : 
    1418              :                 // Is this tenant being spawned as part of process startup?
    1419            0 :                 let starting_up = init_order.is_some();
    1420            0 :                 scopeguard::defer! {
    1421              :                     if starting_up {
    1422              :                         TENANT.startup_complete.inc();
    1423              :                     }
    1424              :                 }
    1425              : 
    1426            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1427            0 :                     t.state.send_modify(|state| match state {
    1428              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1429              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1430              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1431              :                         // logs don't show this happening in production, remove the Stopping cases.
    1432            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1433            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1434              :                         }
    1435              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1436            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1437            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1438              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1439            0 :                             *state = TenantState::Stopping { progress: None };
    1440              :                         }
    1441              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1442              :                         // Stopping. Retain its progress.
    1443              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1444            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1445            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1446            0 :                             info!("attach cancelled, already Stopping: {err}");
    1447              :                         }
    1448              :                         // Mark the tenant as broken.
    1449              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1450            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1451            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1452              :                         }
    1453              :                         // The attach task owns the tenant state until activated.
    1454            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1455            0 :                     });
    1456            0 :                 }
    1457              : 
    1458              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1459            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1460            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1461            0 :                     return Ok(());
    1462            0 :                 }
    1463              : 
    1464            0 :                 let mut init_order = init_order;
    1465              :                 // take the completion because initial tenant loading will complete when all of
    1466              :                 // these tasks complete.
    1467            0 :                 let _completion = init_order
    1468            0 :                     .as_mut()
    1469            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1470            0 :                 let remote_load_completion = init_order
    1471            0 :                     .as_mut()
    1472            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1473              : 
    1474              :                 enum AttachType<'a> {
    1475              :                     /// We are attaching this tenant lazily in the background.
    1476              :                     Warmup {
    1477              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1478              :                         during_startup: bool
    1479              :                     },
    1480              :                     /// We are attaching this tenant as soon as we can, because for example an
    1481              :                     /// endpoint tried to access it.
    1482              :                     OnDemand,
    1483              :                     /// During normal operations after startup, we are attaching a tenant, and
    1484              :                     /// eager attach was requested.
    1485              :                     Normal,
    1486              :                 }
    1487              : 
    1488            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1489              :                     // Before doing any I/O, wait for at least one of:
    1490              :                     // - A client attempting to access to this tenant (on-demand loading)
    1491              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1492              : 
    1493            0 :                     tokio::select!(
    1494            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1495            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1496            0 :                             tracing::info!("Activating tenant (on-demand)");
    1497            0 :                             AttachType::OnDemand
    1498              :                         },
    1499            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1500            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1501            0 :                             tracing::info!("Activating tenant (warmup)");
    1502            0 :                             AttachType::Warmup {
    1503            0 :                                 _permit,
    1504            0 :                                 during_startup: init_order.is_some()
    1505            0 :                             }
    1506              :                         }
    1507            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1508              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1509              :                             // stayed in Activating for such a long time that shutdown found it in
    1510              :                             // that state.
    1511            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1512              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1513            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1514            0 :                             return Ok(());
    1515              :                         },
    1516              :                     )
    1517              :                 } else {
    1518              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1519              :                     // concurrent_tenant_warmup queue
    1520            0 :                     AttachType::Normal
    1521              :                 };
    1522              : 
    1523            0 :                 let preload = match &mode {
    1524              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1525            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1526            0 :                         let res = tenant_clone
    1527            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1528            0 :                             .await;
    1529            0 :                         match res {
    1530            0 :                             Ok(p) => Some(p),
    1531            0 :                             Err(e) => {
    1532            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1533            0 :                                 return Ok(());
    1534              :                             }
    1535              :                         }
    1536              :                     }
    1537              : 
    1538              :                 };
    1539              : 
    1540              :                 // Remote preload is complete.
    1541            0 :                 drop(remote_load_completion);
    1542              : 
    1543              : 
    1544              :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1545            0 :                 let attach_start = std::time::Instant::now();
    1546            0 :                 let attached = {
    1547            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1548            0 :                     tenant_clone.attach(preload, &ctx).await
    1549              :                 };
    1550            0 :                 let attach_duration = attach_start.elapsed();
    1551            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1552              : 
    1553            0 :                 match attached {
    1554              :                     Ok(()) => {
    1555            0 :                         info!("attach finished, activating");
    1556            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1557              :                     }
    1558            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1559              :                 }
    1560              : 
    1561              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1562              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1563              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1564              :                 //
    1565              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1566              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1567              :                 // then warmup will wait for that before proceeding to the next tenant.
    1568            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1569            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1570            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1571            0 :                     while futs.next().await.is_some() {}
    1572            0 :                     tracing::info!("Warm-up complete");
    1573            0 :                 }
    1574              : 
    1575            0 :                 Ok(())
    1576            0 :             }
    1577            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1578              :         );
    1579            0 :         Ok(tenant)
    1580            0 :     }
    1581              : 
    1582              :     #[instrument(skip_all)]
    1583              :     pub(crate) async fn preload(
    1584              :         self: &Arc<Self>,
    1585              :         remote_storage: &GenericRemoteStorage,
    1586              :         cancel: CancellationToken,
    1587              :     ) -> anyhow::Result<TenantPreload> {
    1588              :         span::debug_assert_current_span_has_tenant_id();
    1589              :         // Get list of remote timelines
    1590              :         // download index files for every tenant timeline
    1591              :         info!("listing remote timelines");
    1592              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1593              :             remote_storage,
    1594              :             self.tenant_shard_id,
    1595              :             cancel.clone(),
    1596              :         )
    1597              :         .await?;
    1598              : 
    1599              :         let tenant_manifest = match download_tenant_manifest(
    1600              :             remote_storage,
    1601              :             &self.tenant_shard_id,
    1602              :             self.generation,
    1603              :             &cancel,
    1604              :         )
    1605              :         .await
    1606              :         {
    1607              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1608              :             Err(DownloadError::NotFound) => None,
    1609              :             Err(err) => return Err(err.into()),
    1610              :         };
    1611              : 
    1612              :         info!(
    1613              :             "found {} timelines ({} offloaded timelines)",
    1614              :             remote_timeline_ids.len(),
    1615              :             tenant_manifest
    1616              :                 .as_ref()
    1617            3 :                 .map(|m| m.offloaded_timelines.len())
    1618              :                 .unwrap_or(0)
    1619              :         );
    1620              : 
    1621              :         for k in other_keys {
    1622              :             warn!("Unexpected non timeline key {k}");
    1623              :         }
    1624              : 
    1625              :         // Avoid downloading IndexPart of offloaded timelines.
    1626              :         let mut offloaded_with_prefix = HashSet::new();
    1627              :         if let Some(tenant_manifest) = &tenant_manifest {
    1628              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1629              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1630              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1631              :                 } else {
    1632              :                     // We'll take care later of timelines in the manifest without a prefix
    1633              :                 }
    1634              :             }
    1635              :         }
    1636              : 
    1637              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1638              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1639              :         // will kick the secondary in any case and cause a download.
    1640              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1641              : 
    1642              :         let timelines = self
    1643              :             .load_timelines_metadata(
    1644              :                 remote_timeline_ids,
    1645              :                 remote_storage,
    1646              :                 maybe_heatmap_at,
    1647              :                 cancel,
    1648              :             )
    1649              :             .await?;
    1650              : 
    1651              :         Ok(TenantPreload {
    1652              :             tenant_manifest,
    1653              :             timelines: timelines
    1654              :                 .into_iter()
    1655            3 :                 .map(|(id, tl)| (id, Some(tl)))
    1656            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1657              :                 .collect(),
    1658              :         })
    1659              :     }
    1660              : 
    1661          119 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1662          119 :         if !self.conf.load_previous_heatmap {
    1663            0 :             return None;
    1664          119 :         }
    1665              : 
    1666          119 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1667          119 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1668            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1669            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1670            0 :                 Err(err) => {
    1671            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1672            0 :                     None
    1673              :                 }
    1674              :             },
    1675          119 :             Err(err) => match err.kind() {
    1676          119 :                 std::io::ErrorKind::NotFound => None,
    1677              :                 _ => {
    1678            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1679            0 :                     None
    1680              :                 }
    1681              :             },
    1682              :         }
    1683          119 :     }
    1684              : 
    1685              :     ///
    1686              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1687              :     ///
    1688              :     /// No background tasks are started as part of this routine.
    1689              :     ///
    1690          119 :     async fn attach(
    1691          119 :         self: &Arc<TenantShard>,
    1692          119 :         preload: Option<TenantPreload>,
    1693          119 :         ctx: &RequestContext,
    1694          119 :     ) -> anyhow::Result<()> {
    1695          119 :         span::debug_assert_current_span_has_tenant_id();
    1696              : 
    1697          119 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1698              : 
    1699          119 :         let Some(preload) = preload else {
    1700            0 :             anyhow::bail!(
    1701            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1702              :             );
    1703              :         };
    1704              : 
    1705          119 :         let mut offloaded_timeline_ids = HashSet::new();
    1706          119 :         let mut offloaded_timelines_list = Vec::new();
    1707          119 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1708            3 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1709            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1710            0 :                 let offloaded_timeline =
    1711            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1712            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1713            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1714            0 :             }
    1715          116 :         }
    1716              :         // Complete deletions for offloaded timeline id's from manifest.
    1717              :         // The manifest will be uploaded later in this function.
    1718          119 :         offloaded_timelines_list
    1719          119 :             .retain(|(offloaded_id, offloaded)| {
    1720              :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1721              :                 // If there is dangling references in another location, they need to be cleaned up.
    1722            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1723            0 :                 if delete {
    1724            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1725            0 :                     offloaded.defuse_for_tenant_drop();
    1726            0 :                 }
    1727            0 :                 !delete
    1728            0 :         });
    1729              : 
    1730          119 :         let mut timelines_to_resume_deletions = vec![];
    1731              : 
    1732          119 :         let mut remote_index_and_client = HashMap::new();
    1733          119 :         let mut timeline_ancestors = HashMap::new();
    1734          119 :         let mut existent_timelines = HashSet::new();
    1735          122 :         for (timeline_id, preload) in preload.timelines {
    1736            3 :             let Some(preload) = preload else { continue };
    1737              :             // This is an invariant of the `preload` function's API
    1738            3 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1739            3 :             let index_part = match preload.index_part {
    1740            3 :                 Ok(i) => {
    1741            3 :                     debug!("remote index part exists for timeline {timeline_id}");
    1742              :                     // We found index_part on the remote, this is the standard case.
    1743            3 :                     existent_timelines.insert(timeline_id);
    1744            3 :                     i
    1745              :                 }
    1746              :                 Err(DownloadError::NotFound) => {
    1747              :                     // There is no index_part on the remote. We only get here
    1748              :                     // if there is some prefix for the timeline in the remote storage.
    1749              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1750              :                     // remnant from a prior incomplete creation or deletion attempt.
    1751              :                     // Delete the local directory as the deciding criterion for a
    1752              :                     // timeline's existence is presence of index_part.
    1753            0 :                     info!(%timeline_id, "index_part not found on remote");
    1754            0 :                     continue;
    1755              :                 }
    1756            0 :                 Err(DownloadError::Fatal(why)) => {
    1757              :                     // If, while loading one remote timeline, we saw an indication that our generation
    1758              :                     // number is likely invalid, then we should not load the whole tenant.
    1759            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1760            0 :                     anyhow::bail!(why.to_string());
    1761              :                 }
    1762            0 :                 Err(e) => {
    1763              :                     // Some (possibly ephemeral) error happened during index_part download.
    1764              :                     // Pretend the timeline exists to not delete the timeline directory,
    1765              :                     // as it might be a temporary issue and we don't want to re-download
    1766              :                     // everything after it resolves.
    1767            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1768              : 
    1769            0 :                     existent_timelines.insert(timeline_id);
    1770            0 :                     continue;
    1771              :                 }
    1772              :             };
    1773            3 :             match index_part {
    1774            3 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1775            3 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1776            3 :                     remote_index_and_client.insert(
    1777            3 :                         timeline_id,
    1778            3 :                         (index_part, preload.client, preload.previous_heatmap),
    1779            3 :                     );
    1780            3 :                 }
    1781            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1782            0 :                     info!(
    1783            0 :                         "timeline {} is deleted, picking to resume deletion",
    1784              :                         timeline_id
    1785              :                     );
    1786            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1787              :                 }
    1788              :             }
    1789              :         }
    1790              : 
    1791          119 :         let mut gc_blocks = HashMap::new();
    1792              : 
    1793              :         // For every timeline, download the metadata file, scan the local directory,
    1794              :         // and build a layer map that contains an entry for each remote and local
    1795              :         // layer file.
    1796          119 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1797          122 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1798            3 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1799            3 :                 .remove(&timeline_id)
    1800            3 :                 .expect("just put it in above");
    1801              : 
    1802            3 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1803              :                 // could just filter these away, but it helps while testing
    1804            0 :                 anyhow::ensure!(
    1805            0 :                     !blocking.reasons.is_empty(),
    1806            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1807              :                 );
    1808            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1809            0 :                 assert!(prev.is_none());
    1810            3 :             }
    1811              : 
    1812              :             // TODO again handle early failure
    1813            3 :             let effect = self
    1814            3 :                 .load_remote_timeline(
    1815            3 :                     timeline_id,
    1816            3 :                     index_part,
    1817            3 :                     remote_metadata,
    1818            3 :                     previous_heatmap,
    1819            3 :                     self.get_timeline_resources_for(remote_client),
    1820            3 :                     LoadTimelineCause::Attach,
    1821            3 :                     ctx,
    1822            3 :                 )
    1823            3 :                 .await
    1824            3 :                 .with_context(|| {
    1825            0 :                     format!(
    1826            0 :                         "failed to load remote timeline {} for tenant {}",
    1827            0 :                         timeline_id, self.tenant_shard_id
    1828              :                     )
    1829            0 :                 })?;
    1830              : 
    1831            3 :             match effect {
    1832            3 :                 TimelineInitAndSyncResult::ReadyToActivate => {
    1833            3 :                     // activation happens later, on Tenant::activate
    1834            3 :                 }
    1835              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1836              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1837            0 :                         timeline,
    1838            0 :                         import_pgdata,
    1839            0 :                         guard,
    1840              :                     },
    1841              :                 ) => {
    1842            0 :                     let timeline_id = timeline.timeline_id;
    1843            0 :                     let import_task_gate = Gate::default();
    1844            0 :                     let import_task_guard = import_task_gate.enter().unwrap();
    1845            0 :                     let import_task_handle =
    1846            0 :                         tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1847            0 :                             timeline.clone(),
    1848            0 :                             import_pgdata,
    1849            0 :                             guard,
    1850            0 :                             import_task_guard,
    1851            0 :                             ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1852              :                         ));
    1853              : 
    1854            0 :                     let prev = self.timelines_importing.lock().unwrap().insert(
    1855            0 :                         timeline_id,
    1856            0 :                         Arc::new(ImportingTimeline {
    1857            0 :                             timeline: timeline.clone(),
    1858            0 :                             import_task_handle,
    1859            0 :                             import_task_gate,
    1860            0 :                             delete_progress: TimelineDeleteProgress::default(),
    1861            0 :                         }),
    1862            0 :                     );
    1863              : 
    1864            0 :                     assert!(prev.is_none());
    1865              :                 }
    1866              :             }
    1867              :         }
    1868              : 
    1869              :         // At this point we've initialized all timelines and are tracking them.
    1870              :         // Now compute the layer visibility for all (not offloaded) timelines.
    1871          119 :         let compute_visiblity_for = {
    1872          119 :             let timelines_accessor = self.timelines.lock().unwrap();
    1873          119 :             let mut timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    1874              : 
    1875          119 :             timelines_offloaded_accessor.extend(offloaded_timelines_list.into_iter());
    1876              : 
    1877              :             // Before activation, populate each Timeline's GcInfo with information about its children
    1878          119 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    1879              : 
    1880          119 :             timelines_accessor.values().cloned().collect::<Vec<_>>()
    1881              :         };
    1882              : 
    1883          122 :         for tl in compute_visiblity_for {
    1884            3 :             tl.update_layer_visibility().await.with_context(|| {
    1885            0 :                 format!(
    1886            0 :                     "failed initial timeline visibility computation {} for tenant {}",
    1887            0 :                     tl.timeline_id, self.tenant_shard_id
    1888              :                 )
    1889            0 :             })?;
    1890              :         }
    1891              : 
    1892              :         // Walk through deleted timelines, resume deletion
    1893          119 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1894            0 :             remote_timeline_client
    1895            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1896            0 :                 .context("init queue stopped")
    1897            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1898              : 
    1899            0 :             DeleteTimelineFlow::resume_deletion(
    1900            0 :                 Arc::clone(self),
    1901            0 :                 timeline_id,
    1902            0 :                 &index_part.metadata,
    1903            0 :                 remote_timeline_client,
    1904            0 :                 ctx,
    1905              :             )
    1906            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1907            0 :             .await
    1908            0 :             .context("resume_deletion")
    1909            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1910              :         }
    1911              : 
    1912              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1913              :         //
    1914              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1915              :         // offloaded timelines, which are included in the manifest.
    1916              :         {
    1917          119 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1918          119 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1919          119 :             *guard = preload.tenant_manifest;
    1920              :         }
    1921          119 :         self.maybe_upload_tenant_manifest().await?;
    1922              : 
    1923              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1924              :         // IndexPart is the source of truth.
    1925          119 :         self.clean_up_timelines(&existent_timelines)?;
    1926              : 
    1927          119 :         self.gc_block.set_scanned(gc_blocks);
    1928              : 
    1929          119 :         fail::fail_point!("attach-before-activate", |_| {
    1930            0 :             anyhow::bail!("attach-before-activate");
    1931            0 :         });
    1932          119 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1933              : 
    1934          119 :         info!("Done");
    1935              : 
    1936          119 :         Ok(())
    1937          119 :     }
    1938              : 
    1939              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1940              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1941              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1942          119 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1943          119 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1944              : 
    1945          119 :         let entries = match timelines_dir.read_dir_utf8() {
    1946          119 :             Ok(d) => d,
    1947            0 :             Err(e) => {
    1948            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1949            0 :                     return Ok(());
    1950              :                 } else {
    1951            0 :                     return Err(e).context("list timelines directory for tenant");
    1952              :                 }
    1953              :             }
    1954              :         };
    1955              : 
    1956          123 :         for entry in entries {
    1957            4 :             let entry = entry.context("read timeline dir entry")?;
    1958            4 :             let entry_path = entry.path();
    1959              : 
    1960            4 :             let purge = if crate::is_temporary(entry_path) {
    1961            0 :                 true
    1962              :             } else {
    1963            4 :                 match TimelineId::try_from(entry_path.file_name()) {
    1964            4 :                     Ok(i) => {
    1965              :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1966            4 :                         !existent_timelines.contains(&i)
    1967              :                     }
    1968            0 :                     Err(e) => {
    1969            0 :                         tracing::warn!(
    1970            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1971              :                         );
    1972              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1973            0 :                         false
    1974              :                     }
    1975              :                 }
    1976              :             };
    1977              : 
    1978            4 :             if purge {
    1979            1 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1980            1 :                 if let Err(e) = match entry.file_type() {
    1981            1 :                     Ok(t) => if t.is_dir() {
    1982            1 :                         std::fs::remove_dir_all(entry_path)
    1983              :                     } else {
    1984            0 :                         std::fs::remove_file(entry_path)
    1985              :                     }
    1986            1 :                     .or_else(fs_ext::ignore_not_found),
    1987            0 :                     Err(e) => Err(e),
    1988              :                 } {
    1989            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1990            1 :                 }
    1991            3 :             }
    1992              :         }
    1993              : 
    1994          119 :         Ok(())
    1995          119 :     }
    1996              : 
    1997              :     /// Get sum of all remote timelines sizes
    1998              :     ///
    1999              :     /// This function relies on the index_part instead of listing the remote storage
    2000            0 :     pub fn remote_size(&self) -> u64 {
    2001            0 :         let mut size = 0;
    2002              : 
    2003            0 :         for timeline in self.list_timelines() {
    2004            0 :             size += timeline.remote_client.get_remote_physical_size();
    2005            0 :         }
    2006              : 
    2007            0 :         size
    2008            0 :     }
    2009              : 
    2010              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    2011              :     #[allow(clippy::too_many_arguments)]
    2012              :     async fn load_remote_timeline(
    2013              :         self: &Arc<Self>,
    2014              :         timeline_id: TimelineId,
    2015              :         index_part: IndexPart,
    2016              :         remote_metadata: TimelineMetadata,
    2017              :         previous_heatmap: Option<PreviousHeatmap>,
    2018              :         resources: TimelineResources,
    2019              :         cause: LoadTimelineCause,
    2020              :         ctx: &RequestContext,
    2021              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    2022              :         span::debug_assert_current_span_has_tenant_id();
    2023              : 
    2024              :         info!("downloading index file for timeline {}", timeline_id);
    2025              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    2026              :             .await
    2027              :             .context("Failed to create new timeline directory")?;
    2028              : 
    2029              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    2030              :             let timelines = self.timelines.lock().unwrap();
    2031              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    2032            0 :                 || {
    2033            0 :                     anyhow::anyhow!(
    2034            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    2035              :                     )
    2036            0 :                 },
    2037              :             )?))
    2038              :         } else {
    2039              :             None
    2040              :         };
    2041              : 
    2042              :         self.timeline_init_and_sync(
    2043              :             timeline_id,
    2044              :             resources,
    2045              :             index_part,
    2046              :             remote_metadata,
    2047              :             previous_heatmap,
    2048              :             ancestor,
    2049              :             cause,
    2050              :             ctx,
    2051              :         )
    2052              :         .await
    2053              :     }
    2054              : 
    2055          119 :     async fn load_timelines_metadata(
    2056          119 :         self: &Arc<TenantShard>,
    2057          119 :         timeline_ids: HashSet<TimelineId>,
    2058          119 :         remote_storage: &GenericRemoteStorage,
    2059          119 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    2060          119 :         cancel: CancellationToken,
    2061          119 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    2062          119 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    2063              : 
    2064          119 :         let mut part_downloads = JoinSet::new();
    2065          122 :         for timeline_id in timeline_ids {
    2066            3 :             let cancel_clone = cancel.clone();
    2067              : 
    2068            3 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    2069            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    2070            0 :                     heatmap: h,
    2071            0 :                     read_at: hs.1,
    2072            0 :                     end_lsn: None,
    2073            0 :                 })
    2074            0 :             });
    2075            3 :             part_downloads.spawn(
    2076            3 :                 self.load_timeline_metadata(
    2077            3 :                     timeline_id,
    2078            3 :                     remote_storage.clone(),
    2079            3 :                     previous_timeline_heatmap,
    2080            3 :                     cancel_clone,
    2081              :                 )
    2082            3 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    2083              :             );
    2084              :         }
    2085              : 
    2086          119 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    2087              : 
    2088              :         loop {
    2089          122 :             tokio::select!(
    2090          122 :                 next = part_downloads.join_next() => {
    2091          122 :                     match next {
    2092            3 :                         Some(result) => {
    2093            3 :                             let preload = result.context("join preload task")?;
    2094            3 :                             timeline_preloads.insert(preload.timeline_id, preload);
    2095              :                         },
    2096              :                         None => {
    2097          119 :                             break;
    2098              :                         }
    2099              :                     }
    2100              :                 },
    2101          122 :                 _ = cancel.cancelled() => {
    2102            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2103              :                 }
    2104              :             )
    2105              :         }
    2106              : 
    2107          119 :         Ok(timeline_preloads)
    2108          119 :     }
    2109              : 
    2110            3 :     fn build_timeline_client(
    2111            3 :         &self,
    2112            3 :         timeline_id: TimelineId,
    2113            3 :         remote_storage: GenericRemoteStorage,
    2114            3 :     ) -> RemoteTimelineClient {
    2115            3 :         RemoteTimelineClient::new(
    2116            3 :             remote_storage.clone(),
    2117            3 :             self.deletion_queue_client.clone(),
    2118            3 :             self.conf,
    2119            3 :             self.tenant_shard_id,
    2120            3 :             timeline_id,
    2121            3 :             self.generation,
    2122            3 :             &self.tenant_conf.load().location,
    2123              :         )
    2124            3 :     }
    2125              : 
    2126            3 :     fn load_timeline_metadata(
    2127            3 :         self: &Arc<TenantShard>,
    2128            3 :         timeline_id: TimelineId,
    2129            3 :         remote_storage: GenericRemoteStorage,
    2130            3 :         previous_heatmap: Option<PreviousHeatmap>,
    2131            3 :         cancel: CancellationToken,
    2132            3 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2133            3 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2134            3 :         async move {
    2135            3 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2136            3 :             debug!("starting index part download");
    2137              : 
    2138            3 :             let index_part = client.download_index_file(&cancel).await;
    2139              : 
    2140            3 :             debug!("finished index part download");
    2141              : 
    2142            3 :             TimelinePreload {
    2143            3 :                 client,
    2144            3 :                 timeline_id,
    2145            3 :                 index_part,
    2146            3 :                 previous_heatmap,
    2147            3 :             }
    2148            3 :         }
    2149            3 :     }
    2150              : 
    2151            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2152            0 :         timeline_id: TimelineId,
    2153            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2154            0 :     ) -> Result<(), TimelineArchivalError> {
    2155            0 :         let children: Vec<TimelineId> = timelines
    2156            0 :             .iter()
    2157            0 :             .filter_map(|(id, entry)| {
    2158            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2159            0 :                     return None;
    2160            0 :                 }
    2161            0 :                 if entry.is_archived() == Some(true) {
    2162            0 :                     return None;
    2163            0 :                 }
    2164            0 :                 Some(*id)
    2165            0 :             })
    2166            0 :             .collect();
    2167              : 
    2168            0 :         if !children.is_empty() {
    2169            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2170            0 :         }
    2171            0 :         Ok(())
    2172            0 :     }
    2173              : 
    2174            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2175            0 :         ancestor_timeline_id: TimelineId,
    2176            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2177            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2178            0 :             '_,
    2179            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2180            0 :         >,
    2181            0 :     ) -> Result<(), TimelineArchivalError> {
    2182            0 :         let has_archived_parent =
    2183            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2184            0 :                 ancestor_timeline.is_archived() == Some(true)
    2185            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2186            0 :                 true
    2187              :             } else {
    2188            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2189            0 :                 if cfg!(debug_assertions) {
    2190            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2191            0 :                 }
    2192            0 :                 return Err(TimelineArchivalError::NotFound);
    2193              :             };
    2194            0 :         if has_archived_parent {
    2195            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2196            0 :                 ancestor_timeline_id,
    2197            0 :             ));
    2198            0 :         }
    2199            0 :         Ok(())
    2200            0 :     }
    2201              : 
    2202            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2203            0 :         timeline: &Arc<Timeline>,
    2204            0 :     ) -> Result<(), TimelineArchivalError> {
    2205            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2206            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2207            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2208            0 :                     ancestor_timeline.timeline_id,
    2209            0 :                 ));
    2210            0 :             }
    2211            0 :         }
    2212            0 :         Ok(())
    2213            0 :     }
    2214              : 
    2215              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2216              :     ///
    2217              :     /// Counterpart to [`offload_timeline`].
    2218            0 :     async fn unoffload_timeline(
    2219            0 :         self: &Arc<Self>,
    2220            0 :         timeline_id: TimelineId,
    2221            0 :         broker_client: storage_broker::BrokerClientChannel,
    2222            0 :         ctx: RequestContext,
    2223            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2224            0 :         info!("unoffloading timeline");
    2225              : 
    2226              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2227              :         // We expect callers of this function to ensure this.
    2228            0 :         match self.current_state() {
    2229              :             TenantState::Activating { .. }
    2230              :             | TenantState::Attaching
    2231              :             | TenantState::Broken { .. } => {
    2232            0 :                 panic!("Timeline expected to be active")
    2233              :             }
    2234            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2235            0 :             TenantState::Active => {}
    2236              :         }
    2237            0 :         let cancel = self.cancel.clone();
    2238              : 
    2239              :         // Protect against concurrent attempts to use this TimelineId
    2240              :         // We don't care much about idempotency, as it's ensured a layer above.
    2241            0 :         let allow_offloaded = true;
    2242            0 :         let _create_guard = self
    2243            0 :             .create_timeline_create_guard(
    2244            0 :                 timeline_id,
    2245            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2246            0 :                 allow_offloaded,
    2247              :             )
    2248            0 :             .map_err(|err| match err {
    2249            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2250              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2251            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2252              :                 }
    2253            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2254            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2255            0 :             })?;
    2256              : 
    2257            0 :         let timeline_preload = self
    2258            0 :             .load_timeline_metadata(
    2259            0 :                 timeline_id,
    2260            0 :                 self.remote_storage.clone(),
    2261            0 :                 None,
    2262            0 :                 cancel.clone(),
    2263            0 :             )
    2264            0 :             .await;
    2265              : 
    2266            0 :         let index_part = match timeline_preload.index_part {
    2267            0 :             Ok(index_part) => {
    2268            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2269            0 :                 index_part
    2270              :             }
    2271              :             Err(DownloadError::NotFound) => {
    2272            0 :                 error!(%timeline_id, "index_part not found on remote");
    2273            0 :                 return Err(TimelineArchivalError::NotFound);
    2274              :             }
    2275            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2276            0 :             Err(e) => {
    2277              :                 // Some (possibly ephemeral) error happened during index_part download.
    2278            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2279            0 :                 return Err(TimelineArchivalError::Other(
    2280            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2281            0 :                 ));
    2282              :             }
    2283              :         };
    2284            0 :         let index_part = match index_part {
    2285            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2286            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2287            0 :                 info!("timeline is deleted according to index_part.json");
    2288            0 :                 return Err(TimelineArchivalError::NotFound);
    2289              :             }
    2290              :         };
    2291            0 :         let remote_metadata = index_part.metadata.clone();
    2292            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2293            0 :         self.load_remote_timeline(
    2294            0 :             timeline_id,
    2295            0 :             index_part,
    2296            0 :             remote_metadata,
    2297            0 :             None,
    2298            0 :             timeline_resources,
    2299            0 :             LoadTimelineCause::Unoffload,
    2300            0 :             &ctx,
    2301            0 :         )
    2302            0 :         .await
    2303            0 :         .with_context(|| {
    2304            0 :             format!(
    2305            0 :                 "failed to load remote timeline {} for tenant {}",
    2306            0 :                 timeline_id, self.tenant_shard_id
    2307              :             )
    2308            0 :         })
    2309            0 :         .map_err(TimelineArchivalError::Other)?;
    2310              : 
    2311            0 :         let timeline = {
    2312            0 :             let timelines = self.timelines.lock().unwrap();
    2313            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2314            0 :                 warn!("timeline not available directly after attach");
    2315              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2316              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2317            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2318            0 :                     "timeline not available directly after attach"
    2319            0 :                 )));
    2320              :             };
    2321            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2322            0 :             match offloaded_timelines.remove(&timeline_id) {
    2323            0 :                 Some(offloaded) => {
    2324            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2325            0 :                 }
    2326            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2327              :             }
    2328              : 
    2329            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2330              : 
    2331            0 :             Arc::clone(timeline)
    2332              :         };
    2333              : 
    2334              :         // Upload new list of offloaded timelines to S3
    2335            0 :         self.maybe_upload_tenant_manifest().await?;
    2336              : 
    2337              :         // Activate the timeline (if it makes sense)
    2338            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2339            0 :             let background_jobs_can_start = None;
    2340            0 :             timeline.activate(
    2341            0 :                 self.clone(),
    2342            0 :                 broker_client.clone(),
    2343            0 :                 background_jobs_can_start,
    2344            0 :                 &ctx.with_scope_timeline(&timeline),
    2345            0 :             );
    2346            0 :         }
    2347              : 
    2348            0 :         info!("timeline unoffloading complete");
    2349            0 :         Ok(timeline)
    2350            0 :     }
    2351              : 
    2352            0 :     pub(crate) async fn apply_timeline_archival_config(
    2353            0 :         self: &Arc<Self>,
    2354            0 :         timeline_id: TimelineId,
    2355            0 :         new_state: TimelineArchivalState,
    2356            0 :         broker_client: storage_broker::BrokerClientChannel,
    2357            0 :         ctx: RequestContext,
    2358            0 :     ) -> Result<(), TimelineArchivalError> {
    2359            0 :         info!("setting timeline archival config");
    2360              :         // First part: figure out what is needed to do, and do validation
    2361            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2362            0 :             let timelines = self.timelines.lock().unwrap();
    2363              : 
    2364            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2365            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2366            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2367            0 :                     return Err(TimelineArchivalError::NotFound);
    2368              :                 };
    2369            0 :                 if new_state == TimelineArchivalState::Archived {
    2370              :                     // It's offloaded already, so nothing to do
    2371            0 :                     return Ok(());
    2372            0 :                 }
    2373            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2374            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2375            0 :                         ancestor_timeline_id,
    2376            0 :                         &timelines,
    2377            0 :                         &offloaded_timelines,
    2378            0 :                     )?;
    2379            0 :                 }
    2380            0 :                 break 'outer None;
    2381              :             };
    2382              : 
    2383              :             // Do some validation. We release the timelines lock below, so there is potential
    2384              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2385              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2386            0 :             match new_state {
    2387              :                 TimelineArchivalState::Unarchived => {
    2388            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2389              :                 }
    2390              :                 TimelineArchivalState::Archived => {
    2391            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2392              :                 }
    2393              :             }
    2394            0 :             Some(Arc::clone(timeline))
    2395              :         };
    2396              : 
    2397              :         // Second part: unoffload timeline (if needed)
    2398            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2399            0 :             timeline
    2400              :         } else {
    2401              :             // Turn offloaded timeline into a non-offloaded one
    2402            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2403            0 :                 .await?
    2404              :         };
    2405              : 
    2406              :         // Third part: upload new timeline archival state and block until it is present in S3
    2407            0 :         let upload_needed = match timeline
    2408            0 :             .remote_client
    2409            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2410              :         {
    2411            0 :             Ok(upload_needed) => upload_needed,
    2412            0 :             Err(e) => {
    2413            0 :                 if timeline.cancel.is_cancelled() {
    2414            0 :                     return Err(TimelineArchivalError::Cancelled);
    2415              :                 } else {
    2416            0 :                     return Err(TimelineArchivalError::Other(e));
    2417              :                 }
    2418              :             }
    2419              :         };
    2420              : 
    2421            0 :         if upload_needed {
    2422            0 :             info!("Uploading new state");
    2423              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2424            0 :             let Ok(v) =
    2425            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2426              :             else {
    2427            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2428            0 :                 return Err(TimelineArchivalError::Timeout);
    2429              :             };
    2430            0 :             v.map_err(|e| match e {
    2431            0 :                 WaitCompletionError::NotInitialized(e) => {
    2432            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2433              :                 }
    2434              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2435            0 :                     TimelineArchivalError::Cancelled
    2436              :                 }
    2437            0 :             })?;
    2438            0 :         }
    2439            0 :         Ok(())
    2440            0 :     }
    2441              : 
    2442            1 :     pub fn get_offloaded_timeline(
    2443            1 :         &self,
    2444            1 :         timeline_id: TimelineId,
    2445            1 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2446            1 :         self.timelines_offloaded
    2447            1 :             .lock()
    2448            1 :             .unwrap()
    2449            1 :             .get(&timeline_id)
    2450            1 :             .map(Arc::clone)
    2451            1 :             .ok_or(GetTimelineError::NotFound {
    2452            1 :                 tenant_id: self.tenant_shard_id,
    2453            1 :                 timeline_id,
    2454            1 :             })
    2455            1 :     }
    2456              : 
    2457            2 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2458            2 :         self.tenant_shard_id
    2459            2 :     }
    2460              : 
    2461              :     /// Get Timeline handle for given Neon timeline ID.
    2462              :     /// This function is idempotent. It doesn't change internal state in any way.
    2463          111 :     pub fn get_timeline(
    2464          111 :         &self,
    2465          111 :         timeline_id: TimelineId,
    2466          111 :         active_only: bool,
    2467          111 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2468          111 :         let timelines_accessor = self.timelines.lock().unwrap();
    2469          111 :         let timeline = timelines_accessor
    2470          111 :             .get(&timeline_id)
    2471          111 :             .ok_or(GetTimelineError::NotFound {
    2472          111 :                 tenant_id: self.tenant_shard_id,
    2473          111 :                 timeline_id,
    2474          111 :             })?;
    2475              : 
    2476          110 :         if active_only && !timeline.is_active() {
    2477            0 :             Err(GetTimelineError::NotActive {
    2478            0 :                 tenant_id: self.tenant_shard_id,
    2479            0 :                 timeline_id,
    2480            0 :                 state: timeline.current_state(),
    2481            0 :             })
    2482              :         } else {
    2483          110 :             Ok(Arc::clone(timeline))
    2484              :         }
    2485          111 :     }
    2486              : 
    2487              :     /// Lists timelines the tenant contains.
    2488              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2489            3 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2490            3 :         self.timelines
    2491            3 :             .lock()
    2492            3 :             .unwrap()
    2493            3 :             .values()
    2494            3 :             .map(Arc::clone)
    2495            3 :             .collect()
    2496            3 :     }
    2497              : 
    2498              :     /// Lists timelines the tenant contains.
    2499              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2500            0 :     pub fn list_importing_timelines(&self) -> Vec<Arc<ImportingTimeline>> {
    2501            0 :         self.timelines_importing
    2502            0 :             .lock()
    2503            0 :             .unwrap()
    2504            0 :             .values()
    2505            0 :             .map(Arc::clone)
    2506            0 :             .collect()
    2507            0 :     }
    2508              : 
    2509              :     /// Lists timelines the tenant manages, including offloaded ones.
    2510              :     ///
    2511              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2512            0 :     pub fn list_timelines_and_offloaded(
    2513            0 :         &self,
    2514            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2515            0 :         let timelines = self
    2516            0 :             .timelines
    2517            0 :             .lock()
    2518            0 :             .unwrap()
    2519            0 :             .values()
    2520            0 :             .map(Arc::clone)
    2521            0 :             .collect();
    2522            0 :         let offloaded = self
    2523            0 :             .timelines_offloaded
    2524            0 :             .lock()
    2525            0 :             .unwrap()
    2526            0 :             .values()
    2527            0 :             .map(Arc::clone)
    2528            0 :             .collect();
    2529            0 :         (timelines, offloaded)
    2530            0 :     }
    2531              : 
    2532            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2533            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2534            0 :     }
    2535              : 
    2536              :     /// This is used by tests & import-from-basebackup.
    2537              :     ///
    2538              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2539              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2540              :     ///
    2541              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2542              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2543              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2544              :     /// to the [`TenantShard::timelines`].
    2545              :     ///
    2546              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2547          115 :     pub(crate) async fn create_empty_timeline(
    2548          115 :         self: &Arc<Self>,
    2549          115 :         new_timeline_id: TimelineId,
    2550          115 :         initdb_lsn: Lsn,
    2551          115 :         pg_version: PgMajorVersion,
    2552          115 :         ctx: &RequestContext,
    2553          115 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2554          115 :         anyhow::ensure!(
    2555          115 :             self.is_active(),
    2556            0 :             "Cannot create empty timelines on inactive tenant"
    2557              :         );
    2558              : 
    2559              :         // Protect against concurrent attempts to use this TimelineId
    2560          115 :         let create_guard = match self
    2561          115 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2562          115 :             .await?
    2563              :         {
    2564          114 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2565              :             StartCreatingTimelineResult::Idempotent(_) => {
    2566            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2567              :             }
    2568              :         };
    2569              : 
    2570          114 :         let new_metadata = TimelineMetadata::new(
    2571              :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2572              :             // make it valid, before calling finish_creation()
    2573          114 :             Lsn(0),
    2574          114 :             None,
    2575          114 :             None,
    2576          114 :             Lsn(0),
    2577          114 :             initdb_lsn,
    2578          114 :             initdb_lsn,
    2579          114 :             pg_version,
    2580              :         );
    2581          114 :         self.prepare_new_timeline(
    2582          114 :             new_timeline_id,
    2583          114 :             &new_metadata,
    2584          114 :             create_guard,
    2585          114 :             initdb_lsn,
    2586          114 :             None,
    2587          114 :             None,
    2588          114 :             None,
    2589          114 :             ctx,
    2590          114 :         )
    2591          114 :         .await
    2592          115 :     }
    2593              : 
    2594              :     /// Helper for unit tests to create an empty timeline.
    2595              :     ///
    2596              :     /// The timeline is has state value `Active` but its background loops are not running.
    2597              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2598              :     // Our current tests don't need the background loops.
    2599              :     #[cfg(test)]
    2600          110 :     pub async fn create_test_timeline(
    2601          110 :         self: &Arc<Self>,
    2602          110 :         new_timeline_id: TimelineId,
    2603          110 :         initdb_lsn: Lsn,
    2604          110 :         pg_version: PgMajorVersion,
    2605          110 :         ctx: &RequestContext,
    2606          110 :     ) -> anyhow::Result<Arc<Timeline>> {
    2607          110 :         let (uninit_tl, ctx) = self
    2608          110 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2609          110 :             .await?;
    2610          110 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2611          110 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2612              : 
    2613              :         // Setup minimum keys required for the timeline to be usable.
    2614          110 :         let mut modification = tline.begin_modification(initdb_lsn);
    2615          110 :         modification
    2616          110 :             .init_empty_test_timeline()
    2617          110 :             .context("init_empty_test_timeline")?;
    2618          110 :         modification
    2619          110 :             .commit(&ctx)
    2620          110 :             .await
    2621          110 :             .context("commit init_empty_test_timeline modification")?;
    2622              : 
    2623              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2624          110 :         tline.maybe_spawn_flush_loop();
    2625          110 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2626              : 
    2627              :         // Make sure the freeze_and_flush reaches remote storage.
    2628          110 :         tline.remote_client.wait_completion().await.unwrap();
    2629              : 
    2630          110 :         let tl = uninit_tl.finish_creation().await?;
    2631              :         // The non-test code would call tl.activate() here.
    2632          110 :         tl.set_state(TimelineState::Active);
    2633          110 :         Ok(tl)
    2634          110 :     }
    2635              : 
    2636              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2637              :     #[cfg(test)]
    2638              :     #[allow(clippy::too_many_arguments)]
    2639           24 :     pub async fn create_test_timeline_with_layers(
    2640           24 :         self: &Arc<Self>,
    2641           24 :         new_timeline_id: TimelineId,
    2642           24 :         initdb_lsn: Lsn,
    2643           24 :         pg_version: PgMajorVersion,
    2644           24 :         ctx: &RequestContext,
    2645           24 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2646           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2647           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2648           24 :         end_lsn: Lsn,
    2649           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    2650              :         use checks::check_valid_layermap;
    2651              :         use itertools::Itertools;
    2652              : 
    2653           24 :         let tline = self
    2654           24 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2655           24 :             .await?;
    2656           24 :         tline.force_advance_lsn(end_lsn);
    2657           71 :         for deltas in delta_layer_desc {
    2658           47 :             tline
    2659           47 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2660           47 :                 .await?;
    2661              :         }
    2662           58 :         for (lsn, images) in image_layer_desc {
    2663           34 :             tline
    2664           34 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2665           34 :                 .await?;
    2666              :         }
    2667           28 :         for in_memory in in_memory_layer_desc {
    2668            4 :             tline
    2669            4 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2670            4 :                 .await?;
    2671              :         }
    2672           24 :         let layer_names = tline
    2673           24 :             .layers
    2674           24 :             .read(LayerManagerLockHolder::Testing)
    2675           24 :             .await
    2676           24 :             .layer_map()
    2677           24 :             .unwrap()
    2678           24 :             .iter_historic_layers()
    2679          105 :             .map(|layer| layer.layer_name())
    2680           24 :             .collect_vec();
    2681           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2682            0 :             bail!("invalid layermap: {err}");
    2683           24 :         }
    2684           24 :         Ok(tline)
    2685           24 :     }
    2686              : 
    2687              :     /// Create a new timeline.
    2688              :     ///
    2689              :     /// Returns the new timeline ID and reference to its Timeline object.
    2690              :     ///
    2691              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2692              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2693              :     #[allow(clippy::too_many_arguments)]
    2694            0 :     pub(crate) async fn create_timeline(
    2695            0 :         self: &Arc<TenantShard>,
    2696            0 :         params: CreateTimelineParams,
    2697            0 :         broker_client: storage_broker::BrokerClientChannel,
    2698            0 :         ctx: &RequestContext,
    2699            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2700            0 :         if !self.is_active() {
    2701            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2702            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2703              :             } else {
    2704            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2705            0 :                     "Cannot create timelines on inactive tenant"
    2706            0 :                 )));
    2707              :             }
    2708            0 :         }
    2709              : 
    2710            0 :         let _gate = self
    2711            0 :             .gate
    2712            0 :             .enter()
    2713            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2714              : 
    2715            0 :         let result: CreateTimelineResult = match params {
    2716              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2717            0 :                 new_timeline_id,
    2718            0 :                 existing_initdb_timeline_id,
    2719            0 :                 pg_version,
    2720              :             }) => {
    2721            0 :                 self.bootstrap_timeline(
    2722            0 :                     new_timeline_id,
    2723            0 :                     pg_version,
    2724            0 :                     existing_initdb_timeline_id,
    2725            0 :                     ctx,
    2726            0 :                 )
    2727            0 :                 .await?
    2728              :             }
    2729              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2730            0 :                 new_timeline_id,
    2731            0 :                 ancestor_timeline_id,
    2732            0 :                 mut ancestor_start_lsn,
    2733              :             }) => {
    2734            0 :                 let ancestor_timeline = self
    2735            0 :                     .get_timeline(ancestor_timeline_id, false)
    2736            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2737              : 
    2738              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2739              :                 // ready for other purposes either.
    2740            0 :                 if !ancestor_timeline.is_active() {
    2741            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2742            0 :                 }
    2743              : 
    2744            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2745            0 :                     info!("tried to branch archived timeline");
    2746            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2747            0 :                 }
    2748              : 
    2749            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2750            0 :                     *lsn = lsn.align();
    2751              : 
    2752            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2753            0 :                     if ancestor_ancestor_lsn > *lsn {
    2754              :                         // can we safely just branch from the ancestor instead?
    2755            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2756            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2757            0 :                             lsn,
    2758            0 :                             ancestor_timeline_id,
    2759            0 :                             ancestor_ancestor_lsn,
    2760            0 :                         )));
    2761            0 :                     }
    2762              : 
    2763              :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2764              :                     // to the requested branch point. The repository code itself doesn't
    2765              :                     // require it, but if we start to receive WAL on the new timeline,
    2766              :                     // decoding the new WAL might need to look up previous pages, relation
    2767              :                     // sizes etc. and that would get confused if the previous page versions
    2768              :                     // are not in the repository yet.
    2769            0 :                     ancestor_timeline
    2770            0 :                         .wait_lsn(
    2771            0 :                             *lsn,
    2772            0 :                             timeline::WaitLsnWaiter::Tenant,
    2773            0 :                             timeline::WaitLsnTimeout::Default,
    2774            0 :                             ctx,
    2775            0 :                         )
    2776            0 :                         .await
    2777            0 :                         .map_err(|e| match e {
    2778            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2779            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2780              :                             }
    2781            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2782            0 :                         })?;
    2783            0 :                 }
    2784              : 
    2785            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2786            0 :                     .await?
    2787              :             }
    2788            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2789            0 :                 self.create_timeline_import_pgdata(params, ctx).await?
    2790              :             }
    2791              :         };
    2792              : 
    2793              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2794              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2795              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2796              :         //
    2797              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2798              :         // assume that, because they can see the timeline via API, that the creation is done and
    2799              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2800              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2801              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2802              :         //
    2803              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2804              :         // creation API until it returns success. Only then is durability guaranteed.
    2805            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2806            0 :         result
    2807            0 :             .timeline()
    2808            0 :             .remote_client
    2809            0 :             .wait_completion()
    2810            0 :             .await
    2811            0 :             .map_err(|e| match e {
    2812              :                 WaitCompletionError::NotInitialized(
    2813            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2814            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2815              :                 WaitCompletionError::NotInitialized(_) => {
    2816              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2817            0 :                     debug_assert!(false);
    2818            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2819              :                 }
    2820              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2821            0 :                     CreateTimelineError::ShuttingDown
    2822              :                 }
    2823            0 :             })?;
    2824              : 
    2825              :         // The creating task is responsible for activating the timeline.
    2826              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2827              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2828            0 :         let activated_timeline = match result {
    2829            0 :             CreateTimelineResult::Created(timeline) => {
    2830            0 :                 timeline.activate(
    2831            0 :                     self.clone(),
    2832            0 :                     broker_client,
    2833            0 :                     None,
    2834            0 :                     &ctx.with_scope_timeline(&timeline),
    2835              :                 );
    2836            0 :                 timeline
    2837              :             }
    2838            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2839            0 :                 info!(
    2840            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2841              :                 );
    2842            0 :                 timeline
    2843              :             }
    2844            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2845            0 :                 info!(
    2846            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2847              :                 );
    2848            0 :                 timeline
    2849              :             }
    2850              :         };
    2851              : 
    2852            0 :         Ok(activated_timeline)
    2853            0 :     }
    2854              : 
    2855              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2856              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2857              :     /// [`TenantShard::timelines`] map when the import completes.
    2858              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2859              :     /// for the response.
    2860            0 :     async fn create_timeline_import_pgdata(
    2861            0 :         self: &Arc<Self>,
    2862            0 :         params: CreateTimelineParamsImportPgdata,
    2863            0 :         ctx: &RequestContext,
    2864            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2865              :         let CreateTimelineParamsImportPgdata {
    2866            0 :             new_timeline_id,
    2867            0 :             location,
    2868            0 :             idempotency_key,
    2869            0 :         } = params;
    2870              : 
    2871            0 :         let started_at = chrono::Utc::now().naive_utc();
    2872              : 
    2873              :         //
    2874              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2875              :         // is the canonical way we do it.
    2876              :         // - create an empty timeline in-memory
    2877              :         // - use its remote_timeline_client to do the upload
    2878              :         // - dispose of the uninit timeline
    2879              :         // - keep the creation guard alive
    2880              : 
    2881            0 :         let timeline_create_guard = match self
    2882            0 :             .start_creating_timeline(
    2883            0 :                 new_timeline_id,
    2884            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2885            0 :                     idempotency_key: idempotency_key.clone(),
    2886            0 :                 }),
    2887            0 :             )
    2888            0 :             .await?
    2889              :         {
    2890            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2891            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2892            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2893              :             }
    2894              :         };
    2895              : 
    2896            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2897            0 :             let this = &self;
    2898            0 :             let initdb_lsn = Lsn(0);
    2899            0 :             async move {
    2900            0 :                 let new_metadata = TimelineMetadata::new(
    2901              :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2902              :                     // make it valid, before calling finish_creation()
    2903            0 :                     Lsn(0),
    2904            0 :                     None,
    2905            0 :                     None,
    2906            0 :                     Lsn(0),
    2907            0 :                     initdb_lsn,
    2908            0 :                     initdb_lsn,
    2909            0 :                     PgMajorVersion::PG15,
    2910              :                 );
    2911            0 :                 this.prepare_new_timeline(
    2912            0 :                     new_timeline_id,
    2913            0 :                     &new_metadata,
    2914            0 :                     timeline_create_guard,
    2915            0 :                     initdb_lsn,
    2916            0 :                     None,
    2917            0 :                     None,
    2918            0 :                     None,
    2919            0 :                     ctx,
    2920            0 :                 )
    2921            0 :                 .await
    2922            0 :             }
    2923              :         }
    2924            0 :         .await?;
    2925              : 
    2926            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2927            0 :             idempotency_key,
    2928            0 :             location,
    2929            0 :             started_at,
    2930            0 :         };
    2931            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2932            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2933            0 :         );
    2934            0 :         uninit_timeline
    2935            0 :             .raw_timeline()
    2936            0 :             .unwrap()
    2937            0 :             .remote_client
    2938            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2939              : 
    2940              :         // wait_completion happens in caller
    2941              : 
    2942            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2943              : 
    2944            0 :         let import_task_gate = Gate::default();
    2945            0 :         let import_task_guard = import_task_gate.enter().unwrap();
    2946              : 
    2947            0 :         let import_task_handle = tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2948            0 :             timeline.clone(),
    2949            0 :             index_part,
    2950            0 :             timeline_create_guard,
    2951            0 :             import_task_guard,
    2952            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2953              :         ));
    2954              : 
    2955            0 :         let prev = self.timelines_importing.lock().unwrap().insert(
    2956            0 :             timeline.timeline_id,
    2957            0 :             Arc::new(ImportingTimeline {
    2958            0 :                 timeline: timeline.clone(),
    2959            0 :                 import_task_handle,
    2960            0 :                 import_task_gate,
    2961            0 :                 delete_progress: TimelineDeleteProgress::default(),
    2962            0 :             }),
    2963            0 :         );
    2964              : 
    2965              :         // Idempotency is enforced higher up the stack
    2966            0 :         assert!(prev.is_none());
    2967              : 
    2968              :         // NB: the timeline doesn't exist in self.timelines at this point
    2969            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2970            0 :     }
    2971              : 
    2972              :     /// Finalize the import of a timeline on this shard by marking it complete in
    2973              :     /// the index part. If the import task hasn't finished yet, returns an error.
    2974              :     ///
    2975              :     /// This method is idempotent. If the import was finalized once, the next call
    2976              :     /// will be a no-op.
    2977            0 :     pub(crate) async fn finalize_importing_timeline(
    2978            0 :         &self,
    2979            0 :         timeline_id: TimelineId,
    2980            0 :     ) -> Result<(), FinalizeTimelineImportError> {
    2981            0 :         let timeline = {
    2982            0 :             let locked = self.timelines_importing.lock().unwrap();
    2983            0 :             match locked.get(&timeline_id) {
    2984            0 :                 Some(importing_timeline) => {
    2985            0 :                     if !importing_timeline.import_task_handle.is_finished() {
    2986            0 :                         return Err(FinalizeTimelineImportError::ImportTaskStillRunning);
    2987            0 :                     }
    2988              : 
    2989            0 :                     importing_timeline.timeline.clone()
    2990              :                 }
    2991              :                 None => {
    2992            0 :                     return Ok(());
    2993              :                 }
    2994              :             }
    2995              :         };
    2996              : 
    2997            0 :         timeline
    2998            0 :             .remote_client
    2999            0 :             .schedule_index_upload_for_import_pgdata_finalize()
    3000            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    3001            0 :         timeline
    3002            0 :             .remote_client
    3003            0 :             .wait_completion()
    3004            0 :             .await
    3005            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    3006              : 
    3007            0 :         self.timelines_importing
    3008            0 :             .lock()
    3009            0 :             .unwrap()
    3010            0 :             .remove(&timeline_id);
    3011              : 
    3012            0 :         Ok(())
    3013            0 :     }
    3014              : 
    3015              :     #[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))]
    3016              :     async fn create_timeline_import_pgdata_task(
    3017              :         self: Arc<TenantShard>,
    3018              :         timeline: Arc<Timeline>,
    3019              :         index_part: import_pgdata::index_part_format::Root,
    3020              :         timeline_create_guard: TimelineCreateGuard,
    3021              :         _import_task_guard: GateGuard,
    3022              :         ctx: RequestContext,
    3023              :     ) {
    3024              :         debug_assert_current_span_has_tenant_and_timeline_id();
    3025              :         info!("starting");
    3026              :         scopeguard::defer! {info!("exiting")};
    3027              : 
    3028              :         let res = self
    3029              :             .create_timeline_import_pgdata_task_impl(
    3030              :                 timeline,
    3031              :                 index_part,
    3032              :                 timeline_create_guard,
    3033              :                 ctx,
    3034              :             )
    3035              :             .await;
    3036              :         if let Err(err) = &res {
    3037              :             error!(?err, "task failed");
    3038              :             // TODO sleep & retry, sensitive to tenant shutdown
    3039              :             // TODO: allow timeline deletion requests => should cancel the task
    3040              :         }
    3041              :     }
    3042              : 
    3043            0 :     async fn create_timeline_import_pgdata_task_impl(
    3044            0 :         self: Arc<TenantShard>,
    3045            0 :         timeline: Arc<Timeline>,
    3046            0 :         index_part: import_pgdata::index_part_format::Root,
    3047            0 :         _timeline_create_guard: TimelineCreateGuard,
    3048            0 :         ctx: RequestContext,
    3049            0 :     ) -> Result<(), anyhow::Error> {
    3050            0 :         info!("importing pgdata");
    3051            0 :         let ctx = ctx.with_scope_timeline(&timeline);
    3052            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    3053            0 :             .await
    3054            0 :             .context("import")?;
    3055            0 :         info!("import done - waiting for activation");
    3056              : 
    3057            0 :         anyhow::Ok(())
    3058            0 :     }
    3059              : 
    3060            0 :     pub(crate) async fn delete_timeline(
    3061            0 :         self: Arc<Self>,
    3062            0 :         timeline_id: TimelineId,
    3063            0 :     ) -> Result<(), DeleteTimelineError> {
    3064            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    3065              : 
    3066            0 :         Ok(())
    3067            0 :     }
    3068              : 
    3069              :     /// perform one garbage collection iteration, removing old data files from disk.
    3070              :     /// this function is periodically called by gc task.
    3071              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    3072              :     ///
    3073              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    3074              :     ///
    3075              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    3076              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    3077              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    3078              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    3079              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    3080              :     /// requires more history to be retained.
    3081              :     //
    3082          377 :     pub(crate) async fn gc_iteration(
    3083          377 :         &self,
    3084          377 :         target_timeline_id: Option<TimelineId>,
    3085          377 :         horizon: u64,
    3086          377 :         pitr: Duration,
    3087          377 :         cancel: &CancellationToken,
    3088          377 :         ctx: &RequestContext,
    3089          377 :     ) -> Result<GcResult, GcError> {
    3090              :         // Don't start doing work during shutdown
    3091          377 :         if let TenantState::Stopping { .. } = self.current_state() {
    3092            0 :             return Ok(GcResult::default());
    3093          377 :         }
    3094              : 
    3095              :         // there is a global allowed_error for this
    3096          377 :         if !self.is_active() {
    3097            0 :             return Err(GcError::NotActive);
    3098          377 :         }
    3099              : 
    3100              :         {
    3101          377 :             let conf = self.tenant_conf.load();
    3102              : 
    3103              :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    3104              :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    3105              :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    3106              :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    3107          377 :             if !conf.location.may_delete_layers_hint() {
    3108            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    3109            0 :                 return Ok(GcResult::default());
    3110          377 :             }
    3111              : 
    3112          377 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    3113            0 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3114            0 :                 return Ok(GcResult::default());
    3115          377 :             }
    3116              :         }
    3117              : 
    3118          377 :         let _guard = match self.gc_block.start().await {
    3119          377 :             Ok(guard) => guard,
    3120            0 :             Err(reasons) => {
    3121            0 :                 info!("Skipping GC: {reasons}");
    3122            0 :                 return Ok(GcResult::default());
    3123              :             }
    3124              :         };
    3125              : 
    3126          377 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3127          377 :             .await
    3128          377 :     }
    3129              : 
    3130              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3131              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3132              :     /// immediate L0 compaction.
    3133              :     ///
    3134              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3135            0 :     async fn compaction_iteration(
    3136            0 :         self: &Arc<Self>,
    3137            0 :         cancel: &CancellationToken,
    3138            0 :         ctx: &RequestContext,
    3139            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3140              :         // Don't compact inactive tenants.
    3141            0 :         if !self.is_active() {
    3142            0 :             return Ok(CompactionOutcome::Skipped);
    3143            0 :         }
    3144              : 
    3145              :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3146              :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3147            0 :         let location = self.tenant_conf.load().location;
    3148            0 :         if !location.may_upload_layers_hint() {
    3149            0 :             info!("skipping compaction in location state {location:?}");
    3150            0 :             return Ok(CompactionOutcome::Skipped);
    3151            0 :         }
    3152              : 
    3153              :         // Don't compact if the circuit breaker is tripped.
    3154            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3155            0 :             info!("skipping compaction due to previous failures");
    3156            0 :             return Ok(CompactionOutcome::Skipped);
    3157            0 :         }
    3158              : 
    3159              :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3160            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3161            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3162            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3163              : 
    3164              :         {
    3165            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3166            0 :             let timelines = self.timelines.lock().unwrap();
    3167            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3168              :                 // Skip inactive timelines.
    3169            0 :                 if !timeline.is_active() {
    3170            0 :                     continue;
    3171            0 :                 }
    3172              : 
    3173              :                 // Schedule the timeline for compaction.
    3174            0 :                 compact.push(timeline.clone());
    3175              : 
    3176              :                 // Schedule the timeline for offloading if eligible.
    3177            0 :                 let can_offload = offload_enabled
    3178            0 :                     && timeline.can_offload().0
    3179            0 :                     && !timelines
    3180            0 :                         .iter()
    3181            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3182            0 :                 if can_offload {
    3183            0 :                     offload.insert(timeline_id);
    3184            0 :                 }
    3185              :             }
    3186              :         } // release timelines lock
    3187              : 
    3188            0 :         for timeline in &compact {
    3189              :             // Collect L0 counts. Can't await while holding lock above.
    3190            0 :             if let Ok(lm) = timeline
    3191            0 :                 .layers
    3192            0 :                 .read(LayerManagerLockHolder::Compaction)
    3193            0 :                 .await
    3194            0 :                 .layer_map()
    3195            0 :             {
    3196            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3197            0 :             }
    3198              :         }
    3199              : 
    3200              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3201              :         // bound read amplification.
    3202              :         //
    3203              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3204              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3205              :         // splitting L0 and image/GC compaction to separate background jobs.
    3206            0 :         if self.get_compaction_l0_first() {
    3207            0 :             let compaction_threshold = self.get_compaction_threshold();
    3208            0 :             let compact_l0 = compact
    3209            0 :                 .iter()
    3210            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3211            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3212            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3213            0 :                 .rev()
    3214            0 :                 .map(|(tli, _)| tli.clone())
    3215            0 :                 .collect_vec();
    3216              : 
    3217            0 :             let mut has_pending_l0 = false;
    3218            0 :             for timeline in compact_l0 {
    3219            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3220              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3221            0 :                 let outcome = timeline
    3222            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3223            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3224            0 :                     .await
    3225            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3226            0 :                 match outcome {
    3227            0 :                     CompactionOutcome::Done => {}
    3228            0 :                     CompactionOutcome::Skipped => {}
    3229            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3230            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3231              :                 }
    3232              :             }
    3233            0 :             if has_pending_l0 {
    3234            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3235            0 :             }
    3236            0 :         }
    3237              : 
    3238              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3239              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3240              :         // pending L0 compaction on any tenant timeline.
    3241              :         //
    3242              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3243              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3244            0 :         let mut has_pending = false;
    3245            0 :         for timeline in compact {
    3246            0 :             if !timeline.is_active() {
    3247            0 :                 continue;
    3248            0 :             }
    3249            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3250              : 
    3251              :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3252            0 :             let mut flags = EnumSet::default();
    3253            0 :             if self.get_compaction_l0_first() {
    3254            0 :                 flags |= CompactFlags::YieldForL0;
    3255            0 :             }
    3256              : 
    3257            0 :             let mut outcome = timeline
    3258            0 :                 .compact(cancel, flags, ctx)
    3259            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3260            0 :                 .await
    3261            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3262              : 
    3263              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3264            0 :             if outcome == CompactionOutcome::Done {
    3265            0 :                 let queue = {
    3266            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3267            0 :                     guard
    3268            0 :                         .entry(timeline.timeline_id)
    3269            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3270            0 :                         .clone()
    3271              :                 };
    3272            0 :                 let gc_compaction_strategy = self
    3273            0 :                     .feature_resolver
    3274            0 :                     .evaluate_multivariate("gc-comapction-strategy")
    3275            0 :                     .ok();
    3276            0 :                 let span = if let Some(gc_compaction_strategy) = gc_compaction_strategy {
    3277            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id, strategy = %gc_compaction_strategy)
    3278              :                 } else {
    3279            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id)
    3280              :                 };
    3281            0 :                 outcome = queue
    3282            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3283            0 :                     .instrument(span)
    3284            0 :                     .await?;
    3285            0 :             }
    3286              : 
    3287              :             // If we're done compacting, offload the timeline if requested.
    3288            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3289            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3290            0 :                 offload_timeline(self, &timeline)
    3291            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3292            0 :                     .await
    3293            0 :                     .or_else(|err| match err {
    3294              :                         // Ignore this, we likely raced with unarchival.
    3295            0 :                         OffloadError::NotArchived => Ok(()),
    3296            0 :                         OffloadError::AlreadyInProgress => Ok(()),
    3297            0 :                         OffloadError::Cancelled => Err(CompactionError::new_cancelled()),
    3298              :                         // don't break the anyhow chain
    3299            0 :                         OffloadError::Other(err) => Err(CompactionError::Other(err)),
    3300            0 :                     })?;
    3301            0 :             }
    3302              : 
    3303            0 :             match outcome {
    3304            0 :                 CompactionOutcome::Done => {}
    3305            0 :                 CompactionOutcome::Skipped => {}
    3306            0 :                 CompactionOutcome::Pending => has_pending = true,
    3307              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3308              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3309            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3310              :             }
    3311              :         }
    3312              : 
    3313              :         // Success! Untrip the breaker if necessary.
    3314            0 :         self.compaction_circuit_breaker
    3315            0 :             .lock()
    3316            0 :             .unwrap()
    3317            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3318              : 
    3319            0 :         match has_pending {
    3320            0 :             true => Ok(CompactionOutcome::Pending),
    3321            0 :             false => Ok(CompactionOutcome::Done),
    3322              :         }
    3323            0 :     }
    3324              : 
    3325              :     /// Trips the compaction circuit breaker if appropriate.
    3326            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3327            0 :         if err.is_cancel() {
    3328            0 :             return;
    3329            0 :         }
    3330            0 :         self.compaction_circuit_breaker
    3331            0 :             .lock()
    3332            0 :             .unwrap()
    3333            0 :             .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3334            0 :     }
    3335              : 
    3336              :     /// Cancel scheduled compaction tasks
    3337            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3338            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3339            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3340            0 :             q.cancel_scheduled();
    3341            0 :         }
    3342            0 :     }
    3343              : 
    3344            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3345            0 :         &self,
    3346            0 :         timeline_id: TimelineId,
    3347            0 :     ) -> Vec<CompactInfoResponse> {
    3348            0 :         let res = {
    3349            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3350            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3351              :         };
    3352            0 :         let Some((running, remaining)) = res else {
    3353            0 :             return Vec::new();
    3354              :         };
    3355            0 :         let mut result = Vec::new();
    3356            0 :         if let Some((id, running)) = running {
    3357            0 :             result.extend(running.into_compact_info_resp(id, true));
    3358            0 :         }
    3359            0 :         for (id, job) in remaining {
    3360            0 :             result.extend(job.into_compact_info_resp(id, false));
    3361            0 :         }
    3362            0 :         result
    3363            0 :     }
    3364              : 
    3365              :     /// Schedule a compaction task for a timeline.
    3366            0 :     pub(crate) async fn schedule_compaction(
    3367            0 :         &self,
    3368            0 :         timeline_id: TimelineId,
    3369            0 :         options: CompactOptions,
    3370            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3371            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3372            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3373            0 :         let q = guard
    3374            0 :             .entry(timeline_id)
    3375            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3376            0 :         q.schedule_manual_compaction(options, Some(tx));
    3377            0 :         Ok(rx)
    3378            0 :     }
    3379              : 
    3380              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3381            0 :     async fn housekeeping(&self) {
    3382              :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3383              :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3384              :         //
    3385              :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3386              :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3387              :         // layers that won't be compacted down.
    3388            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3389            0 :             let timelines = self
    3390            0 :                 .timelines
    3391            0 :                 .lock()
    3392            0 :                 .unwrap()
    3393            0 :                 .values()
    3394            0 :                 .filter(|tli| tli.is_active())
    3395            0 :                 .cloned()
    3396            0 :                 .collect_vec();
    3397              : 
    3398            0 :             for timeline in timelines {
    3399              :                 // Include a span with the timeline ID. The parent span already has the tenant ID.
    3400            0 :                 let span =
    3401            0 :                     info_span!("maybe_freeze_ephemeral_layer", timeline_id = %timeline.timeline_id);
    3402            0 :                 timeline
    3403            0 :                     .maybe_freeze_ephemeral_layer()
    3404            0 :                     .instrument(span)
    3405            0 :                     .await;
    3406              :             }
    3407            0 :         }
    3408              : 
    3409              :         // Shut down walredo if idle.
    3410              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3411            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3412            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3413            0 :         }
    3414              : 
    3415              :         // Update the feature resolver with the latest tenant-spcific data.
    3416            0 :         self.feature_resolver.refresh_properties_and_flags(self);
    3417            0 :     }
    3418              : 
    3419            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3420            0 :         let timelines = self.timelines.lock().unwrap();
    3421            0 :         !timelines
    3422            0 :             .iter()
    3423            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3424            0 :     }
    3425              : 
    3426         1371 :     pub fn current_state(&self) -> TenantState {
    3427         1371 :         self.state.borrow().clone()
    3428         1371 :     }
    3429              : 
    3430          990 :     pub fn is_active(&self) -> bool {
    3431          990 :         self.current_state() == TenantState::Active
    3432          990 :     }
    3433              : 
    3434            0 :     pub fn generation(&self) -> Generation {
    3435            0 :         self.generation
    3436            0 :     }
    3437              : 
    3438            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3439            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3440            0 :     }
    3441              : 
    3442              :     /// Changes tenant status to active, unless shutdown was already requested.
    3443              :     ///
    3444              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3445              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3446            0 :     fn activate(
    3447            0 :         self: &Arc<Self>,
    3448            0 :         broker_client: BrokerClientChannel,
    3449            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3450            0 :         ctx: &RequestContext,
    3451            0 :     ) {
    3452            0 :         span::debug_assert_current_span_has_tenant_id();
    3453              : 
    3454            0 :         let mut activating = false;
    3455            0 :         self.state.send_modify(|current_state| {
    3456              :             use pageserver_api::models::ActivatingFrom;
    3457            0 :             match &*current_state {
    3458              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3459            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {current_state:?}");
    3460              :                 }
    3461            0 :                 TenantState::Attaching => {
    3462            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3463            0 :                 }
    3464              :             }
    3465            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3466            0 :             activating = true;
    3467              :             // Continue outside the closure. We need to grab timelines.lock()
    3468              :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3469            0 :         });
    3470              : 
    3471            0 :         if activating {
    3472            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3473            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3474            0 :             let timelines_to_activate = timelines_accessor
    3475            0 :                 .values()
    3476            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3477              : 
    3478              :             // Spawn gc and compaction loops. The loops will shut themselves
    3479              :             // down when they notice that the tenant is inactive.
    3480            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3481              : 
    3482            0 :             let mut activated_timelines = 0;
    3483              : 
    3484            0 :             for timeline in timelines_to_activate {
    3485            0 :                 timeline.activate(
    3486            0 :                     self.clone(),
    3487            0 :                     broker_client.clone(),
    3488            0 :                     background_jobs_can_start,
    3489            0 :                     &ctx.with_scope_timeline(timeline),
    3490            0 :                 );
    3491            0 :                 activated_timelines += 1;
    3492            0 :             }
    3493              : 
    3494            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3495            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3496            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3497            0 :             TENANT_OFFLOADED_TIMELINES
    3498            0 :                 .with_label_values(&[&tid, &shard_id])
    3499            0 :                 .set(offloaded_timeline_count as u64);
    3500              : 
    3501            0 :             self.state.send_modify(move |current_state| {
    3502            0 :                 assert!(
    3503            0 :                     matches!(current_state, TenantState::Activating(_)),
    3504            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3505              :                 );
    3506            0 :                 *current_state = TenantState::Active;
    3507              : 
    3508            0 :                 let elapsed = self.constructed_at.elapsed();
    3509            0 :                 let total_timelines = timelines_accessor.len();
    3510              : 
    3511              :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3512              :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3513            0 :                 info!(
    3514            0 :                     since_creation_millis = elapsed.as_millis(),
    3515            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3516            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3517              :                     activated_timelines,
    3518              :                     total_timelines,
    3519            0 :                     post_state = <&'static str>::from(&*current_state),
    3520            0 :                     "activation attempt finished"
    3521              :                 );
    3522              : 
    3523            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3524            0 :             });
    3525            0 :         }
    3526            0 :     }
    3527              : 
    3528              :     /// Shutdown the tenant and join all of the spawned tasks.
    3529              :     ///
    3530              :     /// The method caters for all use-cases:
    3531              :     /// - pageserver shutdown (freeze_and_flush == true)
    3532              :     /// - detach + ignore (freeze_and_flush == false)
    3533              :     ///
    3534              :     /// This will attempt to shutdown even if tenant is broken.
    3535              :     ///
    3536              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3537              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3538              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3539              :     /// the ongoing shutdown.
    3540            3 :     async fn shutdown(
    3541            3 :         &self,
    3542            3 :         shutdown_progress: completion::Barrier,
    3543            3 :         shutdown_mode: timeline::ShutdownMode,
    3544            3 :     ) -> Result<(), completion::Barrier> {
    3545            3 :         span::debug_assert_current_span_has_tenant_id();
    3546              : 
    3547              :         // Set tenant (and its timlines) to Stoppping state.
    3548              :         //
    3549              :         // Since we can only transition into Stopping state after activation is complete,
    3550              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3551              :         //
    3552              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3553              :         // 1. Lock out any new requests to the tenants.
    3554              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3555              :         // 3. Signal cancellation for other tenant background loops.
    3556              :         // 4. ???
    3557              :         //
    3558              :         // The waiting for the cancellation is not done uniformly.
    3559              :         // We certainly wait for WAL receivers to shut down.
    3560              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3561              :         // But the tenant background loops are joined-on in our caller.
    3562              :         // It's mesed up.
    3563              :         // we just ignore the failure to stop
    3564              : 
    3565              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3566              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3567              :         // is very slow.
    3568            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3569            0 :             self.cancel.cancel();
    3570              : 
    3571              :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3572              :             // are children of ours, so their flush loops will have shut down already
    3573            0 :             timeline::ShutdownMode::Hard
    3574              :         } else {
    3575            3 :             shutdown_mode
    3576              :         };
    3577              : 
    3578            3 :         match self.set_stopping(shutdown_progress).await {
    3579            3 :             Ok(()) => {}
    3580            0 :             Err(SetStoppingError::Broken) => {
    3581            0 :                 // assume that this is acceptable
    3582            0 :             }
    3583            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3584              :                 // give caller the option to wait for this this shutdown
    3585            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3586            0 :                 return Err(other);
    3587              :             }
    3588              :         };
    3589              : 
    3590            3 :         let mut js = tokio::task::JoinSet::new();
    3591              :         {
    3592            3 :             let timelines = self.timelines.lock().unwrap();
    3593            3 :             timelines.values().for_each(|timeline| {
    3594            3 :                 let timeline = Arc::clone(timeline);
    3595            3 :                 let timeline_id = timeline.timeline_id;
    3596            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3597            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3598            3 :             });
    3599              :         }
    3600              :         {
    3601            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3602            3 :             timelines_offloaded.values().for_each(|timeline| {
    3603            0 :                 timeline.defuse_for_tenant_drop();
    3604            0 :             });
    3605              :         }
    3606              :         {
    3607            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3608            3 :             timelines_importing
    3609            3 :                 .drain()
    3610            3 :                 .for_each(|(timeline_id, importing_timeline)| {
    3611            0 :                     let span = tracing::info_span!("importing_timeline_shutdown", %timeline_id);
    3612            0 :                     js.spawn(async move { importing_timeline.shutdown().instrument(span).await });
    3613            0 :                 });
    3614              :         }
    3615              :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3616            3 :         tracing::info!("Waiting for timelines...");
    3617            6 :         while let Some(res) = js.join_next().await {
    3618            0 :             match res {
    3619            3 :                 Ok(()) => {}
    3620            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3621            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3622            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3623              :             }
    3624              :         }
    3625              : 
    3626            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3627            0 :             tracing::info!("Flushing deletion queue");
    3628            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3629            0 :                 match e {
    3630            0 :                     DeletionQueueError::ShuttingDown => {
    3631            0 :                         // This is the only error we expect for now. In the future, if more error
    3632            0 :                         // variants are added, we should handle them here.
    3633            0 :                     }
    3634              :                 }
    3635            0 :             }
    3636            3 :         }
    3637              : 
    3638              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3639              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3640            3 :         tracing::debug!("Cancelling CancellationToken");
    3641            3 :         self.cancel.cancel();
    3642              : 
    3643              :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3644              :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3645              :         //
    3646              :         // this will additionally shutdown and await all timeline tasks.
    3647            3 :         tracing::debug!("Waiting for tasks...");
    3648            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3649              : 
    3650            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3651            3 :             walredo_mgr.shutdown().await;
    3652            0 :         }
    3653              : 
    3654              :         // Wait for any in-flight operations to complete
    3655            3 :         self.gate.close().await;
    3656              : 
    3657            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3658              : 
    3659            3 :         Ok(())
    3660            3 :     }
    3661              : 
    3662              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3663              :     ///
    3664              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3665              :     ///
    3666              :     /// This function is not cancel-safe!
    3667            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3668            3 :         let mut rx = self.state.subscribe();
    3669              : 
    3670              :         // cannot stop before we're done activating, so wait out until we're done activating
    3671            3 :         rx.wait_for(|state| match state {
    3672              :             TenantState::Activating(_) | TenantState::Attaching => {
    3673            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3674            0 :                 false
    3675              :             }
    3676            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3677            3 :         })
    3678            3 :         .await
    3679            3 :         .expect("cannot drop self.state while on a &self method");
    3680              : 
    3681              :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3682            3 :         let mut err = None;
    3683            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3684              :             TenantState::Activating(_) | TenantState::Attaching => {
    3685            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3686              :             }
    3687              :             TenantState::Active => {
    3688              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3689              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3690              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3691            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3692              :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3693              :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3694            3 :                 true
    3695              :             }
    3696              :             TenantState::Stopping { progress: None } => {
    3697              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3698              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3699            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3700            0 :                 true
    3701              :             }
    3702            0 :             TenantState::Broken { reason, .. } => {
    3703            0 :                 info!(
    3704            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3705              :                 );
    3706            0 :                 err = Some(SetStoppingError::Broken);
    3707            0 :                 false
    3708              :             }
    3709            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3710            0 :                 info!("Tenant is already in Stopping state");
    3711            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3712            0 :                 false
    3713              :             }
    3714            3 :         });
    3715            3 :         match (stopping, err) {
    3716            3 :             (true, None) => {} // continue
    3717            0 :             (false, Some(err)) => return Err(err),
    3718            0 :             (true, Some(_)) => unreachable!(
    3719              :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3720              :             ),
    3721            0 :             (false, None) => unreachable!(
    3722              :                 "send_if_modified closure must return true if transitioning to Stopping"
    3723              :             ),
    3724              :         }
    3725              : 
    3726            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3727            3 :         let not_broken_timelines = timelines_accessor
    3728            3 :             .values()
    3729            3 :             .filter(|timeline| !timeline.is_broken());
    3730            6 :         for timeline in not_broken_timelines {
    3731            3 :             timeline.set_state(TimelineState::Stopping);
    3732            3 :         }
    3733            3 :         Ok(())
    3734            3 :     }
    3735              : 
    3736              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3737              :     /// `remove_tenant_from_memory`
    3738              :     ///
    3739              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3740              :     ///
    3741              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3742            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3743            0 :         let mut rx = self.state.subscribe();
    3744              : 
    3745              :         // The load & attach routines own the tenant state until it has reached `Active`.
    3746              :         // So, wait until it's done.
    3747            0 :         rx.wait_for(|state| match state {
    3748              :             TenantState::Activating(_) | TenantState::Attaching => {
    3749            0 :                 info!(
    3750            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3751            0 :                     <&'static str>::from(state)
    3752              :                 );
    3753            0 :                 false
    3754              :             }
    3755            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3756            0 :         })
    3757            0 :         .await
    3758            0 :         .expect("cannot drop self.state while on a &self method");
    3759              : 
    3760              :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3761            0 :         self.set_broken_no_wait(reason)
    3762            0 :     }
    3763              : 
    3764            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3765            0 :         let reason = reason.to_string();
    3766            0 :         self.state.send_modify(|current_state| {
    3767            0 :             match *current_state {
    3768              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3769            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3770              :                 }
    3771              :                 TenantState::Active => {
    3772            0 :                     if cfg!(feature = "testing") {
    3773            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3774            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3775              :                     } else {
    3776            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3777              :                     }
    3778              :                 }
    3779              :                 TenantState::Broken { .. } => {
    3780            0 :                     warn!("Tenant is already in Broken state");
    3781              :                 }
    3782              :                 // This is the only "expected" path, any other path is a bug.
    3783              :                 TenantState::Stopping { .. } => {
    3784            0 :                     warn!(
    3785            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3786              :                         reason
    3787              :                     );
    3788            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3789              :                 }
    3790              :            }
    3791            0 :         });
    3792            0 :     }
    3793              : 
    3794            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3795            0 :         self.state.subscribe()
    3796            0 :     }
    3797              : 
    3798              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3799              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3800            0 :     pub(crate) fn activate_now(&self) {
    3801            0 :         self.activate_now_sem.add_permits(1);
    3802            0 :     }
    3803              : 
    3804            0 :     pub(crate) async fn wait_to_become_active(
    3805            0 :         &self,
    3806            0 :         timeout: Duration,
    3807            0 :     ) -> Result<(), GetActiveTenantError> {
    3808            0 :         let mut receiver = self.state.subscribe();
    3809              :         loop {
    3810            0 :             let current_state = receiver.borrow_and_update().clone();
    3811            0 :             match current_state {
    3812              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3813              :                     // in these states, there's a chance that we can reach ::Active
    3814            0 :                     self.activate_now();
    3815            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3816            0 :                         Ok(r) => {
    3817            0 :                             r.map_err(
    3818              :                             |_e: tokio::sync::watch::error::RecvError|
    3819              :                                 // Tenant existed but was dropped: report it as non-existent
    3820            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3821            0 :                         )?
    3822              :                         }
    3823              :                         Err(TimeoutCancellableError::Cancelled) => {
    3824            0 :                             return Err(GetActiveTenantError::Cancelled);
    3825              :                         }
    3826              :                         Err(TimeoutCancellableError::Timeout) => {
    3827            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3828            0 :                                 latest_state: Some(self.current_state()),
    3829            0 :                                 wait_time: timeout,
    3830            0 :                             });
    3831              :                         }
    3832              :                     }
    3833              :                 }
    3834              :                 TenantState::Active => {
    3835            0 :                     return Ok(());
    3836              :                 }
    3837            0 :                 TenantState::Broken { reason, .. } => {
    3838              :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3839              :                     // it's logically a 500 to external API users (broken is always a bug).
    3840            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3841              :                 }
    3842              :                 TenantState::Stopping { .. } => {
    3843              :                     // There's no chance the tenant can transition back into ::Active
    3844            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3845              :                 }
    3846              :             }
    3847              :         }
    3848            0 :     }
    3849              : 
    3850            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3851            0 :         self.tenant_conf.load().location.attach_mode
    3852            0 :     }
    3853              : 
    3854              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3855              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3856              :     /// rare external API calls, like a reconciliation at startup.
    3857            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3858            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3859              : 
    3860            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3861            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3862            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3863            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3864              :         };
    3865              : 
    3866            0 :         models::LocationConfig {
    3867            0 :             mode: location_config_mode,
    3868            0 :             generation: self.generation.into(),
    3869            0 :             secondary_conf: None,
    3870            0 :             shard_number: self.shard_identity.number.0,
    3871            0 :             shard_count: self.shard_identity.count.literal(),
    3872            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3873            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3874            0 :         }
    3875            0 :     }
    3876              : 
    3877            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3878            0 :         &self.tenant_shard_id
    3879            0 :     }
    3880              : 
    3881            0 :     pub(crate) fn get_shard_identity(&self) -> ShardIdentity {
    3882            0 :         self.shard_identity
    3883            0 :     }
    3884              : 
    3885          120 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3886          120 :         self.shard_identity.stripe_size
    3887          120 :     }
    3888              : 
    3889            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3890            0 :         self.generation
    3891            0 :     }
    3892              : 
    3893              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3894              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3895              :     /// resetting this tenant to a valid state if we fail.
    3896            0 :     pub(crate) async fn split_prepare(
    3897            0 :         &self,
    3898            0 :         child_shards: &Vec<TenantShardId>,
    3899            0 :     ) -> anyhow::Result<()> {
    3900            0 :         let (timelines, offloaded) = {
    3901            0 :             let timelines = self.timelines.lock().unwrap();
    3902            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3903            0 :             (timelines.clone(), offloaded.clone())
    3904            0 :         };
    3905            0 :         let timelines_iter = timelines
    3906            0 :             .values()
    3907            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3908            0 :             .chain(
    3909            0 :                 offloaded
    3910            0 :                     .values()
    3911            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3912              :             );
    3913            0 :         for timeline in timelines_iter {
    3914              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3915              :             // to ensure that they do not start a split if currently in the process of doing these.
    3916              : 
    3917            0 :             let timeline_id = timeline.timeline_id();
    3918              : 
    3919            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3920              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3921              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3922              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3923            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3924            0 :                 timeline
    3925            0 :                     .remote_client
    3926            0 :                     .schedule_index_upload_for_file_changes()?;
    3927            0 :                 timeline.remote_client.wait_completion().await?;
    3928            0 :             }
    3929              : 
    3930            0 :             let remote_client = match timeline {
    3931            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3932            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3933            0 :                     let remote_client = self
    3934            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3935            0 :                     Arc::new(remote_client)
    3936              :                 }
    3937              :                 TimelineOrOffloadedArcRef::Importing(_) => {
    3938            0 :                     unreachable!("Importing timelines are not included in the iterator")
    3939              :                 }
    3940              :             };
    3941              : 
    3942              :             // Shut down the timeline's remote client: this means that the indices we write
    3943              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3944            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3945            0 :             remote_client.shutdown().await;
    3946              : 
    3947              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3948              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3949              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3950              :             // we use here really is the remotely persistent one).
    3951            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3952            0 :             let result = remote_client
    3953            0 :                 .download_index_file(&self.cancel)
    3954            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))
    3955            0 :                 .await?;
    3956            0 :             let index_part = match result {
    3957              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3958            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3959              :                 }
    3960            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3961              :             };
    3962              : 
    3963              :             // A shard split may not take place while a timeline import is on-going
    3964              :             // for the tenant. Timeline imports run as part of each tenant shard
    3965              :             // and rely on the sharding scheme to split the work among pageservers.
    3966              :             // If we were to split in the middle of this process, we would have to
    3967              :             // either ensure that it's driven to completion on the old shard set
    3968              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3969            0 :             match index_part.import_pgdata {
    3970            0 :                 Some(ref import) if !import.is_done() => {
    3971            0 :                     anyhow::bail!(
    3972            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3973            0 :                         import.idempotency_key()
    3974              :                     );
    3975              :                 }
    3976            0 :                 Some(_) | None => {
    3977            0 :                     // fallthrough
    3978            0 :                 }
    3979              :             }
    3980              : 
    3981            0 :             for child_shard in child_shards {
    3982            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3983            0 :                 upload_index_part(
    3984            0 :                     &self.remote_storage,
    3985            0 :                     child_shard,
    3986            0 :                     &timeline_id,
    3987            0 :                     self.generation,
    3988            0 :                     &index_part,
    3989            0 :                     &self.cancel,
    3990            0 :                 )
    3991            0 :                 .await?;
    3992              :             }
    3993              :         }
    3994              : 
    3995            0 :         let tenant_manifest = self.build_tenant_manifest();
    3996            0 :         for child_shard in child_shards {
    3997            0 :             tracing::info!(
    3998            0 :                 "Uploading tenant manifest for child {}",
    3999            0 :                 child_shard.to_index()
    4000              :             );
    4001            0 :             upload_tenant_manifest(
    4002            0 :                 &self.remote_storage,
    4003            0 :                 child_shard,
    4004            0 :                 self.generation,
    4005            0 :                 &tenant_manifest,
    4006            0 :                 &self.cancel,
    4007            0 :             )
    4008            0 :             .await?;
    4009              :         }
    4010              : 
    4011            0 :         Ok(())
    4012            0 :     }
    4013              : 
    4014            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    4015            0 :         let mut result = TopTenantShardItem {
    4016            0 :             id: self.tenant_shard_id,
    4017            0 :             resident_size: 0,
    4018            0 :             physical_size: 0,
    4019            0 :             max_logical_size: 0,
    4020            0 :             max_logical_size_per_shard: 0,
    4021            0 :         };
    4022              : 
    4023            0 :         for timeline in self.timelines.lock().unwrap().values() {
    4024            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    4025            0 : 
    4026            0 :             result.physical_size += timeline
    4027            0 :                 .remote_client
    4028            0 :                 .metrics
    4029            0 :                 .remote_physical_size_gauge
    4030            0 :                 .get();
    4031            0 :             result.max_logical_size = std::cmp::max(
    4032            0 :                 result.max_logical_size,
    4033            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    4034            0 :             );
    4035            0 :         }
    4036              : 
    4037            0 :         result.max_logical_size_per_shard = result
    4038            0 :             .max_logical_size
    4039            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    4040              : 
    4041            0 :         result
    4042            0 :     }
    4043              : }
    4044              : 
    4045              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    4046              : /// perform a topological sort, so that the parent of each timeline comes
    4047              : /// before the children.
    4048              : /// E extracts the ancestor from T
    4049              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    4050          119 : fn tree_sort_timelines<T, E>(
    4051          119 :     timelines: HashMap<TimelineId, T>,
    4052          119 :     extractor: E,
    4053          119 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    4054          119 : where
    4055          119 :     E: Fn(&T) -> Option<TimelineId>,
    4056              : {
    4057          119 :     let mut result = Vec::with_capacity(timelines.len());
    4058              : 
    4059          119 :     let mut now = Vec::with_capacity(timelines.len());
    4060              :     // (ancestor, children)
    4061          119 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    4062          119 :         HashMap::with_capacity(timelines.len());
    4063              : 
    4064          122 :     for (timeline_id, value) in timelines {
    4065            3 :         if let Some(ancestor_id) = extractor(&value) {
    4066            1 :             let children = later.entry(ancestor_id).or_default();
    4067            1 :             children.push((timeline_id, value));
    4068            2 :         } else {
    4069            2 :             now.push((timeline_id, value));
    4070            2 :         }
    4071              :     }
    4072              : 
    4073          122 :     while let Some((timeline_id, metadata)) = now.pop() {
    4074            3 :         result.push((timeline_id, metadata));
    4075              :         // All children of this can be loaded now
    4076            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    4077            1 :             now.append(&mut children);
    4078            2 :         }
    4079              :     }
    4080              : 
    4081              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    4082          119 :     if !later.is_empty() {
    4083            0 :         for (missing_id, orphan_ids) in later {
    4084            0 :             for (orphan_id, _) in orphan_ids {
    4085            0 :                 error!(
    4086            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    4087              :                 );
    4088              :             }
    4089              :         }
    4090            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    4091          119 :     }
    4092              : 
    4093          119 :     Ok(result)
    4094          119 : }
    4095              : 
    4096              : impl TenantShard {
    4097            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    4098            0 :         self.tenant_conf.load().tenant_conf.clone()
    4099            0 :     }
    4100              : 
    4101            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    4102            0 :         self.tenant_specific_overrides()
    4103            0 :             .merge(self.conf.default_tenant_conf.clone())
    4104            0 :     }
    4105              : 
    4106            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    4107            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4108            0 :         tenant_conf
    4109            0 :             .checkpoint_distance
    4110            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    4111            0 :     }
    4112              : 
    4113            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    4114            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4115            0 :         tenant_conf
    4116            0 :             .checkpoint_timeout
    4117            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    4118            0 :     }
    4119              : 
    4120            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    4121            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4122            0 :         tenant_conf
    4123            0 :             .compaction_target_size
    4124            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    4125            0 :     }
    4126              : 
    4127            0 :     pub fn get_compaction_period(&self) -> Duration {
    4128            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4129            0 :         tenant_conf
    4130            0 :             .compaction_period
    4131            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    4132            0 :     }
    4133              : 
    4134            0 :     pub fn get_compaction_threshold(&self) -> usize {
    4135            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4136            0 :         tenant_conf
    4137            0 :             .compaction_threshold
    4138            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4139            0 :     }
    4140              : 
    4141            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4142            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4143            0 :         tenant_conf
    4144            0 :             .rel_size_v2_enabled
    4145            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4146            0 :     }
    4147              : 
    4148            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4149            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4150            0 :         tenant_conf
    4151            0 :             .compaction_upper_limit
    4152            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4153            0 :     }
    4154              : 
    4155            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4156            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4157            0 :         tenant_conf
    4158            0 :             .compaction_l0_first
    4159            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4160            0 :     }
    4161              : 
    4162          121 :     pub fn get_gc_horizon(&self) -> u64 {
    4163          121 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4164          121 :         tenant_conf
    4165          121 :             .gc_horizon
    4166          121 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4167          121 :     }
    4168              : 
    4169            0 :     pub fn get_gc_period(&self) -> Duration {
    4170            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4171            0 :         tenant_conf
    4172            0 :             .gc_period
    4173            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4174            0 :     }
    4175              : 
    4176            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4177            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4178            0 :         tenant_conf
    4179            0 :             .image_creation_threshold
    4180            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4181            0 :     }
    4182              : 
    4183              :     // HADRON
    4184            0 :     pub fn get_image_creation_timeout(&self) -> Option<Duration> {
    4185            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4186            0 :         tenant_conf.image_layer_force_creation_period.or(self
    4187            0 :             .conf
    4188            0 :             .default_tenant_conf
    4189            0 :             .image_layer_force_creation_period)
    4190            0 :     }
    4191              : 
    4192            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4193            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4194            2 :         tenant_conf
    4195            2 :             .pitr_interval
    4196            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4197            2 :     }
    4198              : 
    4199            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4200            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4201            0 :         tenant_conf
    4202            0 :             .min_resident_size_override
    4203            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4204            0 :     }
    4205              : 
    4206            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4207            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4208            0 :         let heatmap_period = tenant_conf
    4209            0 :             .heatmap_period
    4210            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4211            0 :         if heatmap_period.is_zero() {
    4212            0 :             None
    4213              :         } else {
    4214            0 :             Some(heatmap_period)
    4215              :         }
    4216            0 :     }
    4217              : 
    4218            0 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4219            0 :         Self::get_lsn_lease_length_impl(self.conf, &self.tenant_conf.load().tenant_conf)
    4220            0 :     }
    4221              : 
    4222          119 :     pub fn get_lsn_lease_length_impl(
    4223          119 :         conf: &'static PageServerConf,
    4224          119 :         tenant_conf: &pageserver_api::models::TenantConfig,
    4225          119 :     ) -> Duration {
    4226          119 :         tenant_conf
    4227          119 :             .lsn_lease_length
    4228          119 :             .unwrap_or(conf.default_tenant_conf.lsn_lease_length)
    4229          119 :     }
    4230              : 
    4231            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4232            0 :         if self.conf.timeline_offloading {
    4233            0 :             return true;
    4234            0 :         }
    4235            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4236            0 :         tenant_conf
    4237            0 :             .timeline_offloading
    4238            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4239            0 :     }
    4240              : 
    4241              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4242          120 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4243              :         // Collect the offloaded timelines, and sort them for deterministic output.
    4244          120 :         let offloaded_timelines = self
    4245          120 :             .timelines_offloaded
    4246          120 :             .lock()
    4247          120 :             .unwrap()
    4248          120 :             .values()
    4249          120 :             .map(|tli| tli.manifest())
    4250          120 :             .sorted_by_key(|m| m.timeline_id)
    4251          120 :             .collect_vec();
    4252              : 
    4253          120 :         TenantManifest {
    4254          120 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4255          120 :             stripe_size: Some(self.get_shard_stripe_size()),
    4256          120 :             offloaded_timelines,
    4257          120 :         }
    4258          120 :     }
    4259              : 
    4260            1 :     pub fn update_tenant_config<
    4261            1 :         F: Fn(
    4262            1 :             pageserver_api::models::TenantConfig,
    4263            1 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4264            1 :     >(
    4265            1 :         &self,
    4266            1 :         update: F,
    4267            1 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4268              :         // Use read-copy-update in order to avoid overwriting the location config
    4269              :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4270              :         // this race is not possible if both request types come from the storage
    4271              :         // controller (as they should!) because an exclusive op lock is required
    4272              :         // on the storage controller side.
    4273              : 
    4274            1 :         self.tenant_conf
    4275            1 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4276            1 :                 Ok(Arc::new(AttachedTenantConf {
    4277            1 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4278            1 :                     location: attached_conf.location,
    4279            1 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4280              :                 }))
    4281            1 :             })?;
    4282              : 
    4283            1 :         let updated = self.tenant_conf.load();
    4284              : 
    4285            1 :         self.tenant_conf_updated(&updated.tenant_conf);
    4286              :         // Don't hold self.timelines.lock() during the notifies.
    4287              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4288              :         // mutexes in struct Timeline in the future.
    4289            1 :         let timelines = self.list_timelines();
    4290            1 :         for timeline in timelines {
    4291            0 :             timeline.tenant_conf_updated(&updated);
    4292            0 :         }
    4293              : 
    4294            1 :         Ok(updated.tenant_conf.clone())
    4295            1 :     }
    4296              : 
    4297            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4298            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4299              : 
    4300            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4301              : 
    4302            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4303              :         // Don't hold self.timelines.lock() during the notifies.
    4304              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4305              :         // mutexes in struct Timeline in the future.
    4306            0 :         let timelines = self.list_timelines();
    4307            0 :         for timeline in timelines {
    4308            0 :             timeline.tenant_conf_updated(&new_conf);
    4309            0 :         }
    4310            0 :     }
    4311              : 
    4312          120 :     fn get_pagestream_throttle_config(
    4313          120 :         psconf: &'static PageServerConf,
    4314          120 :         overrides: &pageserver_api::models::TenantConfig,
    4315          120 :     ) -> throttle::Config {
    4316          120 :         overrides
    4317          120 :             .timeline_get_throttle
    4318          120 :             .clone()
    4319          120 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4320          120 :     }
    4321              : 
    4322            1 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4323            1 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4324            1 :         self.pagestream_throttle.reconfigure(conf)
    4325            1 :     }
    4326              : 
    4327              :     /// Helper function to create a new Timeline struct.
    4328              :     ///
    4329              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4330              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4331              :     /// map.
    4332              :     ///
    4333              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4334              :     /// and we might not have the ancestor present anymore which is fine for to be
    4335              :     /// deleted timelines.
    4336              :     #[allow(clippy::too_many_arguments)]
    4337          235 :     fn create_timeline_struct(
    4338          235 :         &self,
    4339          235 :         new_timeline_id: TimelineId,
    4340          235 :         new_metadata: &TimelineMetadata,
    4341          235 :         previous_heatmap: Option<PreviousHeatmap>,
    4342          235 :         ancestor: Option<Arc<Timeline>>,
    4343          235 :         resources: TimelineResources,
    4344          235 :         cause: CreateTimelineCause,
    4345          235 :         create_idempotency: CreateTimelineIdempotency,
    4346          235 :         gc_compaction_state: Option<GcCompactionState>,
    4347          235 :         rel_size_v2_status: Option<RelSizeMigration>,
    4348          235 :         rel_size_migrated_at: Option<Lsn>,
    4349          235 :         ctx: &RequestContext,
    4350          235 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4351          235 :         let state = match cause {
    4352              :             CreateTimelineCause::Load => {
    4353          235 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4354          235 :                 anyhow::ensure!(
    4355          235 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4356            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4357              :                 );
    4358          235 :                 TimelineState::Loading
    4359              :             }
    4360            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4361              :         };
    4362              : 
    4363          235 :         let pg_version = new_metadata.pg_version();
    4364              : 
    4365          235 :         let timeline = Timeline::new(
    4366          235 :             self.conf,
    4367          235 :             Arc::clone(&self.tenant_conf),
    4368          235 :             new_metadata,
    4369          235 :             previous_heatmap,
    4370          235 :             ancestor,
    4371          235 :             new_timeline_id,
    4372          235 :             self.tenant_shard_id,
    4373          235 :             self.generation,
    4374          235 :             self.shard_identity,
    4375          235 :             self.walredo_mgr.clone(),
    4376          235 :             resources,
    4377          235 :             pg_version,
    4378          235 :             state,
    4379          235 :             self.attach_wal_lag_cooldown.clone(),
    4380          235 :             create_idempotency,
    4381          235 :             gc_compaction_state,
    4382          235 :             rel_size_v2_status,
    4383          235 :             rel_size_migrated_at,
    4384          235 :             self.cancel.child_token(),
    4385              :         );
    4386              : 
    4387          235 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4388          235 :             .scope(context::Scope::new_timeline(&timeline))
    4389          235 :             .detached_child();
    4390              : 
    4391          235 :         Ok((timeline, timeline_ctx))
    4392          235 :     }
    4393              : 
    4394              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4395              :     /// to ensure proper cleanup of background tasks and metrics.
    4396              :     //
    4397              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4398              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4399              :     #[allow(clippy::too_many_arguments)]
    4400          119 :     fn new(
    4401          119 :         state: TenantState,
    4402          119 :         conf: &'static PageServerConf,
    4403          119 :         attached_conf: AttachedTenantConf,
    4404          119 :         shard_identity: ShardIdentity,
    4405          119 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4406          119 :         tenant_shard_id: TenantShardId,
    4407          119 :         remote_storage: GenericRemoteStorage,
    4408          119 :         deletion_queue_client: DeletionQueueClient,
    4409          119 :         l0_flush_global_state: L0FlushGlobalState,
    4410          119 :         basebackup_cache: Arc<BasebackupCache>,
    4411          119 :         feature_resolver: FeatureResolver,
    4412          119 :     ) -> TenantShard {
    4413          119 :         assert!(!attached_conf.location.generation.is_none());
    4414              : 
    4415          119 :         let (state, mut rx) = watch::channel(state);
    4416              : 
    4417          119 :         tokio::spawn(async move {
    4418              :             // reflect tenant state in metrics:
    4419              :             // - global per tenant state: TENANT_STATE_METRIC
    4420              :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4421              :             //
    4422              :             // set of broken tenants should not have zero counts so that it remains accessible for
    4423              :             // alerting.
    4424              : 
    4425          119 :             let tid = tenant_shard_id.to_string();
    4426          119 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4427          119 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4428              : 
    4429          235 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4430          235 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4431          235 :             }
    4432              : 
    4433          119 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4434              : 
    4435          119 :             let is_broken = tuple.1;
    4436          119 :             let mut counted_broken = if is_broken {
    4437              :                 // add the id to the set right away, there should not be any updates on the channel
    4438              :                 // after before tenant is removed, if ever
    4439            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4440            0 :                 true
    4441              :             } else {
    4442          119 :                 false
    4443              :             };
    4444              : 
    4445              :             loop {
    4446          235 :                 let labels = &tuple.0;
    4447          235 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4448          235 :                 current.inc();
    4449              : 
    4450          235 :                 if rx.changed().await.is_err() {
    4451              :                     // tenant has been dropped
    4452            7 :                     current.dec();
    4453            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4454            7 :                     break;
    4455          116 :                 }
    4456              : 
    4457          116 :                 current.dec();
    4458          116 :                 tuple = inspect_state(&rx.borrow_and_update());
    4459              : 
    4460          116 :                 let is_broken = tuple.1;
    4461          116 :                 if is_broken && !counted_broken {
    4462            0 :                     counted_broken = true;
    4463            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4464            0 :                     // access
    4465            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4466          116 :                 }
    4467              :             }
    4468            7 :         });
    4469              : 
    4470          119 :         TenantShard {
    4471          119 :             tenant_shard_id,
    4472          119 :             shard_identity,
    4473          119 :             generation: attached_conf.location.generation,
    4474          119 :             conf,
    4475          119 :             // using now here is good enough approximation to catch tenants with really long
    4476          119 :             // activation times.
    4477          119 :             constructed_at: Instant::now(),
    4478          119 :             timelines: Mutex::new(HashMap::new()),
    4479          119 :             timelines_creating: Mutex::new(HashSet::new()),
    4480          119 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4481          119 :             timelines_importing: Mutex::new(HashMap::new()),
    4482          119 :             remote_tenant_manifest: Default::default(),
    4483          119 :             gc_cs: tokio::sync::Mutex::new(()),
    4484          119 :             walredo_mgr,
    4485          119 :             remote_storage,
    4486          119 :             deletion_queue_client,
    4487          119 :             state,
    4488          119 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4489          119 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4490          119 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4491          119 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4492          119 :                 format!("compaction-{tenant_shard_id}"),
    4493          119 :                 5,
    4494          119 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4495          119 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4496          119 :                 // use an extremely long backoff.
    4497          119 :                 Some(Duration::from_secs(3600 * 24)),
    4498          119 :             )),
    4499          119 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4500          119 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4501          119 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4502          119 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4503          119 :             cancel: CancellationToken::default(),
    4504          119 :             gate: Gate::default(),
    4505          119 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4506          119 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4507          119 :             )),
    4508          119 :             pagestream_throttle_metrics: Arc::new(
    4509          119 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4510          119 :             ),
    4511          119 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4512          119 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4513          119 :             gc_block: Default::default(),
    4514          119 :             l0_flush_global_state,
    4515          119 :             basebackup_cache,
    4516          119 :             feature_resolver: Arc::new(TenantFeatureResolver::new(
    4517          119 :                 feature_resolver,
    4518          119 :                 tenant_shard_id.tenant_id,
    4519          119 :             )),
    4520          119 :         }
    4521          119 :     }
    4522              : 
    4523              :     /// Locate and load config
    4524            0 :     pub(super) fn load_tenant_config(
    4525            0 :         conf: &'static PageServerConf,
    4526            0 :         tenant_shard_id: &TenantShardId,
    4527            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4528            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4529              : 
    4530            0 :         info!("loading tenant configuration from {config_path}");
    4531              : 
    4532              :         // load and parse file
    4533            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4534            0 :             match e.kind() {
    4535              :                 std::io::ErrorKind::NotFound => {
    4536              :                     // The config should almost always exist for a tenant directory:
    4537              :                     //  - When attaching a tenant, the config is the first thing we write
    4538              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4539              :                     //    before deleting contents.
    4540              :                     //
    4541              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4542              :                     // between creating directory and writing config.  Callers should handle that as if the
    4543              :                     // directory didn't exist.
    4544              : 
    4545            0 :                     LoadConfigError::NotFound(config_path)
    4546              :                 }
    4547              :                 _ => {
    4548              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4549              :                     // that we cannot cleanly recover
    4550            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4551              :                 }
    4552              :             }
    4553            0 :         })?;
    4554              : 
    4555            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4556            0 :     }
    4557              : 
    4558              :     /// Stores a tenant location config to disk.
    4559              :     ///
    4560              :     /// NB: make sure to call `ShardIdentity::assert_equal` before persisting a new config, to avoid
    4561              :     /// changes to shard parameters that may result in data corruption.
    4562              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4563              :     pub(super) async fn persist_tenant_config(
    4564              :         conf: &'static PageServerConf,
    4565              :         tenant_shard_id: &TenantShardId,
    4566              :         location_conf: &LocationConf,
    4567              :     ) -> std::io::Result<()> {
    4568              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4569              : 
    4570              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4571              :     }
    4572              : 
    4573              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4574              :     pub(super) async fn persist_tenant_config_at(
    4575              :         tenant_shard_id: &TenantShardId,
    4576              :         config_path: &Utf8Path,
    4577              :         location_conf: &LocationConf,
    4578              :     ) -> std::io::Result<()> {
    4579              :         debug!("persisting tenantconf to {config_path}");
    4580              : 
    4581              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4582              : #  It is read in case of pageserver restart.
    4583              : "#
    4584              :         .to_string();
    4585              : 
    4586            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4587            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4588            0 :         });
    4589              : 
    4590              :         // Convert the config to a toml file.
    4591              :         conf_content +=
    4592              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4593              : 
    4594              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4595              : 
    4596              :         let conf_content = conf_content.into_bytes();
    4597              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4598              :     }
    4599              : 
    4600              :     //
    4601              :     // How garbage collection works:
    4602              :     //
    4603              :     //                    +--bar------------->
    4604              :     //                   /
    4605              :     //             +----+-----foo---------------->
    4606              :     //            /
    4607              :     // ----main--+-------------------------->
    4608              :     //                \
    4609              :     //                 +-----baz-------->
    4610              :     //
    4611              :     //
    4612              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4613              :     //    `gc_infos` are being refreshed
    4614              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4615              :     //    all the points where other timelines have been branched off.
    4616              :     //    We will refrain from removing page versions at those LSNs.
    4617              :     // 3. For each timeline, scan all layer files on the timeline.
    4618              :     //    Remove all files for which a newer file exists and which
    4619              :     //    don't cover any branch point LSNs.
    4620              :     //
    4621              :     // TODO:
    4622              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4623              :     //   don't need to keep that in the parent anymore. But currently
    4624              :     //   we do.
    4625          377 :     async fn gc_iteration_internal(
    4626          377 :         &self,
    4627          377 :         target_timeline_id: Option<TimelineId>,
    4628          377 :         horizon: u64,
    4629          377 :         pitr: Duration,
    4630          377 :         cancel: &CancellationToken,
    4631          377 :         ctx: &RequestContext,
    4632          377 :     ) -> Result<GcResult, GcError> {
    4633          377 :         let mut totals: GcResult = Default::default();
    4634          377 :         let now = Instant::now();
    4635              : 
    4636          377 :         let gc_timelines = self
    4637          377 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4638          377 :             .await?;
    4639              : 
    4640          377 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4641              : 
    4642              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4643          377 :         if !gc_timelines.is_empty() {
    4644          377 :             info!("{} timelines need GC", gc_timelines.len());
    4645              :         } else {
    4646            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4647              :         }
    4648              : 
    4649              :         // Perform GC for each timeline.
    4650              :         //
    4651              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4652              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4653              :         // with branch creation.
    4654              :         //
    4655              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4656              :         // creation task can run concurrently with timeline's GC iteration.
    4657          754 :         for timeline in gc_timelines {
    4658          377 :             if cancel.is_cancelled() {
    4659              :                 // We were requested to shut down. Stop and return with the progress we
    4660              :                 // made.
    4661            0 :                 break;
    4662          377 :             }
    4663          377 :             let result = match timeline.gc().await {
    4664              :                 Err(GcError::TimelineCancelled) => {
    4665            0 :                     if target_timeline_id.is_some() {
    4666              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4667            0 :                         return Err(GcError::TimelineCancelled);
    4668              :                     } else {
    4669              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4670              :                         // skip past this and proceed to try GC on other timelines.
    4671            0 :                         continue;
    4672              :                     }
    4673              :                 }
    4674          377 :                 r => r?,
    4675              :             };
    4676          377 :             totals += result;
    4677              :         }
    4678              : 
    4679          377 :         totals.elapsed = now.elapsed();
    4680          377 :         Ok(totals)
    4681          377 :     }
    4682              : 
    4683              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4684              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4685              :     /// [`TenantShard::get_gc_horizon`].
    4686              :     ///
    4687              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4688            2 :     pub(crate) async fn refresh_gc_info(
    4689            2 :         &self,
    4690            2 :         cancel: &CancellationToken,
    4691            2 :         ctx: &RequestContext,
    4692            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4693              :         // since this method can now be called at different rates than the configured gc loop, it
    4694              :         // might be that these configuration values get applied faster than what it was previously,
    4695              :         // since these were only read from the gc task.
    4696            2 :         let horizon = self.get_gc_horizon();
    4697            2 :         let pitr = self.get_pitr_interval();
    4698              : 
    4699              :         // refresh all timelines
    4700            2 :         let target_timeline_id = None;
    4701              : 
    4702            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4703            2 :             .await
    4704            2 :     }
    4705              : 
    4706              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4707              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4708              :     ///
    4709              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4710          119 :     fn initialize_gc_info(
    4711          119 :         &self,
    4712          119 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4713          119 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4714          119 :         restrict_to_timeline: Option<TimelineId>,
    4715          119 :     ) {
    4716          119 :         if restrict_to_timeline.is_none() {
    4717              :             // This function must be called before activation: after activation timeline create/delete operations
    4718              :             // might happen, and this function is not safe to run concurrently with those.
    4719          119 :             assert!(!self.is_active());
    4720            0 :         }
    4721              : 
    4722              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4723              :         // the branch point where it was created.
    4724          119 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4725          119 :             BTreeMap::new();
    4726          119 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4727            3 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4728            1 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4729            1 :                 ancestor_children.push((
    4730            1 :                     timeline_entry.get_ancestor_lsn(),
    4731            1 :                     *timeline_id,
    4732            1 :                     MaybeOffloaded::No,
    4733            1 :                 ));
    4734            2 :             }
    4735            3 :         });
    4736          119 :         timelines_offloaded
    4737          119 :             .iter()
    4738          119 :             .for_each(|(timeline_id, timeline_entry)| {
    4739            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4740            0 :                     return;
    4741              :                 };
    4742            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4743            0 :                     return;
    4744              :                 };
    4745            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4746            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4747            0 :             });
    4748              : 
    4749              :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4750          119 :         let horizon = self.get_gc_horizon();
    4751              : 
    4752              :         // Populate each timeline's GcInfo with information about its child branches
    4753          119 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4754            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4755              :         } else {
    4756          119 :             itertools::Either::Right(timelines.values())
    4757              :         };
    4758          122 :         for timeline in timelines_to_write {
    4759            3 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4760            3 :                 .remove(&timeline.timeline_id)
    4761            3 :                 .unwrap_or_default();
    4762              : 
    4763            3 :             branchpoints.sort_by_key(|b| b.0);
    4764              : 
    4765            3 :             let mut target = timeline.gc_info.write().unwrap();
    4766              : 
    4767            3 :             target.retain_lsns = branchpoints;
    4768              : 
    4769            3 :             let space_cutoff = timeline
    4770            3 :                 .get_last_record_lsn()
    4771            3 :                 .checked_sub(horizon)
    4772            3 :                 .unwrap_or(Lsn(0));
    4773              : 
    4774            3 :             target.cutoffs = GcCutoffs {
    4775            3 :                 space: space_cutoff,
    4776            3 :                 time: None,
    4777            3 :             };
    4778              :         }
    4779          119 :     }
    4780              : 
    4781          379 :     async fn refresh_gc_info_internal(
    4782          379 :         &self,
    4783          379 :         target_timeline_id: Option<TimelineId>,
    4784          379 :         horizon: u64,
    4785          379 :         pitr: Duration,
    4786          379 :         cancel: &CancellationToken,
    4787          379 :         ctx: &RequestContext,
    4788          379 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4789              :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4790              :         // currently visible timelines.
    4791          379 :         let timelines = self
    4792          379 :             .timelines
    4793          379 :             .lock()
    4794          379 :             .unwrap()
    4795          379 :             .values()
    4796         1663 :             .filter(|tl| match target_timeline_id.as_ref() {
    4797         1655 :                 Some(target) => &tl.timeline_id == target,
    4798            8 :                 None => true,
    4799         1663 :             })
    4800          379 :             .cloned()
    4801          379 :             .collect::<Vec<_>>();
    4802              : 
    4803          379 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4804              :             // We were to act on a particular timeline and it wasn't found
    4805            0 :             return Err(GcError::TimelineNotFound);
    4806          379 :         }
    4807              : 
    4808          379 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4809          379 :             HashMap::with_capacity(timelines.len());
    4810              : 
    4811              :         // Ensures all timelines use the same start time when computing the time cutoff.
    4812          379 :         let now_ts_for_pitr_calc = SystemTime::now();
    4813          385 :         for timeline in timelines.iter() {
    4814          385 :             let ctx = &ctx.with_scope_timeline(timeline);
    4815          385 :             let cutoff = timeline
    4816          385 :                 .get_last_record_lsn()
    4817          385 :                 .checked_sub(horizon)
    4818          385 :                 .unwrap_or(Lsn(0));
    4819              : 
    4820          385 :             let cutoffs = timeline
    4821          385 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4822          385 :                 .await?;
    4823          385 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4824          385 :             assert!(old.is_none());
    4825              :         }
    4826              : 
    4827          379 :         if !self.is_active() || self.cancel.is_cancelled() {
    4828            0 :             return Err(GcError::TenantCancelled);
    4829          379 :         }
    4830              : 
    4831              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4832              :         // because that will stall branch creation.
    4833          379 :         let gc_cs = self.gc_cs.lock().await;
    4834              : 
    4835              :         // Ok, we now know all the branch points.
    4836              :         // Update the GC information for each timeline.
    4837          379 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4838          764 :         for timeline in timelines {
    4839              :             // We filtered the timeline list above
    4840          385 :             if let Some(target_timeline_id) = target_timeline_id {
    4841          377 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4842            8 :             }
    4843              : 
    4844              :             {
    4845          385 :                 let mut target = timeline.gc_info.write().unwrap();
    4846              : 
    4847              :                 // Cull any expired leases
    4848          385 :                 let now = SystemTime::now();
    4849          385 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4850              : 
    4851          385 :                 timeline
    4852          385 :                     .metrics
    4853          385 :                     .valid_lsn_lease_count_gauge
    4854          385 :                     .set(target.leases.len() as u64);
    4855              : 
    4856              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4857          385 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4858           56 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4859            6 :                         target.within_ancestor_pitr =
    4860            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4861           50 :                     }
    4862          329 :                 }
    4863              : 
    4864              :                 // Update metrics that depend on GC state
    4865          385 :                 timeline
    4866          385 :                     .metrics
    4867          385 :                     .archival_size
    4868          385 :                     .set(if target.within_ancestor_pitr {
    4869            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4870              :                     } else {
    4871          385 :                         0
    4872              :                     });
    4873          385 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4874          319 :                     timeline.metrics.pitr_history_size.set(
    4875          319 :                         timeline
    4876          319 :                             .get_last_record_lsn()
    4877          319 :                             .checked_sub(time_cutoff)
    4878          319 :                             .unwrap_or_default()
    4879          319 :                             .0,
    4880          319 :                     );
    4881          319 :                 }
    4882              : 
    4883              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4884              :                 // - this timeline was created while we were finding cutoffs
    4885              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4886          385 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4887          385 :                     let original_cutoffs = target.cutoffs.clone();
    4888              :                     // GC cutoffs should never go back
    4889          385 :                     target.cutoffs = GcCutoffs {
    4890          385 :                         space: cutoffs.space.max(original_cutoffs.space),
    4891          385 :                         time: cutoffs.time.max(original_cutoffs.time),
    4892          385 :                     }
    4893            0 :                 }
    4894              :             }
    4895              : 
    4896          385 :             gc_timelines.push(timeline);
    4897              :         }
    4898          379 :         drop(gc_cs);
    4899          379 :         Ok(gc_timelines)
    4900          379 :     }
    4901              : 
    4902              :     /// A substitute for `branch_timeline` for use in unit tests.
    4903              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4904              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4905              :     /// timeline background tasks are launched, except the flush loop.
    4906              :     #[cfg(test)]
    4907          119 :     async fn branch_timeline_test(
    4908          119 :         self: &Arc<Self>,
    4909          119 :         src_timeline: &Arc<Timeline>,
    4910          119 :         dst_id: TimelineId,
    4911          119 :         ancestor_lsn: Option<Lsn>,
    4912          119 :         ctx: &RequestContext,
    4913          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4914          119 :         let tl = self
    4915          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4916          119 :             .await?
    4917          117 :             .into_timeline_for_test();
    4918          117 :         tl.set_state(TimelineState::Active);
    4919          117 :         Ok(tl)
    4920          119 :     }
    4921              : 
    4922              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4923              :     #[cfg(test)]
    4924              :     #[allow(clippy::too_many_arguments)]
    4925            6 :     pub async fn branch_timeline_test_with_layers(
    4926            6 :         self: &Arc<Self>,
    4927            6 :         src_timeline: &Arc<Timeline>,
    4928            6 :         dst_id: TimelineId,
    4929            6 :         ancestor_lsn: Option<Lsn>,
    4930            6 :         ctx: &RequestContext,
    4931            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4932            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4933            6 :         end_lsn: Lsn,
    4934            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4935              :         use checks::check_valid_layermap;
    4936              :         use itertools::Itertools;
    4937              : 
    4938            6 :         let tline = self
    4939            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4940            6 :             .await?;
    4941            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4942            6 :             ancestor_lsn
    4943              :         } else {
    4944            0 :             tline.get_last_record_lsn()
    4945              :         };
    4946            6 :         assert!(end_lsn >= ancestor_lsn);
    4947            6 :         tline.force_advance_lsn(end_lsn);
    4948            9 :         for deltas in delta_layer_desc {
    4949            3 :             tline
    4950            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4951            3 :                 .await?;
    4952              :         }
    4953            8 :         for (lsn, images) in image_layer_desc {
    4954            2 :             tline
    4955            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4956            2 :                 .await?;
    4957              :         }
    4958            6 :         let layer_names = tline
    4959            6 :             .layers
    4960            6 :             .read(LayerManagerLockHolder::Testing)
    4961            6 :             .await
    4962            6 :             .layer_map()
    4963            6 :             .unwrap()
    4964            6 :             .iter_historic_layers()
    4965            6 :             .map(|layer| layer.layer_name())
    4966            6 :             .collect_vec();
    4967            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4968            0 :             bail!("invalid layermap: {err}");
    4969            6 :         }
    4970            6 :         Ok(tline)
    4971            6 :     }
    4972              : 
    4973              :     /// Branch an existing timeline.
    4974            0 :     async fn branch_timeline(
    4975            0 :         self: &Arc<Self>,
    4976            0 :         src_timeline: &Arc<Timeline>,
    4977            0 :         dst_id: TimelineId,
    4978            0 :         start_lsn: Option<Lsn>,
    4979            0 :         ctx: &RequestContext,
    4980            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4981            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4982            0 :             .await
    4983            0 :     }
    4984              : 
    4985          119 :     async fn branch_timeline_impl(
    4986          119 :         self: &Arc<Self>,
    4987          119 :         src_timeline: &Arc<Timeline>,
    4988          119 :         dst_id: TimelineId,
    4989          119 :         start_lsn: Option<Lsn>,
    4990          119 :         ctx: &RequestContext,
    4991          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4992          119 :         let src_id = src_timeline.timeline_id;
    4993              : 
    4994              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4995              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4996              :         // valid while we are creating the branch.
    4997          119 :         let _gc_cs = self.gc_cs.lock().await;
    4998              : 
    4999              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    5000          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    5001            1 :             let lsn = src_timeline.get_last_record_lsn();
    5002            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    5003            1 :             lsn
    5004            1 :         });
    5005              : 
    5006              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    5007          119 :         let timeline_create_guard = match self
    5008          119 :             .start_creating_timeline(
    5009          119 :                 dst_id,
    5010          119 :                 CreateTimelineIdempotency::Branch {
    5011          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    5012          119 :                     ancestor_start_lsn: start_lsn,
    5013          119 :                 },
    5014          119 :             )
    5015          119 :             .await?
    5016              :         {
    5017          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5018            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5019            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5020              :             }
    5021              :         };
    5022              : 
    5023              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    5024              :         // horizon on the source timeline
    5025              :         //
    5026              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    5027              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    5028              :         // planned GC cutoff in 'gc_info' is normally larger than
    5029              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    5030              :         // changed the GC settings for the tenant to make the PITR window
    5031              :         // larger, but some of the data was already removed by an earlier GC
    5032              :         // iteration.
    5033              : 
    5034              :         // check against last actual 'latest_gc_cutoff' first
    5035          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    5036              :         {
    5037          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    5038          119 :             let planned_cutoff = gc_info.min_cutoff();
    5039          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    5040            0 :                 tracing::info!(
    5041            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    5042            0 :                     *applied_gc_cutoff_lsn
    5043              :                 );
    5044              :             } else {
    5045          119 :                 src_timeline
    5046          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    5047          119 :                     .context(format!(
    5048          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    5049          119 :                         *applied_gc_cutoff_lsn,
    5050              :                     ))
    5051          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    5052              : 
    5053              :                 // and then the planned GC cutoff
    5054          117 :                 if start_lsn < planned_cutoff {
    5055            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    5056            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    5057            0 :                     )));
    5058          117 :                 }
    5059              :             }
    5060              :         }
    5061              : 
    5062              :         //
    5063              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    5064              :         // so that GC cannot advance the GC cutoff until we are finished.
    5065              :         // Proceed with the branch creation.
    5066              :         //
    5067              : 
    5068              :         // Determine prev-LSN for the new timeline. We can only determine it if
    5069              :         // the timeline was branched at the current end of the source timeline.
    5070              :         let RecordLsn {
    5071          117 :             last: src_last,
    5072          117 :             prev: src_prev,
    5073          117 :         } = src_timeline.get_last_record_rlsn();
    5074          117 :         let dst_prev = if src_last == start_lsn {
    5075          108 :             Some(src_prev)
    5076              :         } else {
    5077            9 :             None
    5078              :         };
    5079              : 
    5080              :         // Create the metadata file, noting the ancestor of the new timeline.
    5081              :         // There is initially no data in it, but all the read-calls know to look
    5082              :         // into the ancestor.
    5083          117 :         let metadata = TimelineMetadata::new(
    5084          117 :             start_lsn,
    5085          117 :             dst_prev,
    5086          117 :             Some(src_id),
    5087          117 :             start_lsn,
    5088          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    5089          117 :             src_timeline.initdb_lsn,
    5090          117 :             src_timeline.pg_version,
    5091              :         );
    5092              : 
    5093          117 :         let (rel_size_v2_status, rel_size_migrated_at) = src_timeline.get_rel_size_v2_status();
    5094          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    5095          117 :             .prepare_new_timeline(
    5096          117 :                 dst_id,
    5097          117 :                 &metadata,
    5098          117 :                 timeline_create_guard,
    5099          117 :                 start_lsn + 1,
    5100          117 :                 Some(Arc::clone(src_timeline)),
    5101          117 :                 Some(rel_size_v2_status),
    5102          117 :                 rel_size_migrated_at,
    5103          117 :                 ctx,
    5104          117 :             )
    5105          117 :             .await?;
    5106              : 
    5107          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    5108              : 
    5109              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    5110              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    5111              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    5112              :         // could get incorrect information and remove more layers, than needed.
    5113              :         // See also https://github.com/neondatabase/neon/issues/3865
    5114          117 :         new_timeline
    5115          117 :             .remote_client
    5116          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    5117          117 :             .context("branch initial metadata upload")?;
    5118              : 
    5119              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5120              : 
    5121          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    5122          119 :     }
    5123              : 
    5124              :     /// For unit tests, make this visible so that other modules can directly create timelines
    5125              :     #[cfg(test)]
    5126              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    5127              :     pub(crate) async fn bootstrap_timeline_test(
    5128              :         self: &Arc<Self>,
    5129              :         timeline_id: TimelineId,
    5130              :         pg_version: PgMajorVersion,
    5131              :         load_existing_initdb: Option<TimelineId>,
    5132              :         ctx: &RequestContext,
    5133              :     ) -> anyhow::Result<Arc<Timeline>> {
    5134              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    5135              :             .await
    5136              :             .map_err(anyhow::Error::new)
    5137            1 :             .map(|r| r.into_timeline_for_test())
    5138              :     }
    5139              : 
    5140              :     /// Get exclusive access to the timeline ID for creation.
    5141              :     ///
    5142              :     /// Timeline-creating code paths must use this function before making changes
    5143              :     /// to in-memory or persistent state.
    5144              :     ///
    5145              :     /// The `state` parameter is a description of the timeline creation operation
    5146              :     /// we intend to perform.
    5147              :     /// If the timeline was already created in the meantime, we check whether this
    5148              :     /// request conflicts or is idempotent , based on `state`.
    5149          235 :     async fn start_creating_timeline(
    5150          235 :         self: &Arc<Self>,
    5151          235 :         new_timeline_id: TimelineId,
    5152          235 :         idempotency: CreateTimelineIdempotency,
    5153          235 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    5154          235 :         let allow_offloaded = false;
    5155          235 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    5156          234 :             Ok(create_guard) => {
    5157          234 :                 pausable_failpoint!("timeline-creation-after-uninit");
    5158          234 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    5159              :             }
    5160            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    5161              :             Err(TimelineExclusionError::AlreadyCreating) => {
    5162              :                 // Creation is in progress, we cannot create it again, and we cannot
    5163              :                 // check if this request matches the existing one, so caller must try
    5164              :                 // again later.
    5165            0 :                 Err(CreateTimelineError::AlreadyCreating)
    5166              :             }
    5167            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    5168              :             Err(TimelineExclusionError::AlreadyExists {
    5169            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5170              :                 ..
    5171              :             }) => {
    5172            0 :                 info!("timeline already exists but is offloaded");
    5173            0 :                 Err(CreateTimelineError::Conflict)
    5174              :             }
    5175              :             Err(TimelineExclusionError::AlreadyExists {
    5176            0 :                 existing: TimelineOrOffloaded::Importing(_existing),
    5177              :                 ..
    5178              :             }) => {
    5179              :                 // If there's a timeline already importing, then we would hit
    5180              :                 // the [`TimelineExclusionError::AlreadyCreating`] branch above.
    5181            0 :                 unreachable!("Importing timelines hold the creation guard")
    5182              :             }
    5183              :             Err(TimelineExclusionError::AlreadyExists {
    5184            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5185            1 :                 arg,
    5186              :             }) => {
    5187              :                 {
    5188            1 :                     let existing = &existing.create_idempotency;
    5189            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5190            1 :                     debug!("timeline already exists");
    5191              : 
    5192            1 :                     match (existing, &arg) {
    5193              :                         // FailWithConflict => no idempotency check
    5194              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5195              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5196            1 :                             warn!("timeline already exists, failing request");
    5197            1 :                             return Err(CreateTimelineError::Conflict);
    5198              :                         }
    5199              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5200            0 :                         (x, y) if x == y => {
    5201            0 :                             info!(
    5202            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5203              :                             );
    5204              :                             // fallthrough
    5205              :                         }
    5206              :                         (_, _) => {
    5207            0 :                             warn!("idempotency conflict, failing request");
    5208            0 :                             return Err(CreateTimelineError::Conflict);
    5209              :                         }
    5210              :                     }
    5211              :                 }
    5212              : 
    5213            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5214              :             }
    5215              :         }
    5216          235 :     }
    5217              : 
    5218            0 :     async fn upload_initdb(
    5219            0 :         &self,
    5220            0 :         timelines_path: &Utf8PathBuf,
    5221            0 :         pgdata_path: &Utf8PathBuf,
    5222            0 :         timeline_id: &TimelineId,
    5223            0 :     ) -> anyhow::Result<()> {
    5224            0 :         let temp_path = timelines_path.join(format!(
    5225            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5226            0 :         ));
    5227              : 
    5228            0 :         scopeguard::defer! {
    5229              :             if let Err(e) = fs::remove_file(&temp_path) {
    5230              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5231              :             }
    5232              :         }
    5233              : 
    5234            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5235              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5236            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5237            0 :             warn!(
    5238            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5239              :             );
    5240            0 :         }
    5241              : 
    5242            0 :         pausable_failpoint!("before-initdb-upload");
    5243              : 
    5244            0 :         backoff::retry(
    5245            0 :             || async {
    5246            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5247            0 :                     &self.remote_storage,
    5248            0 :                     &self.tenant_shard_id.tenant_id,
    5249            0 :                     timeline_id,
    5250            0 :                     pgdata_zstd.try_clone().await?,
    5251            0 :                     tar_zst_size,
    5252            0 :                     &self.cancel,
    5253              :                 )
    5254            0 :                 .await
    5255            0 :             },
    5256              :             |_| false,
    5257              :             3,
    5258              :             u32::MAX,
    5259            0 :             "persist_initdb_tar_zst",
    5260            0 :             &self.cancel,
    5261              :         )
    5262            0 :         .await
    5263            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5264            0 :         .and_then(|x| x)
    5265            0 :     }
    5266              : 
    5267              :     /// - run initdb to init temporary instance and get bootstrap data
    5268              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5269            1 :     async fn bootstrap_timeline(
    5270            1 :         self: &Arc<Self>,
    5271            1 :         timeline_id: TimelineId,
    5272            1 :         pg_version: PgMajorVersion,
    5273            1 :         load_existing_initdb: Option<TimelineId>,
    5274            1 :         ctx: &RequestContext,
    5275            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5276            1 :         let timeline_create_guard = match self
    5277            1 :             .start_creating_timeline(
    5278            1 :                 timeline_id,
    5279            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5280            1 :             )
    5281            1 :             .await?
    5282              :         {
    5283            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5284            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5285            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5286              :             }
    5287              :         };
    5288              : 
    5289              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5290              :         // temporary directory for basebackup files for the given timeline.
    5291              : 
    5292            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5293            1 :         let pgdata_path = path_with_suffix_extension(
    5294            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5295            1 :             TEMP_FILE_SUFFIX,
    5296              :         );
    5297              : 
    5298              :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5299              :         // we won't race with other creations or existent timelines with the same path.
    5300            1 :         if pgdata_path.exists() {
    5301            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5302            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5303            0 :             })?;
    5304            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5305            1 :         }
    5306              : 
    5307              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5308            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5309            1 :         scopeguard::defer! {
    5310              :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5311              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5312              :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5313              :             } else {
    5314              :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5315              :             }
    5316              :         }
    5317            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5318            1 :             if existing_initdb_timeline_id != timeline_id {
    5319            0 :                 let source_path = &remote_initdb_archive_path(
    5320            0 :                     &self.tenant_shard_id.tenant_id,
    5321            0 :                     &existing_initdb_timeline_id,
    5322            0 :                 );
    5323            0 :                 let dest_path =
    5324            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5325              : 
    5326              :                 // if this fails, it will get retried by retried control plane requests
    5327            0 :                 self.remote_storage
    5328            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5329            0 :                     .await
    5330            0 :                     .context("copy initdb tar")?;
    5331            1 :             }
    5332            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5333            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5334            1 :                     self.conf,
    5335            1 :                     &self.remote_storage,
    5336            1 :                     &self.tenant_shard_id,
    5337            1 :                     &existing_initdb_timeline_id,
    5338            1 :                     &self.cancel,
    5339            1 :                 )
    5340            1 :                 .await
    5341            1 :                 .context("download initdb tar")?;
    5342              : 
    5343            1 :             scopeguard::defer! {
    5344              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5345              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5346              :                 }
    5347              :             }
    5348              : 
    5349            1 :             let buf_read =
    5350            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5351            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5352            1 :                 .await
    5353            1 :                 .context("extract initdb tar")?;
    5354              :         } else {
    5355              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5356            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5357            0 :                 .await
    5358            0 :                 .context("run initdb")?;
    5359              : 
    5360              :             // Upload the created data dir to S3
    5361            0 :             if self.tenant_shard_id().is_shard_zero() {
    5362            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5363            0 :                     .await?;
    5364            0 :             }
    5365              :         }
    5366            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5367              : 
    5368              :         // Import the contents of the data directory at the initial checkpoint
    5369              :         // LSN, and any WAL after that.
    5370              :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5371              :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5372            1 :         let new_metadata = TimelineMetadata::new(
    5373            1 :             Lsn(0),
    5374            1 :             None,
    5375            1 :             None,
    5376            1 :             Lsn(0),
    5377            1 :             pgdata_lsn,
    5378            1 :             pgdata_lsn,
    5379            1 :             pg_version,
    5380              :         );
    5381            1 :         let (mut raw_timeline, timeline_ctx) = self
    5382            1 :             .prepare_new_timeline(
    5383            1 :                 timeline_id,
    5384            1 :                 &new_metadata,
    5385            1 :                 timeline_create_guard,
    5386            1 :                 pgdata_lsn,
    5387            1 :                 None,
    5388            1 :                 None,
    5389            1 :                 None,
    5390            1 :                 ctx,
    5391            1 :             )
    5392            1 :             .await?;
    5393              : 
    5394            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5395            1 :         raw_timeline
    5396            1 :             .write(|unfinished_timeline| async move {
    5397            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5398            1 :                     &unfinished_timeline,
    5399            1 :                     &pgdata_path,
    5400            1 :                     pgdata_lsn,
    5401            1 :                     &timeline_ctx,
    5402            1 :                 )
    5403            1 :                 .await
    5404            1 :                 .with_context(|| {
    5405            0 :                     format!(
    5406            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5407              :                     )
    5408            0 :                 })?;
    5409              : 
    5410            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5411            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5412            0 :                         "failpoint before-checkpoint-new-timeline"
    5413            0 :                     )))
    5414            0 :                 });
    5415              : 
    5416            1 :                 Ok(())
    5417            2 :             })
    5418            1 :             .await?;
    5419              : 
    5420              :         // All done!
    5421            1 :         let timeline = raw_timeline.finish_creation().await?;
    5422              : 
    5423              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5424              : 
    5425            1 :         Ok(CreateTimelineResult::Created(timeline))
    5426            1 :     }
    5427              : 
    5428          232 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5429          232 :         RemoteTimelineClient::new(
    5430          232 :             self.remote_storage.clone(),
    5431          232 :             self.deletion_queue_client.clone(),
    5432          232 :             self.conf,
    5433          232 :             self.tenant_shard_id,
    5434          232 :             timeline_id,
    5435          232 :             self.generation,
    5436          232 :             &self.tenant_conf.load().location,
    5437              :         )
    5438          232 :     }
    5439              : 
    5440              :     /// Builds required resources for a new timeline.
    5441          232 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5442          232 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5443          232 :         self.get_timeline_resources_for(remote_client)
    5444          232 :     }
    5445              : 
    5446              :     /// Builds timeline resources for the given remote client.
    5447          235 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5448          235 :         TimelineResources {
    5449          235 :             remote_client,
    5450          235 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5451          235 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5452          235 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5453          235 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5454          235 :             basebackup_cache: self.basebackup_cache.clone(),
    5455          235 :             feature_resolver: self.feature_resolver.clone(),
    5456          235 :         }
    5457          235 :     }
    5458              : 
    5459              :     /// Creates intermediate timeline structure and its files.
    5460              :     ///
    5461              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5462              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5463              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5464              :     #[allow(clippy::too_many_arguments)]
    5465          232 :     async fn prepare_new_timeline<'a>(
    5466          232 :         &'a self,
    5467          232 :         new_timeline_id: TimelineId,
    5468          232 :         new_metadata: &TimelineMetadata,
    5469          232 :         create_guard: TimelineCreateGuard,
    5470          232 :         start_lsn: Lsn,
    5471          232 :         ancestor: Option<Arc<Timeline>>,
    5472          232 :         rel_size_v2_status: Option<RelSizeMigration>,
    5473          232 :         rel_size_migrated_at: Option<Lsn>,
    5474          232 :         ctx: &RequestContext,
    5475          232 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5476          232 :         let tenant_shard_id = self.tenant_shard_id;
    5477              : 
    5478          232 :         let resources = self.build_timeline_resources(new_timeline_id);
    5479          232 :         resources.remote_client.init_upload_queue_for_empty_remote(
    5480          232 :             new_metadata,
    5481          232 :             rel_size_v2_status.clone(),
    5482          232 :             rel_size_migrated_at,
    5483            0 :         )?;
    5484              : 
    5485          232 :         let (timeline_struct, timeline_ctx) = self
    5486          232 :             .create_timeline_struct(
    5487          232 :                 new_timeline_id,
    5488          232 :                 new_metadata,
    5489          232 :                 None,
    5490          232 :                 ancestor,
    5491          232 :                 resources,
    5492          232 :                 CreateTimelineCause::Load,
    5493          232 :                 create_guard.idempotency.clone(),
    5494          232 :                 None,
    5495          232 :                 rel_size_v2_status,
    5496          232 :                 rel_size_migrated_at,
    5497          232 :                 ctx,
    5498              :             )
    5499          232 :             .context("Failed to create timeline data structure")?;
    5500              : 
    5501          232 :         timeline_struct.init_empty_layer_map(start_lsn);
    5502              : 
    5503          232 :         if let Err(e) = self
    5504          232 :             .create_timeline_files(&create_guard.timeline_path)
    5505          232 :             .await
    5506              :         {
    5507            0 :             error!(
    5508            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5509              :             );
    5510            0 :             cleanup_timeline_directory(create_guard);
    5511            0 :             return Err(e);
    5512          232 :         }
    5513              : 
    5514          232 :         debug!(
    5515            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5516              :         );
    5517              : 
    5518          232 :         Ok((
    5519          232 :             UninitializedTimeline::new(
    5520          232 :                 self,
    5521          232 :                 new_timeline_id,
    5522          232 :                 Some((timeline_struct, create_guard)),
    5523          232 :             ),
    5524          232 :             timeline_ctx,
    5525          232 :         ))
    5526          232 :     }
    5527              : 
    5528          232 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5529          232 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5530              : 
    5531          232 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5532            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5533            0 :         });
    5534              : 
    5535          232 :         Ok(())
    5536          232 :     }
    5537              : 
    5538              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5539              :     /// concurrent attempts to create the same timeline.
    5540              :     ///
    5541              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5542              :     /// offloaded timelines or not.
    5543          235 :     fn create_timeline_create_guard(
    5544          235 :         self: &Arc<Self>,
    5545          235 :         timeline_id: TimelineId,
    5546          235 :         idempotency: CreateTimelineIdempotency,
    5547          235 :         allow_offloaded: bool,
    5548          235 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5549          235 :         let tenant_shard_id = self.tenant_shard_id;
    5550              : 
    5551          235 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5552              : 
    5553          235 :         let create_guard = TimelineCreateGuard::new(
    5554          235 :             self,
    5555          235 :             timeline_id,
    5556          235 :             timeline_path.clone(),
    5557          235 :             idempotency,
    5558          235 :             allow_offloaded,
    5559            1 :         )?;
    5560              : 
    5561              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5562              :         // for creation.
    5563              :         // A timeline directory should never exist on disk already:
    5564              :         // - a previous failed creation would have cleaned up after itself
    5565              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5566              :         //
    5567              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5568              :         // this error may indicate a bug in cleanup on failed creations.
    5569          234 :         if timeline_path.exists() {
    5570            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5571            0 :                 "Timeline directory already exists! This is a bug."
    5572            0 :             )));
    5573          234 :         }
    5574              : 
    5575          234 :         Ok(create_guard)
    5576          235 :     }
    5577              : 
    5578              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5579              :     ///
    5580              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5581              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5582              :     pub async fn gather_size_inputs(
    5583              :         &self,
    5584              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5585              :         // (only if it is shorter than the real cutoff).
    5586              :         max_retention_period: Option<u64>,
    5587              :         cause: LogicalSizeCalculationCause,
    5588              :         cancel: &CancellationToken,
    5589              :         ctx: &RequestContext,
    5590              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5591              :         let logical_sizes_at_once = self
    5592              :             .conf
    5593              :             .concurrent_tenant_size_logical_size_queries
    5594              :             .inner();
    5595              : 
    5596              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5597              :         //
    5598              :         // But the only case where we need to run multiple of these at once is when we
    5599              :         // request a size for a tenant manually via API, while another background calculation
    5600              :         // is in progress (which is not a common case).
    5601              :         //
    5602              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5603              :         let mut shared_cache = tokio::select! {
    5604              :             locked = self.cached_logical_sizes.lock() => locked,
    5605              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5606              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5607              :         };
    5608              : 
    5609              :         size::gather_inputs(
    5610              :             self,
    5611              :             logical_sizes_at_once,
    5612              :             max_retention_period,
    5613              :             &mut shared_cache,
    5614              :             cause,
    5615              :             cancel,
    5616              :             ctx,
    5617              :         )
    5618              :         .await
    5619              :     }
    5620              : 
    5621              :     /// Calculate synthetic tenant size and cache the result.
    5622              :     /// This is periodically called by background worker.
    5623              :     /// result is cached in tenant struct
    5624              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5625              :     pub async fn calculate_synthetic_size(
    5626              :         &self,
    5627              :         cause: LogicalSizeCalculationCause,
    5628              :         cancel: &CancellationToken,
    5629              :         ctx: &RequestContext,
    5630              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5631              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5632              : 
    5633              :         let size = inputs.calculate();
    5634              : 
    5635              :         self.set_cached_synthetic_size(size);
    5636              : 
    5637              :         Ok(size)
    5638              :     }
    5639              : 
    5640              :     /// Cache given synthetic size and update the metric value
    5641            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5642            0 :         self.cached_synthetic_tenant_size
    5643            0 :             .store(size, Ordering::Relaxed);
    5644              : 
    5645              :         // Only shard zero should be calculating synthetic sizes
    5646            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5647              : 
    5648            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5649            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5650            0 :             .unwrap()
    5651            0 :             .set(size);
    5652            0 :     }
    5653              : 
    5654            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5655            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5656            0 :     }
    5657              : 
    5658              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5659              :     ///
    5660              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5661              :     /// from an external API handler.
    5662              :     ///
    5663              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5664              :     /// still bounded by tenant/timeline shutdown.
    5665              :     #[tracing::instrument(skip_all)]
    5666              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5667              :         let timelines = self.timelines.lock().unwrap().clone();
    5668              : 
    5669            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5670            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5671            0 :             timeline.freeze_and_flush().await?;
    5672            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5673            0 :             timeline.remote_client.wait_completion().await?;
    5674              : 
    5675            0 :             Ok(())
    5676            0 :         }
    5677              : 
    5678              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5679              :         // aborted when this function's future is cancelled: they should stay alive
    5680              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5681              :         // before Timeline shutdown completes.
    5682              :         let mut results = FuturesUnordered::new();
    5683              : 
    5684              :         for (_timeline_id, timeline) in timelines {
    5685              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5686              :             // means that if this function's future is cancelled, the Timeline shutdown
    5687              :             // will still wait for any I/O in here to complete.
    5688              :             let Ok(gate) = timeline.gate.enter() else {
    5689              :                 continue;
    5690              :             };
    5691            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5692              :             results.push(jh);
    5693              :         }
    5694              : 
    5695              :         while let Some(r) = results.next().await {
    5696              :             if let Err(e) = r {
    5697              :                 if !e.is_cancelled() && !e.is_panic() {
    5698              :                     tracing::error!("unexpected join error: {e:?}");
    5699              :                 }
    5700              :             }
    5701              :         }
    5702              : 
    5703              :         // The flushes we did above were just writes, but the TenantShard might have had
    5704              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5705              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5706              :         // because it's typically a no-op.
    5707              :         match self.deletion_queue_client.flush_execute().await {
    5708              :             Ok(_) => {}
    5709              :             Err(DeletionQueueError::ShuttingDown) => {}
    5710              :         }
    5711              : 
    5712              :         Ok(())
    5713              :     }
    5714              : 
    5715            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5716            0 :         self.tenant_conf.load().tenant_conf.clone()
    5717            0 :     }
    5718              : 
    5719              :     /// How much local storage would this tenant like to have?  It can cope with
    5720              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5721              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5722              :     /// by keeping important things on local disk.
    5723              :     ///
    5724              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5725              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5726              :     /// actually use more than they report here.
    5727            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5728            0 :         let timelines = self.timelines.lock().unwrap();
    5729              : 
    5730              :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5731              :         // reflects the observation that on tenants with multiple large branches, typically only one
    5732              :         // of them is used actively enough to occupy space on disk.
    5733            0 :         timelines
    5734            0 :             .values()
    5735            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5736            0 :             .max()
    5737            0 :             .unwrap_or(0)
    5738            0 :     }
    5739              : 
    5740              :     /// HADRON
    5741              :     /// Return the visible size of all timelines in this tenant.
    5742            0 :     pub(crate) fn get_visible_size(&self) -> u64 {
    5743            0 :         let timelines = self.timelines.lock().unwrap();
    5744            0 :         timelines
    5745            0 :             .values()
    5746            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5747            0 :             .sum()
    5748            0 :     }
    5749              : 
    5750              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5751              :     /// manifest in `Self::remote_tenant_manifest`.
    5752              :     ///
    5753              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5754              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5755              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5756              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5757          120 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5758              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5759              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5760              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5761              :         // simple coalescing mechanism.
    5762          120 :         let mut guard = tokio::select! {
    5763          120 :             guard = self.remote_tenant_manifest.lock() => guard,
    5764          120 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5765              :         };
    5766              : 
    5767              :         // Build a new manifest.
    5768          120 :         let manifest = self.build_tenant_manifest();
    5769              : 
    5770              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5771              :         // uploading every manifest on version number bumps.
    5772          120 :         if let Some(old) = guard.as_ref() {
    5773            4 :             if manifest.eq_ignoring_version(old) {
    5774            3 :                 return Ok(());
    5775            1 :             }
    5776          116 :         }
    5777              : 
    5778              :         // Update metrics
    5779          117 :         let tid = self.tenant_shard_id.to_string();
    5780          117 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5781          117 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5782          117 :         TENANT_OFFLOADED_TIMELINES
    5783          117 :             .with_label_values(set_key)
    5784          117 :             .set(manifest.offloaded_timelines.len() as u64);
    5785              : 
    5786              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5787          117 :         match backoff::retry(
    5788          117 :             || async {
    5789          117 :                 upload_tenant_manifest(
    5790          117 :                     &self.remote_storage,
    5791          117 :                     &self.tenant_shard_id,
    5792          117 :                     self.generation,
    5793          117 :                     &manifest,
    5794          117 :                     &self.cancel,
    5795          117 :                 )
    5796          117 :                 .await
    5797          234 :             },
    5798            0 :             |_| self.cancel.is_cancelled(),
    5799              :             FAILED_UPLOAD_WARN_THRESHOLD,
    5800              :             FAILED_REMOTE_OP_RETRIES,
    5801          117 :             "uploading tenant manifest",
    5802          117 :             &self.cancel,
    5803              :         )
    5804          117 :         .await
    5805              :         {
    5806            0 :             None => Err(TenantManifestError::Cancelled),
    5807            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5808            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5809              :             Some(Ok(_)) => {
    5810              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5811              :                 // re-uploading the same thing.
    5812          117 :                 *guard = Some(manifest);
    5813              : 
    5814          117 :                 Ok(())
    5815              :             }
    5816              :         }
    5817          120 :     }
    5818              : }
    5819              : 
    5820              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5821              : /// to get bootstrap data for timeline initialization.
    5822            0 : async fn run_initdb(
    5823            0 :     conf: &'static PageServerConf,
    5824            0 :     initdb_target_dir: &Utf8Path,
    5825            0 :     pg_version: PgMajorVersion,
    5826            0 :     cancel: &CancellationToken,
    5827            0 : ) -> Result<(), InitdbError> {
    5828            0 :     let initdb_bin_path = conf
    5829            0 :         .pg_bin_dir(pg_version)
    5830            0 :         .map_err(InitdbError::Other)?
    5831            0 :         .join("initdb");
    5832            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5833            0 :     info!(
    5834            0 :         "running {} in {}, libdir: {}",
    5835              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5836              :     );
    5837              : 
    5838            0 :     let _permit = {
    5839            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5840            0 :         INIT_DB_SEMAPHORE.acquire().await
    5841              :     };
    5842              : 
    5843            0 :     CONCURRENT_INITDBS.inc();
    5844            0 :     scopeguard::defer! {
    5845              :         CONCURRENT_INITDBS.dec();
    5846              :     }
    5847              : 
    5848            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5849            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5850            0 :         superuser: &conf.superuser,
    5851            0 :         locale: &conf.locale,
    5852            0 :         initdb_bin: &initdb_bin_path,
    5853            0 :         pg_version,
    5854            0 :         library_search_path: &initdb_lib_dir,
    5855            0 :         pgdata: initdb_target_dir,
    5856            0 :     })
    5857            0 :     .await
    5858            0 :     .map_err(InitdbError::Inner);
    5859              : 
    5860              :     // This isn't true cancellation support, see above. Still return an error to
    5861              :     // excercise the cancellation code path.
    5862            0 :     if cancel.is_cancelled() {
    5863            0 :         return Err(InitdbError::Cancelled);
    5864            0 :     }
    5865              : 
    5866            0 :     res
    5867            0 : }
    5868              : 
    5869              : /// Dump contents of a layer file to stdout.
    5870            0 : pub async fn dump_layerfile_from_path(
    5871            0 :     path: &Utf8Path,
    5872            0 :     verbose: bool,
    5873            0 :     ctx: &RequestContext,
    5874            0 : ) -> anyhow::Result<()> {
    5875              :     use std::os::unix::fs::FileExt;
    5876              : 
    5877              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5878              :     // file.
    5879            0 :     let file = File::open(path)?;
    5880            0 :     let mut header_buf = [0u8; 2];
    5881            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5882              : 
    5883            0 :     match u16::from_be_bytes(header_buf) {
    5884              :         crate::IMAGE_FILE_MAGIC => {
    5885            0 :             ImageLayer::new_for_path(path, file)?
    5886            0 :                 .dump(verbose, ctx)
    5887            0 :                 .await?
    5888              :         }
    5889              :         crate::DELTA_FILE_MAGIC => {
    5890            0 :             DeltaLayer::new_for_path(path, file)?
    5891            0 :                 .dump(verbose, ctx)
    5892            0 :                 .await?
    5893              :         }
    5894            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5895              :     }
    5896              : 
    5897            0 :     Ok(())
    5898            0 : }
    5899              : 
    5900              : #[cfg(test)]
    5901              : pub(crate) mod harness {
    5902              :     use bytes::{Bytes, BytesMut};
    5903              :     use hex_literal::hex;
    5904              :     use once_cell::sync::OnceCell;
    5905              :     use pageserver_api::key::Key;
    5906              :     use pageserver_api::models::ShardParameters;
    5907              :     use pageserver_api::shard::ShardIndex;
    5908              :     use utils::id::TenantId;
    5909              :     use utils::logging;
    5910              :     use wal_decoder::models::record::NeonWalRecord;
    5911              : 
    5912              :     use super::*;
    5913              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5914              :     use crate::l0_flush::L0FlushConfig;
    5915              :     use crate::walredo::apply_neon;
    5916              : 
    5917              :     pub const TIMELINE_ID: TimelineId =
    5918              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5919              :     pub const NEW_TIMELINE_ID: TimelineId =
    5920              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5921              : 
    5922              :     /// Convenience function to create a page image with given string as the only content
    5923      2514409 :     pub fn test_img(s: &str) -> Bytes {
    5924      2514409 :         let mut buf = BytesMut::new();
    5925      2514409 :         buf.extend_from_slice(s.as_bytes());
    5926      2514409 :         buf.resize(64, 0);
    5927              : 
    5928      2514409 :         buf.freeze()
    5929      2514409 :     }
    5930              : 
    5931              :     pub struct TenantHarness {
    5932              :         pub conf: &'static PageServerConf,
    5933              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5934              :         pub tenant_shard_id: TenantShardId,
    5935              :         pub shard_identity: ShardIdentity,
    5936              :         pub generation: Generation,
    5937              :         pub shard: ShardIndex,
    5938              :         pub remote_storage: GenericRemoteStorage,
    5939              :         pub remote_fs_dir: Utf8PathBuf,
    5940              :         pub deletion_queue: MockDeletionQueue,
    5941              :     }
    5942              : 
    5943              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5944              : 
    5945          131 :     pub(crate) fn setup_logging() {
    5946          131 :         LOG_HANDLE.get_or_init(|| {
    5947          125 :             logging::init(
    5948          125 :                 logging::LogFormat::Test,
    5949              :                 // enable it in case the tests exercise code paths that use
    5950              :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5951          125 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5952          125 :                 logging::Output::Stdout,
    5953              :             )
    5954          125 :             .expect("Failed to init test logging");
    5955          125 :         });
    5956          131 :     }
    5957              : 
    5958              :     impl TenantHarness {
    5959          119 :         pub async fn create_custom(
    5960          119 :             test_name: &'static str,
    5961          119 :             tenant_conf: pageserver_api::models::TenantConfig,
    5962          119 :             tenant_id: TenantId,
    5963          119 :             shard_identity: ShardIdentity,
    5964          119 :             generation: Generation,
    5965          119 :         ) -> anyhow::Result<Self> {
    5966          119 :             setup_logging();
    5967              : 
    5968          119 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5969          119 :             let _ = fs::remove_dir_all(&repo_dir);
    5970          119 :             fs::create_dir_all(&repo_dir)?;
    5971              : 
    5972          119 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5973              :             // Make a static copy of the config. This can never be free'd, but that's
    5974              :             // OK in a test.
    5975          119 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5976              : 
    5977          119 :             let shard = shard_identity.shard_index();
    5978          119 :             let tenant_shard_id = TenantShardId {
    5979          119 :                 tenant_id,
    5980          119 :                 shard_number: shard.shard_number,
    5981          119 :                 shard_count: shard.shard_count,
    5982          119 :             };
    5983          119 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5984          119 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5985              : 
    5986              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5987          119 :             let remote_fs_dir = conf.workdir.join("localfs");
    5988          119 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5989          119 :             let config = RemoteStorageConfig {
    5990          119 :                 storage: RemoteStorageKind::LocalFs {
    5991          119 :                     local_path: remote_fs_dir.clone(),
    5992          119 :                 },
    5993          119 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5994          119 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5995          119 :             };
    5996          119 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5997          119 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5998              : 
    5999          119 :             Ok(Self {
    6000          119 :                 conf,
    6001          119 :                 tenant_conf,
    6002          119 :                 tenant_shard_id,
    6003          119 :                 shard_identity,
    6004          119 :                 generation,
    6005          119 :                 shard,
    6006          119 :                 remote_storage,
    6007          119 :                 remote_fs_dir,
    6008          119 :                 deletion_queue,
    6009          119 :             })
    6010          119 :         }
    6011              : 
    6012          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    6013              :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    6014              :             // The tests perform them manually if needed.
    6015          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    6016          110 :                 gc_period: Some(Duration::ZERO),
    6017          110 :                 compaction_period: Some(Duration::ZERO),
    6018          110 :                 ..Default::default()
    6019          110 :             };
    6020          110 :             let tenant_id = TenantId::generate();
    6021          110 :             let shard = ShardIdentity::unsharded();
    6022          110 :             Self::create_custom(
    6023          110 :                 test_name,
    6024          110 :                 tenant_conf,
    6025          110 :                 tenant_id,
    6026          110 :                 shard,
    6027          110 :                 Generation::new(0xdeadbeef),
    6028          110 :             )
    6029          110 :             .await
    6030          110 :         }
    6031              : 
    6032           10 :         pub fn span(&self) -> tracing::Span {
    6033           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    6034           10 :         }
    6035              : 
    6036          119 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    6037          119 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    6038          119 :                 .with_scope_unit_test();
    6039              :             (
    6040          119 :                 self.do_try_load(&ctx)
    6041          119 :                     .await
    6042          119 :                     .expect("failed to load test tenant"),
    6043          119 :                 ctx,
    6044              :             )
    6045          119 :         }
    6046              : 
    6047              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    6048              :         pub(crate) async fn do_try_load_with_redo(
    6049              :             &self,
    6050              :             walredo_mgr: Arc<WalRedoManager>,
    6051              :             ctx: &RequestContext,
    6052              :         ) -> anyhow::Result<Arc<TenantShard>> {
    6053              :             let (basebackup_cache, _) = BasebackupCache::new(Utf8PathBuf::new(), None);
    6054              : 
    6055              :             let tenant = Arc::new(TenantShard::new(
    6056              :                 TenantState::Attaching,
    6057              :                 self.conf,
    6058              :                 AttachedTenantConf::try_from(
    6059              :                     self.conf,
    6060              :                     LocationConf::attached_single(
    6061              :                         self.tenant_conf.clone(),
    6062              :                         self.generation,
    6063              :                         ShardParameters::default(),
    6064              :                     ),
    6065              :                 )
    6066              :                 .unwrap(),
    6067              :                 self.shard_identity,
    6068              :                 Some(walredo_mgr),
    6069              :                 self.tenant_shard_id,
    6070              :                 self.remote_storage.clone(),
    6071              :                 self.deletion_queue.new_client(),
    6072              :                 // TODO: ideally we should run all unit tests with both configs
    6073              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    6074              :                 basebackup_cache,
    6075              :                 FeatureResolver::new_disabled(),
    6076              :             ));
    6077              : 
    6078              :             let preload = tenant
    6079              :                 .preload(&self.remote_storage, CancellationToken::new())
    6080              :                 .await?;
    6081              :             tenant.attach(Some(preload), ctx).await?;
    6082              : 
    6083              :             tenant.state.send_replace(TenantState::Active);
    6084              :             for timeline in tenant.timelines.lock().unwrap().values() {
    6085              :                 timeline.set_state(TimelineState::Active);
    6086              :             }
    6087              :             Ok(tenant)
    6088              :         }
    6089              : 
    6090          119 :         pub(crate) async fn do_try_load(
    6091          119 :             &self,
    6092          119 :             ctx: &RequestContext,
    6093          119 :         ) -> anyhow::Result<Arc<TenantShard>> {
    6094          119 :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    6095          119 :             self.do_try_load_with_redo(walredo_mgr, ctx).await
    6096          119 :         }
    6097              : 
    6098            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    6099            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    6100            1 :         }
    6101              :     }
    6102              : 
    6103              :     // Mock WAL redo manager that doesn't do much
    6104              :     pub(crate) struct TestRedoManager;
    6105              : 
    6106              :     impl TestRedoManager {
    6107              :         /// # Cancel-Safety
    6108              :         ///
    6109              :         /// This method is cancellation-safe.
    6110        26649 :         pub async fn request_redo(
    6111        26649 :             &self,
    6112        26649 :             key: Key,
    6113        26649 :             lsn: Lsn,
    6114        26649 :             base_img: Option<(Lsn, Bytes)>,
    6115        26649 :             records: Vec<(Lsn, NeonWalRecord)>,
    6116        26649 :             _pg_version: PgMajorVersion,
    6117        26649 :             _redo_attempt_type: RedoAttemptType,
    6118        26649 :         ) -> Result<Bytes, walredo::Error> {
    6119      1401844 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    6120        26649 :             if records_neon {
    6121              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    6122        26649 :                 let mut page = match (base_img, records.first()) {
    6123        12781 :                     (Some((_lsn, img)), _) => {
    6124        12781 :                         let mut page = BytesMut::new();
    6125        12781 :                         page.extend_from_slice(&img);
    6126        12781 :                         page
    6127              :                     }
    6128        13868 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    6129              :                     _ => {
    6130            0 :                         panic!("Neon WAL redo requires base image or will init record");
    6131              :                     }
    6132              :                 };
    6133              : 
    6134      1428492 :                 for (record_lsn, record) in records {
    6135      1401844 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    6136              :                 }
    6137        26648 :                 Ok(page.freeze())
    6138              :             } else {
    6139              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    6140            0 :                 let s = format!(
    6141            0 :                     "redo for {} to get to {}, with {} and {} records",
    6142              :                     key,
    6143              :                     lsn,
    6144            0 :                     if base_img.is_some() {
    6145            0 :                         "base image"
    6146              :                     } else {
    6147            0 :                         "no base image"
    6148              :                     },
    6149            0 :                     records.len()
    6150              :                 );
    6151            0 :                 println!("{s}");
    6152              : 
    6153            0 :                 Ok(test_img(&s))
    6154              :             }
    6155        26649 :         }
    6156              :     }
    6157              : }
    6158              : 
    6159              : #[cfg(test)]
    6160              : mod tests {
    6161              :     use std::collections::{BTreeMap, BTreeSet};
    6162              : 
    6163              :     use bytes::{Bytes, BytesMut};
    6164              :     use hex_literal::hex;
    6165              :     use itertools::Itertools;
    6166              :     #[cfg(feature = "testing")]
    6167              :     use models::CompactLsnRange;
    6168              :     use pageserver_api::key::{
    6169              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    6170              :     };
    6171              :     use pageserver_api::keyspace::KeySpace;
    6172              :     #[cfg(feature = "testing")]
    6173              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    6174              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings, LsnLease};
    6175              :     use pageserver_compaction::helpers::overlaps_with;
    6176              :     use rand::Rng;
    6177              :     #[cfg(feature = "testing")]
    6178              :     use rand::SeedableRng;
    6179              :     #[cfg(feature = "testing")]
    6180              :     use rand::rngs::StdRng;
    6181              :     #[cfg(feature = "testing")]
    6182              :     use std::ops::Range;
    6183              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    6184              :     use tests::storage_layer::ValuesReconstructState;
    6185              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    6186              :     #[cfg(feature = "testing")]
    6187              :     use timeline::GcInfo;
    6188              :     #[cfg(feature = "testing")]
    6189              :     use timeline::InMemoryLayerTestDesc;
    6190              :     #[cfg(feature = "testing")]
    6191              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    6192              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    6193              :     use utils::id::TenantId;
    6194              :     use utils::shard::{ShardCount, ShardNumber};
    6195              :     #[cfg(feature = "testing")]
    6196              :     use wal_decoder::models::record::NeonWalRecord;
    6197              :     use wal_decoder::models::value::Value;
    6198              : 
    6199              :     use super::*;
    6200              :     use crate::DEFAULT_PG_VERSION;
    6201              :     use crate::keyspace::KeySpaceAccum;
    6202              :     use crate::tenant::harness::*;
    6203              :     use crate::tenant::timeline::CompactFlags;
    6204              : 
    6205              :     static TEST_KEY: Lazy<Key> =
    6206           10 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    6207              : 
    6208              :     #[cfg(feature = "testing")]
    6209              :     struct TestTimelineSpecification {
    6210              :         start_lsn: Lsn,
    6211              :         last_record_lsn: Lsn,
    6212              : 
    6213              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6214              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6215              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6216              : 
    6217              :         gap_chance: u8,
    6218              :         will_init_chance: u8,
    6219              :     }
    6220              : 
    6221              :     #[cfg(feature = "testing")]
    6222              :     struct Storage {
    6223              :         storage: HashMap<(Key, Lsn), Value>,
    6224              :         start_lsn: Lsn,
    6225              :     }
    6226              : 
    6227              :     #[cfg(feature = "testing")]
    6228              :     impl Storage {
    6229        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6230              :             use bytes::BufMut;
    6231              : 
    6232        32000 :             let mut crnt_lsn = lsn;
    6233        32000 :             let mut got_base = false;
    6234              : 
    6235        32000 :             let mut acc = Vec::new();
    6236              : 
    6237      2798140 :             while crnt_lsn >= self.start_lsn {
    6238      2798140 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6239      1419383 :                     acc.push(value.clone());
    6240              : 
    6241      1401215 :                     match value {
    6242      1401215 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6243      1401215 :                             if *will_init {
    6244        13832 :                                 got_base = true;
    6245        13832 :                                 break;
    6246      1387383 :                             }
    6247              :                         }
    6248              :                         Value::Image(_) => {
    6249        18168 :                             got_base = true;
    6250        18168 :                             break;
    6251              :                         }
    6252            0 :                         _ => unreachable!(),
    6253              :                     }
    6254      1378757 :                 }
    6255              : 
    6256      2766140 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6257              :             }
    6258              : 
    6259        32000 :             assert!(
    6260        32000 :                 got_base,
    6261            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6262              :             );
    6263              : 
    6264        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6265              : 
    6266        32000 :             let mut blob = BytesMut::new();
    6267      1419383 :             for value in acc.into_iter().rev() {
    6268      1401215 :                 match value {
    6269      1401215 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6270      1401215 :                         blob.extend_from_slice(append.as_bytes());
    6271      1401215 :                     }
    6272        18168 :                     Value::Image(img) => {
    6273        18168 :                         blob.put(img);
    6274        18168 :                     }
    6275            0 :                     _ => unreachable!(),
    6276              :                 }
    6277              :             }
    6278              : 
    6279        32000 :             blob.into()
    6280        32000 :         }
    6281              :     }
    6282              : 
    6283              :     #[cfg(feature = "testing")]
    6284              :     #[allow(clippy::too_many_arguments)]
    6285            1 :     async fn randomize_timeline(
    6286            1 :         tenant: &Arc<TenantShard>,
    6287            1 :         new_timeline_id: TimelineId,
    6288            1 :         pg_version: PgMajorVersion,
    6289            1 :         spec: TestTimelineSpecification,
    6290            1 :         random: &mut rand::rngs::StdRng,
    6291            1 :         ctx: &RequestContext,
    6292            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6293            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6294            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6295              : 
    6296            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6297            2 :             let mut lsn = lsn_range.start;
    6298          202 :             while lsn < lsn_range.end {
    6299          200 :                 let mut key = key_range.start;
    6300        21018 :                 while key < key_range.end {
    6301        20818 :                     let gap = random.random_range(1..=100) <= spec.gap_chance;
    6302        20818 :                     let will_init = random.random_range(1..=100) <= spec.will_init_chance;
    6303              : 
    6304        20818 :                     if gap {
    6305         1018 :                         continue;
    6306        19800 :                     }
    6307              : 
    6308        19800 :                     let record = if will_init {
    6309          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6310              :                     } else {
    6311        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6312              :                     };
    6313              : 
    6314        19800 :                     storage.insert((key, lsn), record);
    6315              : 
    6316        19800 :                     key = key.next();
    6317              :                 }
    6318          200 :                 lsn = Lsn(lsn.0 + 1);
    6319              :             }
    6320              : 
    6321              :             // Stash some interesting LSN for future use
    6322            6 :             for offset in [0, 5, 100].iter() {
    6323            6 :                 if *offset == 0 {
    6324            2 :                     interesting_lsns.push(lsn_range.start);
    6325            2 :                 } else {
    6326            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6327            4 :                     match below {
    6328            4 :                         Some(v) if v >= spec.start_lsn => {
    6329            4 :                             interesting_lsns.push(v);
    6330            4 :                         }
    6331            0 :                         _ => {}
    6332              :                     }
    6333              : 
    6334            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6335            4 :                     interesting_lsns.push(above);
    6336              :                 }
    6337              :             }
    6338              :         }
    6339              : 
    6340            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6341            3 :             let mut lsn = lsn_range.start;
    6342          315 :             while lsn < lsn_range.end {
    6343          312 :                 let mut key = key_range.start;
    6344        11112 :                 while key < key_range.end {
    6345        10800 :                     let gap = random.random_range(1..=100) <= spec.gap_chance;
    6346        10800 :                     let will_init = random.random_range(1..=100) <= spec.will_init_chance;
    6347              : 
    6348        10800 :                     if gap {
    6349          504 :                         continue;
    6350        10296 :                     }
    6351              : 
    6352        10296 :                     let record = if will_init {
    6353          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6354              :                     } else {
    6355        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6356              :                     };
    6357              : 
    6358        10296 :                     storage.insert((key, lsn), record);
    6359              : 
    6360        10296 :                     key = key.next();
    6361              :                 }
    6362          312 :                 lsn = Lsn(lsn.0 + 1);
    6363              :             }
    6364              : 
    6365              :             // Stash some interesting LSN for future use
    6366            9 :             for offset in [0, 5, 100].iter() {
    6367            9 :                 if *offset == 0 {
    6368            3 :                     interesting_lsns.push(lsn_range.start);
    6369            3 :                 } else {
    6370            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6371            6 :                     match below {
    6372            6 :                         Some(v) if v >= spec.start_lsn => {
    6373            3 :                             interesting_lsns.push(v);
    6374            3 :                         }
    6375            3 :                         _ => {}
    6376              :                     }
    6377              : 
    6378            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6379            6 :                     interesting_lsns.push(above);
    6380              :                 }
    6381              :             }
    6382              :         }
    6383              : 
    6384            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6385            3 :             let mut key = key_range.start;
    6386          142 :             while key < key_range.end {
    6387          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6388          139 :                 let record = Value::Image(blob.clone());
    6389          139 :                 storage.insert((key, *lsn), record);
    6390          139 : 
    6391          139 :                 key = key.next();
    6392          139 :             }
    6393              : 
    6394              :             // Stash some interesting LSN for future use
    6395            9 :             for offset in [0, 5, 100].iter() {
    6396            9 :                 if *offset == 0 {
    6397            3 :                     interesting_lsns.push(*lsn);
    6398            3 :                 } else {
    6399            6 :                     let below = lsn.checked_sub(*offset);
    6400            6 :                     match below {
    6401            6 :                         Some(v) if v >= spec.start_lsn => {
    6402            4 :                             interesting_lsns.push(v);
    6403            4 :                         }
    6404            2 :                         _ => {}
    6405              :                     }
    6406              : 
    6407            6 :                     let above = Lsn(lsn.0 + offset);
    6408            6 :                     interesting_lsns.push(above);
    6409              :                 }
    6410              :             }
    6411              :         }
    6412              : 
    6413            1 :         let in_memory_test_layers = {
    6414            1 :             let mut acc = Vec::new();
    6415              : 
    6416            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6417            2 :                 let mut data = Vec::new();
    6418              : 
    6419            2 :                 let mut lsn = lsn_range.start;
    6420          202 :                 while lsn < lsn_range.end {
    6421          200 :                     let mut key = key_range.start;
    6422        20000 :                     while key < key_range.end {
    6423        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6424        19800 :                             data.push((key, lsn, record.clone()));
    6425        19800 :                         }
    6426              : 
    6427        19800 :                         key = key.next();
    6428              :                     }
    6429          200 :                     lsn = Lsn(lsn.0 + 1);
    6430              :                 }
    6431              : 
    6432            2 :                 acc.push(InMemoryLayerTestDesc {
    6433            2 :                     data,
    6434            2 :                     lsn_range: lsn_range.clone(),
    6435            2 :                     is_open: false,
    6436            2 :                 })
    6437              :             }
    6438              : 
    6439            1 :             acc
    6440              :         };
    6441              : 
    6442            1 :         let delta_test_layers = {
    6443            1 :             let mut acc = Vec::new();
    6444              : 
    6445            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6446            3 :                 let mut data = Vec::new();
    6447              : 
    6448            3 :                 let mut lsn = lsn_range.start;
    6449          315 :                 while lsn < lsn_range.end {
    6450          312 :                     let mut key = key_range.start;
    6451        10608 :                     while key < key_range.end {
    6452        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6453        10296 :                             data.push((key, lsn, record.clone()));
    6454        10296 :                         }
    6455              : 
    6456        10296 :                         key = key.next();
    6457              :                     }
    6458          312 :                     lsn = Lsn(lsn.0 + 1);
    6459              :                 }
    6460              : 
    6461            3 :                 acc.push(DeltaLayerTestDesc {
    6462            3 :                     data,
    6463            3 :                     lsn_range: lsn_range.clone(),
    6464            3 :                     key_range: key_range.clone(),
    6465            3 :                 })
    6466              :             }
    6467              : 
    6468            1 :             acc
    6469              :         };
    6470              : 
    6471            1 :         let image_test_layers = {
    6472            1 :             let mut acc = Vec::new();
    6473              : 
    6474            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6475            3 :                 let mut data = Vec::new();
    6476              : 
    6477            3 :                 let mut key = key_range.start;
    6478          142 :                 while key < key_range.end {
    6479          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6480          139 :                         let blob = match record {
    6481          139 :                             Value::Image(blob) => blob.clone(),
    6482            0 :                             _ => unreachable!(),
    6483              :                         };
    6484              : 
    6485          139 :                         data.push((key, blob));
    6486            0 :                     }
    6487              : 
    6488          139 :                     key = key.next();
    6489              :                 }
    6490              : 
    6491            3 :                 acc.push((*lsn, data));
    6492              :             }
    6493              : 
    6494            1 :             acc
    6495              :         };
    6496              : 
    6497            1 :         let tline = tenant
    6498            1 :             .create_test_timeline_with_layers(
    6499            1 :                 new_timeline_id,
    6500            1 :                 spec.start_lsn,
    6501            1 :                 pg_version,
    6502            1 :                 ctx,
    6503            1 :                 in_memory_test_layers,
    6504            1 :                 delta_test_layers,
    6505            1 :                 image_test_layers,
    6506            1 :                 spec.last_record_lsn,
    6507            1 :             )
    6508            1 :             .await?;
    6509              : 
    6510            1 :         Ok((
    6511            1 :             tline,
    6512            1 :             Storage {
    6513            1 :                 storage,
    6514            1 :                 start_lsn: spec.start_lsn,
    6515            1 :             },
    6516            1 :             interesting_lsns,
    6517            1 :         ))
    6518            1 :     }
    6519              : 
    6520              :     #[tokio::test]
    6521            1 :     async fn test_basic() -> anyhow::Result<()> {
    6522            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6523            1 :         let tline = tenant
    6524            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6525            1 :             .await?;
    6526              : 
    6527            1 :         let mut writer = tline.writer().await;
    6528            1 :         writer
    6529            1 :             .put(
    6530            1 :                 *TEST_KEY,
    6531            1 :                 Lsn(0x10),
    6532            1 :                 &Value::Image(test_img("foo at 0x10")),
    6533            1 :                 &ctx,
    6534            1 :             )
    6535            1 :             .await?;
    6536            1 :         writer.finish_write(Lsn(0x10));
    6537            1 :         drop(writer);
    6538              : 
    6539            1 :         let mut writer = tline.writer().await;
    6540            1 :         writer
    6541            1 :             .put(
    6542            1 :                 *TEST_KEY,
    6543            1 :                 Lsn(0x20),
    6544            1 :                 &Value::Image(test_img("foo at 0x20")),
    6545            1 :                 &ctx,
    6546            1 :             )
    6547            1 :             .await?;
    6548            1 :         writer.finish_write(Lsn(0x20));
    6549            1 :         drop(writer);
    6550              : 
    6551            1 :         assert_eq!(
    6552            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6553            1 :             test_img("foo at 0x10")
    6554              :         );
    6555            1 :         assert_eq!(
    6556            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6557            1 :             test_img("foo at 0x10")
    6558              :         );
    6559            1 :         assert_eq!(
    6560            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6561            1 :             test_img("foo at 0x20")
    6562              :         );
    6563              : 
    6564            2 :         Ok(())
    6565            1 :     }
    6566              : 
    6567              :     #[tokio::test]
    6568            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6569            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6570            1 :             .await?
    6571            1 :             .load()
    6572            1 :             .await;
    6573            1 :         let _ = tenant
    6574            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6575            1 :             .await?;
    6576              : 
    6577            1 :         match tenant
    6578            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6579            1 :             .await
    6580            1 :         {
    6581            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6582            1 :             Err(e) => assert_eq!(
    6583            1 :                 e.to_string(),
    6584            1 :                 "timeline already exists with different parameters".to_string()
    6585            1 :             ),
    6586            1 :         }
    6587            1 : 
    6588            1 :         Ok(())
    6589            1 :     }
    6590              : 
    6591              :     /// Convenience function to create a page image with given string as the only content
    6592            5 :     pub fn test_value(s: &str) -> Value {
    6593            5 :         let mut buf = BytesMut::new();
    6594            5 :         buf.extend_from_slice(s.as_bytes());
    6595            5 :         Value::Image(buf.freeze())
    6596            5 :     }
    6597              : 
    6598              :     ///
    6599              :     /// Test branch creation
    6600              :     ///
    6601              :     #[tokio::test]
    6602            1 :     async fn test_branch() -> anyhow::Result<()> {
    6603              :         use std::str::from_utf8;
    6604              : 
    6605            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6606            1 :         let tline = tenant
    6607            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6608            1 :             .await?;
    6609            1 :         let mut writer = tline.writer().await;
    6610              : 
    6611              :         #[allow(non_snake_case)]
    6612            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6613              :         #[allow(non_snake_case)]
    6614            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6615              : 
    6616              :         // Insert a value on the timeline
    6617            1 :         writer
    6618            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6619            1 :             .await?;
    6620            1 :         writer
    6621            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6622            1 :             .await?;
    6623            1 :         writer.finish_write(Lsn(0x20));
    6624              : 
    6625            1 :         writer
    6626            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6627            1 :             .await?;
    6628            1 :         writer.finish_write(Lsn(0x30));
    6629            1 :         writer
    6630            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6631            1 :             .await?;
    6632            1 :         writer.finish_write(Lsn(0x40));
    6633              : 
    6634              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6635              : 
    6636              :         // Branch the history, modify relation differently on the new timeline
    6637            1 :         tenant
    6638            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6639            1 :             .await?;
    6640            1 :         let newtline = tenant
    6641            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6642            1 :             .expect("Should have a local timeline");
    6643            1 :         let mut new_writer = newtline.writer().await;
    6644            1 :         new_writer
    6645            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6646            1 :             .await?;
    6647            1 :         new_writer.finish_write(Lsn(0x40));
    6648              : 
    6649              :         // Check page contents on both branches
    6650            1 :         assert_eq!(
    6651            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6652              :             "foo at 0x40"
    6653              :         );
    6654            1 :         assert_eq!(
    6655            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6656              :             "bar at 0x40"
    6657              :         );
    6658            1 :         assert_eq!(
    6659            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6660              :             "foobar at 0x20"
    6661              :         );
    6662              : 
    6663              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6664              : 
    6665            2 :         Ok(())
    6666            1 :     }
    6667              : 
    6668           10 :     async fn make_some_layers(
    6669           10 :         tline: &Timeline,
    6670           10 :         start_lsn: Lsn,
    6671           10 :         ctx: &RequestContext,
    6672           10 :     ) -> anyhow::Result<()> {
    6673           10 :         let mut lsn = start_lsn;
    6674              :         {
    6675           10 :             let mut writer = tline.writer().await;
    6676              :             // Create a relation on the timeline
    6677           10 :             writer
    6678           10 :                 .put(
    6679           10 :                     *TEST_KEY,
    6680           10 :                     lsn,
    6681           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6682           10 :                     ctx,
    6683           10 :                 )
    6684           10 :                 .await?;
    6685           10 :             writer.finish_write(lsn);
    6686           10 :             lsn += 0x10;
    6687           10 :             writer
    6688           10 :                 .put(
    6689           10 :                     *TEST_KEY,
    6690           10 :                     lsn,
    6691           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6692           10 :                     ctx,
    6693           10 :                 )
    6694           10 :                 .await?;
    6695           10 :             writer.finish_write(lsn);
    6696           10 :             lsn += 0x10;
    6697              :         }
    6698           10 :         tline.freeze_and_flush().await?;
    6699              :         {
    6700           10 :             let mut writer = tline.writer().await;
    6701           10 :             writer
    6702           10 :                 .put(
    6703           10 :                     *TEST_KEY,
    6704           10 :                     lsn,
    6705           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6706           10 :                     ctx,
    6707           10 :                 )
    6708           10 :                 .await?;
    6709           10 :             writer.finish_write(lsn);
    6710           10 :             lsn += 0x10;
    6711           10 :             writer
    6712           10 :                 .put(
    6713           10 :                     *TEST_KEY,
    6714           10 :                     lsn,
    6715           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6716           10 :                     ctx,
    6717           10 :                 )
    6718           10 :                 .await?;
    6719           10 :             writer.finish_write(lsn);
    6720              :         }
    6721           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6722           10 :     }
    6723              : 
    6724              :     #[tokio::test]
    6725            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6726            1 :         let (tenant, ctx) =
    6727            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6728            1 :                 .await?
    6729            1 :                 .load()
    6730            1 :                 .await;
    6731            1 :         let tline = tenant
    6732            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6733            1 :             .await?;
    6734            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6735              : 
    6736              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6737              :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6738              :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6739              :         // below should fail.
    6740            1 :         tenant
    6741            1 :             .gc_iteration(
    6742            1 :                 Some(TIMELINE_ID),
    6743            1 :                 0x10,
    6744            1 :                 Duration::ZERO,
    6745            1 :                 &CancellationToken::new(),
    6746            1 :                 &ctx,
    6747            1 :             )
    6748            1 :             .await?;
    6749              : 
    6750              :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6751            1 :         match tenant
    6752            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6753            1 :             .await
    6754            1 :         {
    6755            1 :             Ok(_) => panic!("branching should have failed"),
    6756            1 :             Err(err) => {
    6757            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6758            1 :                     panic!("wrong error type")
    6759            1 :                 };
    6760            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6761            1 :                 assert!(
    6762            1 :                     err.source()
    6763            1 :                         .unwrap()
    6764            1 :                         .to_string()
    6765            1 :                         .contains("we might've already garbage collected needed data")
    6766            1 :                 )
    6767            1 :             }
    6768            1 :         }
    6769            1 : 
    6770            1 :         Ok(())
    6771            1 :     }
    6772              : 
    6773              :     #[tokio::test]
    6774            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6775            1 :         let (tenant, ctx) =
    6776            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6777            1 :                 .await?
    6778            1 :                 .load()
    6779            1 :                 .await;
    6780              : 
    6781            1 :         let tline = tenant
    6782            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6783            1 :             .await?;
    6784              :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6785            1 :         match tenant
    6786            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6787            1 :             .await
    6788            1 :         {
    6789            1 :             Ok(_) => panic!("branching should have failed"),
    6790            1 :             Err(err) => {
    6791            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6792            1 :                     panic!("wrong error type");
    6793            1 :                 };
    6794            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6795            1 :                 assert!(
    6796            1 :                     &err.source()
    6797            1 :                         .unwrap()
    6798            1 :                         .to_string()
    6799            1 :                         .contains("is earlier than latest GC cutoff")
    6800            1 :                 );
    6801            1 :             }
    6802            1 :         }
    6803            1 : 
    6804            1 :         Ok(())
    6805            1 :     }
    6806              : 
    6807              :     /*
    6808              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6809              :     // remove the old value, we'd need to work a little harder
    6810              :     #[tokio::test]
    6811              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6812              :         let repo =
    6813              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6814              :             .load();
    6815              : 
    6816              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6817              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6818              : 
    6819              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6820              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6821              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6822              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6823              :             Ok(_) => panic!("request for page should have failed"),
    6824              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6825              :         }
    6826              :         Ok(())
    6827              :     }
    6828              :      */
    6829              : 
    6830              :     #[tokio::test]
    6831            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6832            1 :         let (tenant, ctx) =
    6833            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6834            1 :                 .await?
    6835            1 :                 .load()
    6836            1 :                 .await;
    6837            1 :         let tline = tenant
    6838            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6839            1 :             .await?;
    6840            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6841              : 
    6842            1 :         tenant
    6843            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6844            1 :             .await?;
    6845            1 :         let newtline = tenant
    6846            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6847            1 :             .expect("Should have a local timeline");
    6848              : 
    6849            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6850              : 
    6851            1 :         tline.set_broken("test".to_owned());
    6852              : 
    6853            1 :         tenant
    6854            1 :             .gc_iteration(
    6855            1 :                 Some(TIMELINE_ID),
    6856            1 :                 0x10,
    6857            1 :                 Duration::ZERO,
    6858            1 :                 &CancellationToken::new(),
    6859            1 :                 &ctx,
    6860            1 :             )
    6861            1 :             .await?;
    6862              : 
    6863              :         // The branchpoints should contain all timelines, even ones marked
    6864              :         // as Broken.
    6865              :         {
    6866            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6867            1 :             assert_eq!(branchpoints.len(), 1);
    6868            1 :             assert_eq!(
    6869            1 :                 branchpoints[0],
    6870              :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6871              :             );
    6872              :         }
    6873              : 
    6874              :         // You can read the key from the child branch even though the parent is
    6875              :         // Broken, as long as you don't need to access data from the parent.
    6876            1 :         assert_eq!(
    6877            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6878            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6879              :         );
    6880              : 
    6881              :         // This needs to traverse to the parent, and fails.
    6882            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6883            1 :         assert!(
    6884            1 :             err.to_string().starts_with(&format!(
    6885            1 :                 "bad state on timeline {}: Broken",
    6886            1 :                 tline.timeline_id
    6887            1 :             )),
    6888            0 :             "{err}"
    6889              :         );
    6890              : 
    6891            2 :         Ok(())
    6892            1 :     }
    6893              : 
    6894              :     #[tokio::test]
    6895            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6896            1 :         let (tenant, ctx) =
    6897            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6898            1 :                 .await?
    6899            1 :                 .load()
    6900            1 :                 .await;
    6901            1 :         let tline = tenant
    6902            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6903            1 :             .await?;
    6904            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6905              : 
    6906            1 :         tenant
    6907            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6908            1 :             .await?;
    6909            1 :         let newtline = tenant
    6910            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6911            1 :             .expect("Should have a local timeline");
    6912              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6913            1 :         tenant
    6914            1 :             .gc_iteration(
    6915            1 :                 Some(TIMELINE_ID),
    6916            1 :                 0x10,
    6917            1 :                 Duration::ZERO,
    6918            1 :                 &CancellationToken::new(),
    6919            1 :                 &ctx,
    6920            1 :             )
    6921            1 :             .await?;
    6922            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6923              : 
    6924            2 :         Ok(())
    6925            1 :     }
    6926              :     #[tokio::test]
    6927            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6928            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6929            1 :             .await?
    6930            1 :             .load()
    6931            1 :             .await;
    6932            1 :         let tline = tenant
    6933            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6934            1 :             .await?;
    6935            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6936              : 
    6937            1 :         tenant
    6938            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6939            1 :             .await?;
    6940            1 :         let newtline = tenant
    6941            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6942            1 :             .expect("Should have a local timeline");
    6943              : 
    6944            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6945              : 
    6946              :         // run gc on parent
    6947            1 :         tenant
    6948            1 :             .gc_iteration(
    6949            1 :                 Some(TIMELINE_ID),
    6950            1 :                 0x10,
    6951            1 :                 Duration::ZERO,
    6952            1 :                 &CancellationToken::new(),
    6953            1 :                 &ctx,
    6954            1 :             )
    6955            1 :             .await?;
    6956              : 
    6957              :         // Check that the data is still accessible on the branch.
    6958            1 :         assert_eq!(
    6959            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6960            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6961              :         );
    6962              : 
    6963            2 :         Ok(())
    6964            1 :     }
    6965              : 
    6966              :     #[tokio::test]
    6967            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6968              :         const TEST_NAME: &str = "timeline_load";
    6969            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6970              :         {
    6971            1 :             let (tenant, ctx) = harness.load().await;
    6972            1 :             let tline = tenant
    6973            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6974            1 :                 .await?;
    6975            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6976              :             // so that all uploads finish & we can call harness.load() below again
    6977            1 :             tenant
    6978            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6979            1 :                 .instrument(harness.span())
    6980            1 :                 .await
    6981            1 :                 .ok()
    6982            1 :                 .unwrap();
    6983              :         }
    6984              : 
    6985            1 :         let (tenant, _ctx) = harness.load().await;
    6986            1 :         tenant
    6987            1 :             .get_timeline(TIMELINE_ID, true)
    6988            1 :             .expect("cannot load timeline");
    6989              : 
    6990            2 :         Ok(())
    6991            1 :     }
    6992              : 
    6993              :     #[tokio::test]
    6994            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6995              :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6996            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6997              :         // create two timelines
    6998              :         {
    6999            1 :             let (tenant, ctx) = harness.load().await;
    7000            1 :             let tline = tenant
    7001            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7002            1 :                 .await?;
    7003              : 
    7004            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7005              : 
    7006            1 :             let child_tline = tenant
    7007            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    7008            1 :                 .await?;
    7009            1 :             child_tline.set_state(TimelineState::Active);
    7010              : 
    7011            1 :             let newtline = tenant
    7012            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    7013            1 :                 .expect("Should have a local timeline");
    7014              : 
    7015            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    7016              : 
    7017              :             // so that all uploads finish & we can call harness.load() below again
    7018            1 :             tenant
    7019            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    7020            1 :                 .instrument(harness.span())
    7021            1 :                 .await
    7022            1 :                 .ok()
    7023            1 :                 .unwrap();
    7024              :         }
    7025              : 
    7026              :         // check that both of them are initially unloaded
    7027            1 :         let (tenant, _ctx) = harness.load().await;
    7028              : 
    7029              :         // check that both, child and ancestor are loaded
    7030            1 :         let _child_tline = tenant
    7031            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    7032            1 :             .expect("cannot get child timeline loaded");
    7033              : 
    7034            1 :         let _ancestor_tline = tenant
    7035            1 :             .get_timeline(TIMELINE_ID, true)
    7036            1 :             .expect("cannot get ancestor timeline loaded");
    7037              : 
    7038            2 :         Ok(())
    7039            1 :     }
    7040              : 
    7041              :     #[tokio::test]
    7042            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    7043              :         use storage_layer::AsLayerDesc;
    7044            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    7045            1 :             .await?
    7046            1 :             .load()
    7047            1 :             .await;
    7048            1 :         let tline = tenant
    7049            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7050            1 :             .await?;
    7051            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7052              : 
    7053            1 :         let layer_map = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7054            1 :         let level0_deltas = layer_map
    7055            1 :             .layer_map()?
    7056            1 :             .level0_deltas()
    7057            1 :             .iter()
    7058            2 :             .map(|desc| layer_map.get_from_desc(desc))
    7059            1 :             .collect::<Vec<_>>();
    7060              : 
    7061            1 :         assert!(!level0_deltas.is_empty());
    7062              : 
    7063            3 :         for delta in level0_deltas {
    7064            1 :             // Ensure we are dumping a delta layer here
    7065            2 :             assert!(delta.layer_desc().is_delta);
    7066            2 :             delta.dump(true, &ctx).await.unwrap();
    7067            1 :         }
    7068            1 : 
    7069            1 :         Ok(())
    7070            1 :     }
    7071              : 
    7072              :     #[tokio::test]
    7073            1 :     async fn test_images() -> anyhow::Result<()> {
    7074            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    7075            1 :         let tline = tenant
    7076            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7077            1 :             .await?;
    7078              : 
    7079            1 :         let mut writer = tline.writer().await;
    7080            1 :         writer
    7081            1 :             .put(
    7082            1 :                 *TEST_KEY,
    7083            1 :                 Lsn(0x10),
    7084            1 :                 &Value::Image(test_img("foo at 0x10")),
    7085            1 :                 &ctx,
    7086            1 :             )
    7087            1 :             .await?;
    7088            1 :         writer.finish_write(Lsn(0x10));
    7089            1 :         drop(writer);
    7090              : 
    7091            1 :         tline.freeze_and_flush().await?;
    7092            1 :         tline
    7093            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7094            1 :             .await?;
    7095              : 
    7096            1 :         let mut writer = tline.writer().await;
    7097            1 :         writer
    7098            1 :             .put(
    7099            1 :                 *TEST_KEY,
    7100            1 :                 Lsn(0x20),
    7101            1 :                 &Value::Image(test_img("foo at 0x20")),
    7102            1 :                 &ctx,
    7103            1 :             )
    7104            1 :             .await?;
    7105            1 :         writer.finish_write(Lsn(0x20));
    7106            1 :         drop(writer);
    7107              : 
    7108            1 :         tline.freeze_and_flush().await?;
    7109            1 :         tline
    7110            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7111            1 :             .await?;
    7112              : 
    7113            1 :         let mut writer = tline.writer().await;
    7114            1 :         writer
    7115            1 :             .put(
    7116            1 :                 *TEST_KEY,
    7117            1 :                 Lsn(0x30),
    7118            1 :                 &Value::Image(test_img("foo at 0x30")),
    7119            1 :                 &ctx,
    7120            1 :             )
    7121            1 :             .await?;
    7122            1 :         writer.finish_write(Lsn(0x30));
    7123            1 :         drop(writer);
    7124              : 
    7125            1 :         tline.freeze_and_flush().await?;
    7126            1 :         tline
    7127            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7128            1 :             .await?;
    7129              : 
    7130            1 :         let mut writer = tline.writer().await;
    7131            1 :         writer
    7132            1 :             .put(
    7133            1 :                 *TEST_KEY,
    7134            1 :                 Lsn(0x40),
    7135            1 :                 &Value::Image(test_img("foo at 0x40")),
    7136            1 :                 &ctx,
    7137            1 :             )
    7138            1 :             .await?;
    7139            1 :         writer.finish_write(Lsn(0x40));
    7140            1 :         drop(writer);
    7141              : 
    7142            1 :         tline.freeze_and_flush().await?;
    7143            1 :         tline
    7144            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7145            1 :             .await?;
    7146              : 
    7147            1 :         assert_eq!(
    7148            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    7149            1 :             test_img("foo at 0x10")
    7150              :         );
    7151            1 :         assert_eq!(
    7152            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    7153            1 :             test_img("foo at 0x10")
    7154              :         );
    7155            1 :         assert_eq!(
    7156            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    7157            1 :             test_img("foo at 0x20")
    7158              :         );
    7159            1 :         assert_eq!(
    7160            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    7161            1 :             test_img("foo at 0x30")
    7162              :         );
    7163            1 :         assert_eq!(
    7164            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    7165            1 :             test_img("foo at 0x40")
    7166              :         );
    7167              : 
    7168            2 :         Ok(())
    7169            1 :     }
    7170              : 
    7171            2 :     async fn bulk_insert_compact_gc(
    7172            2 :         tenant: &TenantShard,
    7173            2 :         timeline: &Arc<Timeline>,
    7174            2 :         ctx: &RequestContext,
    7175            2 :         lsn: Lsn,
    7176            2 :         repeat: usize,
    7177            2 :         key_count: usize,
    7178            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7179            2 :         let compact = true;
    7180            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    7181            2 :     }
    7182              : 
    7183            4 :     async fn bulk_insert_maybe_compact_gc(
    7184            4 :         tenant: &TenantShard,
    7185            4 :         timeline: &Arc<Timeline>,
    7186            4 :         ctx: &RequestContext,
    7187            4 :         mut lsn: Lsn,
    7188            4 :         repeat: usize,
    7189            4 :         key_count: usize,
    7190            4 :         compact: bool,
    7191            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7192            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    7193              : 
    7194            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7195            4 :         let mut blknum = 0;
    7196              : 
    7197              :         // Enforce that key range is monotonously increasing
    7198            4 :         let mut keyspace = KeySpaceAccum::new();
    7199              : 
    7200            4 :         let cancel = CancellationToken::new();
    7201              : 
    7202            4 :         for _ in 0..repeat {
    7203          200 :             for _ in 0..key_count {
    7204      2000000 :                 test_key.field6 = blknum;
    7205      2000000 :                 let mut writer = timeline.writer().await;
    7206      2000000 :                 writer
    7207      2000000 :                     .put(
    7208      2000000 :                         test_key,
    7209      2000000 :                         lsn,
    7210      2000000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7211      2000000 :                         ctx,
    7212      2000000 :                     )
    7213      2000000 :                     .await?;
    7214      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7215      2000000 :                 writer.finish_write(lsn);
    7216      2000000 :                 drop(writer);
    7217              : 
    7218      2000000 :                 keyspace.add_key(test_key);
    7219              : 
    7220      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7221      2000000 :                 blknum += 1;
    7222              :             }
    7223              : 
    7224          200 :             timeline.freeze_and_flush().await?;
    7225          200 :             if compact {
    7226              :                 // this requires timeline to be &Arc<Timeline>
    7227          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7228          100 :             }
    7229              : 
    7230              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7231              :             // originally was.
    7232          200 :             let res = tenant
    7233          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7234          200 :                 .await?;
    7235              : 
    7236          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7237              :         }
    7238              : 
    7239            4 :         Ok(inserted)
    7240            4 :     }
    7241              : 
    7242              :     //
    7243              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7244              :     // Repeat 50 times.
    7245              :     //
    7246              :     #[tokio::test]
    7247            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7248            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7249            1 :         let (tenant, ctx) = harness.load().await;
    7250            1 :         let tline = tenant
    7251            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7252            1 :             .await?;
    7253              : 
    7254            1 :         let lsn = Lsn(0x10);
    7255            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7256              : 
    7257            2 :         Ok(())
    7258            1 :     }
    7259              : 
    7260              :     // Test the vectored get real implementation against a simple sequential implementation.
    7261              :     //
    7262              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7263              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7264              :     // grow to the right on the X axis.
    7265              :     //                       [Delta]
    7266              :     //                 [Delta]
    7267              :     //           [Delta]
    7268              :     //    [Delta]
    7269              :     // ------------ Image ---------------
    7270              :     //
    7271              :     // After layer generation we pick the ranges to query as follows:
    7272              :     // 1. The beginning of each delta layer
    7273              :     // 2. At the seam between two adjacent delta layers
    7274              :     //
    7275              :     // There's one major downside to this test: delta layers only contains images,
    7276              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7277              :     #[tokio::test]
    7278            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7279            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7280            1 :         let (tenant, ctx) = harness.load().await;
    7281            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7282            1 :         let tline = tenant
    7283            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7284            1 :             .await?;
    7285              : 
    7286            1 :         let lsn = Lsn(0x10);
    7287            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7288              : 
    7289            1 :         let guard = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7290            1 :         let lm = guard.layer_map()?;
    7291              : 
    7292            1 :         lm.dump(true, &ctx).await?;
    7293              : 
    7294            1 :         let mut reads = Vec::new();
    7295            1 :         let mut prev = None;
    7296            6 :         lm.iter_historic_layers().for_each(|desc| {
    7297            6 :             if !desc.is_delta() {
    7298            1 :                 prev = Some(desc.clone());
    7299            1 :                 return;
    7300            5 :             }
    7301              : 
    7302            5 :             let start = desc.key_range.start;
    7303            5 :             let end = desc
    7304            5 :                 .key_range
    7305            5 :                 .start
    7306            5 :                 .add(tenant.conf.max_get_vectored_keys.get() as u32);
    7307            5 :             reads.push(KeySpace {
    7308            5 :                 ranges: vec![start..end],
    7309            5 :             });
    7310              : 
    7311            5 :             if let Some(prev) = &prev {
    7312            5 :                 if !prev.is_delta() {
    7313            5 :                     return;
    7314            0 :                 }
    7315              : 
    7316            0 :                 let first_range = Key {
    7317            0 :                     field6: prev.key_range.end.field6 - 4,
    7318            0 :                     ..prev.key_range.end
    7319            0 :                 }..prev.key_range.end;
    7320              : 
    7321            0 :                 let second_range = desc.key_range.start..Key {
    7322            0 :                     field6: desc.key_range.start.field6 + 4,
    7323            0 :                     ..desc.key_range.start
    7324            0 :                 };
    7325              : 
    7326            0 :                 reads.push(KeySpace {
    7327            0 :                     ranges: vec![first_range, second_range],
    7328            0 :                 });
    7329            0 :             };
    7330              : 
    7331            0 :             prev = Some(desc.clone());
    7332            6 :         });
    7333              : 
    7334            1 :         drop(guard);
    7335              : 
    7336              :         // Pick a big LSN such that we query over all the changes.
    7337            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7338              : 
    7339            6 :         for read in reads {
    7340            5 :             info!("Doing vectored read on {:?}", read);
    7341            1 : 
    7342            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7343            1 : 
    7344            5 :             let vectored_res = tline
    7345            5 :                 .get_vectored_impl(
    7346            5 :                     query,
    7347            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7348            5 :                     &ctx,
    7349            5 :                 )
    7350            5 :                 .await;
    7351            1 : 
    7352            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7353            5 :             let mut expect_missing = false;
    7354            5 :             let mut key = read.start().unwrap();
    7355          165 :             while key != read.end().unwrap() {
    7356          160 :                 if let Some(lsns) = inserted.get(&key) {
    7357          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7358          160 :                     match expected_lsn {
    7359          160 :                         Some(lsn) => {
    7360          160 :                             expected_lsns.insert(key, *lsn);
    7361          160 :                         }
    7362            1 :                         None => {
    7363            1 :                             expect_missing = true;
    7364            1 :                             break;
    7365            1 :                         }
    7366            1 :                     }
    7367            1 :                 } else {
    7368            1 :                     expect_missing = true;
    7369            1 :                     break;
    7370            1 :                 }
    7371            1 : 
    7372          160 :                 key = key.next();
    7373            1 :             }
    7374            1 : 
    7375            5 :             if expect_missing {
    7376            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7377            1 :             } else {
    7378          160 :                 for (key, image) in vectored_res? {
    7379          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7380          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7381          160 :                     assert_eq!(image?, expected_image);
    7382            1 :                 }
    7383            1 :             }
    7384            1 :         }
    7385            1 : 
    7386            1 :         Ok(())
    7387            1 :     }
    7388              : 
    7389              :     #[tokio::test]
    7390            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7391            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7392              : 
    7393            1 :         let (tenant, ctx) = harness.load().await;
    7394            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7395            1 :         let (tline, ctx) = tenant
    7396            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7397            1 :             .await?;
    7398            1 :         let tline = tline.raw_timeline().unwrap();
    7399              : 
    7400            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7401            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7402            1 :         modification.set_lsn(Lsn(0x1008))?;
    7403            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7404            1 :         modification.commit(&ctx).await?;
    7405              : 
    7406            1 :         let child_timeline_id = TimelineId::generate();
    7407            1 :         tenant
    7408            1 :             .branch_timeline_test(
    7409            1 :                 tline,
    7410            1 :                 child_timeline_id,
    7411            1 :                 Some(tline.get_last_record_lsn()),
    7412            1 :                 &ctx,
    7413            1 :             )
    7414            1 :             .await?;
    7415              : 
    7416            1 :         let child_timeline = tenant
    7417            1 :             .get_timeline(child_timeline_id, true)
    7418            1 :             .expect("Should have the branched timeline");
    7419              : 
    7420            1 :         let aux_keyspace = KeySpace {
    7421            1 :             ranges: vec![NON_INHERITED_RANGE],
    7422            1 :         };
    7423            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7424              : 
    7425            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7426              : 
    7427            1 :         let vectored_res = child_timeline
    7428            1 :             .get_vectored_impl(
    7429            1 :                 query,
    7430            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7431            1 :                 &ctx,
    7432            1 :             )
    7433            1 :             .await;
    7434              : 
    7435            1 :         let images = vectored_res?;
    7436            1 :         assert!(images.is_empty());
    7437            2 :         Ok(())
    7438            1 :     }
    7439              : 
    7440              :     // Test that vectored get handles layer gaps correctly
    7441              :     // by advancing into the next ancestor timeline if required.
    7442              :     //
    7443              :     // The test generates timelines that look like the diagram below.
    7444              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7445              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7446              :     //
    7447              :     // ```
    7448              :     //-------------------------------+
    7449              :     //                          ...  |
    7450              :     //               [   L1   ]      |
    7451              :     //     [ / L1   ]                | Child Timeline
    7452              :     // ...                           |
    7453              :     // ------------------------------+
    7454              :     //     [ X L1   ]                | Parent Timeline
    7455              :     // ------------------------------+
    7456              :     // ```
    7457              :     #[tokio::test]
    7458            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7459            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7460            1 :             // Make compaction deterministic
    7461            1 :             gc_period: Some(Duration::ZERO),
    7462            1 :             compaction_period: Some(Duration::ZERO),
    7463            1 :             // Encourage creation of L1 layers
    7464            1 :             checkpoint_distance: Some(16 * 1024),
    7465            1 :             compaction_target_size: Some(8 * 1024),
    7466            1 :             ..Default::default()
    7467            1 :         };
    7468              : 
    7469            1 :         let harness = TenantHarness::create_custom(
    7470            1 :             "test_get_vectored_key_gap",
    7471            1 :             tenant_conf,
    7472            1 :             TenantId::generate(),
    7473            1 :             ShardIdentity::unsharded(),
    7474            1 :             Generation::new(0xdeadbeef),
    7475            1 :         )
    7476            1 :         .await?;
    7477            1 :         let (tenant, ctx) = harness.load().await;
    7478            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7479              : 
    7480            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7481            1 :         let gap_at_key = current_key.add(100);
    7482            1 :         let mut current_lsn = Lsn(0x10);
    7483              : 
    7484              :         const KEY_COUNT: usize = 10_000;
    7485              : 
    7486            1 :         let timeline_id = TimelineId::generate();
    7487            1 :         let current_timeline = tenant
    7488            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7489            1 :             .await?;
    7490              : 
    7491            1 :         current_lsn += 0x100;
    7492              : 
    7493            1 :         let mut writer = current_timeline.writer().await;
    7494            1 :         writer
    7495            1 :             .put(
    7496            1 :                 gap_at_key,
    7497            1 :                 current_lsn,
    7498            1 :                 &Value::Image(test_img(&format!("{gap_at_key} at {current_lsn}"))),
    7499            1 :                 &ctx,
    7500            1 :             )
    7501            1 :             .await?;
    7502            1 :         writer.finish_write(current_lsn);
    7503            1 :         drop(writer);
    7504              : 
    7505            1 :         let mut latest_lsns = HashMap::new();
    7506            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7507              : 
    7508            1 :         current_timeline.freeze_and_flush().await?;
    7509              : 
    7510            1 :         let child_timeline_id = TimelineId::generate();
    7511              : 
    7512            1 :         tenant
    7513            1 :             .branch_timeline_test(
    7514            1 :                 &current_timeline,
    7515            1 :                 child_timeline_id,
    7516            1 :                 Some(current_lsn),
    7517            1 :                 &ctx,
    7518            1 :             )
    7519            1 :             .await?;
    7520            1 :         let child_timeline = tenant
    7521            1 :             .get_timeline(child_timeline_id, true)
    7522            1 :             .expect("Should have the branched timeline");
    7523              : 
    7524        10001 :         for i in 0..KEY_COUNT {
    7525        10000 :             if current_key == gap_at_key {
    7526            1 :                 current_key = current_key.next();
    7527            1 :                 continue;
    7528         9999 :             }
    7529              : 
    7530         9999 :             current_lsn += 0x10;
    7531              : 
    7532         9999 :             let mut writer = child_timeline.writer().await;
    7533         9999 :             writer
    7534         9999 :                 .put(
    7535         9999 :                     current_key,
    7536         9999 :                     current_lsn,
    7537         9999 :                     &Value::Image(test_img(&format!("{current_key} at {current_lsn}"))),
    7538         9999 :                     &ctx,
    7539         9999 :                 )
    7540         9999 :                 .await?;
    7541         9999 :             writer.finish_write(current_lsn);
    7542         9999 :             drop(writer);
    7543              : 
    7544         9999 :             latest_lsns.insert(current_key, current_lsn);
    7545         9999 :             current_key = current_key.next();
    7546              : 
    7547              :             // Flush every now and then to encourage layer file creation.
    7548         9999 :             if i % 500 == 0 {
    7549           20 :                 child_timeline.freeze_and_flush().await?;
    7550         9979 :             }
    7551              :         }
    7552              : 
    7553            1 :         child_timeline.freeze_and_flush().await?;
    7554            1 :         let mut flags = EnumSet::new();
    7555            1 :         flags.insert(CompactFlags::ForceRepartition);
    7556            1 :         child_timeline
    7557            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7558            1 :             .await?;
    7559              : 
    7560            1 :         let key_near_end = {
    7561            1 :             let mut tmp = current_key;
    7562            1 :             tmp.field6 -= 10;
    7563            1 :             tmp
    7564              :         };
    7565              : 
    7566            1 :         let key_near_gap = {
    7567            1 :             let mut tmp = gap_at_key;
    7568            1 :             tmp.field6 -= 10;
    7569            1 :             tmp
    7570              :         };
    7571              : 
    7572            1 :         let read = KeySpace {
    7573            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7574            1 :         };
    7575              : 
    7576            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7577              : 
    7578            1 :         let results = child_timeline
    7579            1 :             .get_vectored_impl(
    7580            1 :                 query,
    7581            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7582            1 :                 &ctx,
    7583            1 :             )
    7584            1 :             .await?;
    7585              : 
    7586           22 :         for (key, img_res) in results {
    7587           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7588           21 :             assert_eq!(img_res?, expected);
    7589            1 :         }
    7590            1 : 
    7591            1 :         Ok(())
    7592            1 :     }
    7593              : 
    7594              :     // Test that vectored get descends into ancestor timelines correctly and
    7595              :     // does not return an image that's newer than requested.
    7596              :     //
    7597              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7598              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7599              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7600              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7601              :     // order to avoid returning an image that's too new. The test below constructs such
    7602              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7603              :     // ```
    7604              :     //    LSN
    7605              :     //     ^
    7606              :     //     |
    7607              :     //     |
    7608              :     // 500 | --------------------------------------> branch point
    7609              :     // 400 |        X
    7610              :     // 300 |        X
    7611              :     // 200 | --------------------------------------> requested lsn
    7612              :     // 100 |        X
    7613              :     //     |---------------------------------------> Key
    7614              :     //              |
    7615              :     //              ------> requested key
    7616              :     //
    7617              :     // Legend:
    7618              :     // * X - page images
    7619              :     // ```
    7620              :     #[tokio::test]
    7621            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7622            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7623            1 :         let (tenant, ctx) = harness.load().await;
    7624            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7625              : 
    7626            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7627            1 :         let end_key = start_key.add(1000);
    7628            1 :         let child_gap_at_key = start_key.add(500);
    7629            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7630              : 
    7631            1 :         let mut current_lsn = Lsn(0x10);
    7632              : 
    7633            1 :         let timeline_id = TimelineId::generate();
    7634            1 :         let parent_timeline = tenant
    7635            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7636            1 :             .await?;
    7637              : 
    7638            1 :         current_lsn += 0x100;
    7639              : 
    7640            4 :         for _ in 0..3 {
    7641            3 :             let mut key = start_key;
    7642         3003 :             while key < end_key {
    7643         3000 :                 current_lsn += 0x10;
    7644              : 
    7645         3000 :                 let image_value = format!("{child_gap_at_key} at {current_lsn}");
    7646              : 
    7647         3000 :                 let mut writer = parent_timeline.writer().await;
    7648         3000 :                 writer
    7649         3000 :                     .put(
    7650         3000 :                         key,
    7651         3000 :                         current_lsn,
    7652         3000 :                         &Value::Image(test_img(&image_value)),
    7653         3000 :                         &ctx,
    7654         3000 :                     )
    7655         3000 :                     .await?;
    7656         3000 :                 writer.finish_write(current_lsn);
    7657              : 
    7658         3000 :                 if key == child_gap_at_key {
    7659            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7660         2997 :                 }
    7661              : 
    7662         3000 :                 key = key.next();
    7663              :             }
    7664              : 
    7665            3 :             parent_timeline.freeze_and_flush().await?;
    7666              :         }
    7667              : 
    7668            1 :         let child_timeline_id = TimelineId::generate();
    7669              : 
    7670            1 :         let child_timeline = tenant
    7671            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7672            1 :             .await?;
    7673              : 
    7674            1 :         let mut key = start_key;
    7675         1001 :         while key < end_key {
    7676         1000 :             if key == child_gap_at_key {
    7677            1 :                 key = key.next();
    7678            1 :                 continue;
    7679          999 :             }
    7680              : 
    7681          999 :             current_lsn += 0x10;
    7682              : 
    7683          999 :             let mut writer = child_timeline.writer().await;
    7684          999 :             writer
    7685          999 :                 .put(
    7686          999 :                     key,
    7687          999 :                     current_lsn,
    7688          999 :                     &Value::Image(test_img(&format!("{key} at {current_lsn}"))),
    7689          999 :                     &ctx,
    7690          999 :                 )
    7691          999 :                 .await?;
    7692          999 :             writer.finish_write(current_lsn);
    7693              : 
    7694          999 :             key = key.next();
    7695              :         }
    7696              : 
    7697            1 :         child_timeline.freeze_and_flush().await?;
    7698              : 
    7699            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7700            1 :         let mut query_lsns = Vec::new();
    7701            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7702           18 :             for offset in lsn_offsets {
    7703           15 :                 query_lsns.push(Lsn(image_lsn
    7704           15 :                     .0
    7705           15 :                     .checked_add_signed(offset)
    7706           15 :                     .expect("Shouldn't overflow")));
    7707           15 :             }
    7708            1 :         }
    7709            1 : 
    7710           16 :         for query_lsn in query_lsns {
    7711           15 :             let query = VersionedKeySpaceQuery::uniform(
    7712           15 :                 KeySpace {
    7713           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7714           15 :                 },
    7715           15 :                 query_lsn,
    7716            1 :             );
    7717            1 : 
    7718           15 :             let results = child_timeline
    7719           15 :                 .get_vectored_impl(
    7720           15 :                     query,
    7721           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7722           15 :                     &ctx,
    7723           15 :                 )
    7724           15 :                 .await;
    7725            1 : 
    7726           15 :             let expected_item = parent_gap_lsns
    7727           15 :                 .iter()
    7728           15 :                 .rev()
    7729           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7730            1 : 
    7731           15 :             info!(
    7732            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7733            1 :                 query_lsn, expected_item
    7734            1 :             );
    7735            1 : 
    7736           15 :             match expected_item {
    7737           13 :                 Some((_, img_value)) => {
    7738           13 :                     let key_results = results.expect("No vectored get error expected");
    7739           13 :                     let key_result = &key_results[&child_gap_at_key];
    7740           13 :                     let returned_img = key_result
    7741           13 :                         .as_ref()
    7742           13 :                         .expect("No page reconstruct error expected");
    7743            1 : 
    7744           13 :                     info!(
    7745            1 :                         "Vectored read at LSN {} returned image {}",
    7746            1 :                         query_lsn,
    7747            1 :                         std::str::from_utf8(returned_img)?
    7748            1 :                     );
    7749           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7750            1 :                 }
    7751            1 :                 None => {
    7752            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7753            1 :                 }
    7754            1 :             }
    7755            1 :         }
    7756            1 : 
    7757            1 :         Ok(())
    7758            1 :     }
    7759              : 
    7760              :     #[tokio::test]
    7761            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7762            1 :         let names_algorithms = [
    7763            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7764            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7765            1 :         ];
    7766            3 :         for (name, algorithm) in names_algorithms {
    7767            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7768            1 :         }
    7769            1 :         Ok(())
    7770            1 :     }
    7771              : 
    7772            2 :     async fn test_random_updates_algorithm(
    7773            2 :         name: &'static str,
    7774            2 :         compaction_algorithm: CompactionAlgorithm,
    7775            2 :     ) -> anyhow::Result<()> {
    7776            2 :         let mut harness = TenantHarness::create(name).await?;
    7777            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7778            2 :             kind: compaction_algorithm,
    7779            2 :         });
    7780            2 :         let (tenant, ctx) = harness.load().await;
    7781            2 :         let tline = tenant
    7782            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7783            2 :             .await?;
    7784              : 
    7785              :         const NUM_KEYS: usize = 1000;
    7786            2 :         let cancel = CancellationToken::new();
    7787              : 
    7788            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7789            2 :         let mut test_key_end = test_key;
    7790            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7791            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7792              : 
    7793            2 :         let mut keyspace = KeySpaceAccum::new();
    7794              : 
    7795              :         // Track when each page was last modified. Used to assert that
    7796              :         // a read sees the latest page version.
    7797            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7798              : 
    7799            2 :         let mut lsn = Lsn(0x10);
    7800              :         #[allow(clippy::needless_range_loop)]
    7801         2002 :         for blknum in 0..NUM_KEYS {
    7802         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7803         2000 :             test_key.field6 = blknum as u32;
    7804         2000 :             let mut writer = tline.writer().await;
    7805         2000 :             writer
    7806         2000 :                 .put(
    7807         2000 :                     test_key,
    7808         2000 :                     lsn,
    7809         2000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7810         2000 :                     &ctx,
    7811         2000 :                 )
    7812         2000 :                 .await?;
    7813         2000 :             writer.finish_write(lsn);
    7814         2000 :             updated[blknum] = lsn;
    7815         2000 :             drop(writer);
    7816              : 
    7817         2000 :             keyspace.add_key(test_key);
    7818              :         }
    7819              : 
    7820          102 :         for _ in 0..50 {
    7821       100100 :             for _ in 0..NUM_KEYS {
    7822       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7823       100000 :                 let blknum = rand::rng().random_range(0..NUM_KEYS);
    7824       100000 :                 test_key.field6 = blknum as u32;
    7825       100000 :                 let mut writer = tline.writer().await;
    7826       100000 :                 writer
    7827       100000 :                     .put(
    7828       100000 :                         test_key,
    7829       100000 :                         lsn,
    7830       100000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7831       100000 :                         &ctx,
    7832       100000 :                     )
    7833       100000 :                     .await?;
    7834       100000 :                 writer.finish_write(lsn);
    7835       100000 :                 drop(writer);
    7836       100000 :                 updated[blknum] = lsn;
    7837              :             }
    7838              : 
    7839              :             // Read all the blocks
    7840       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7841       100000 :                 test_key.field6 = blknum as u32;
    7842       100000 :                 assert_eq!(
    7843       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7844       100000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7845              :                 );
    7846              :             }
    7847              : 
    7848              :             // Perform a cycle of flush, and GC
    7849          100 :             tline.freeze_and_flush().await?;
    7850          100 :             tenant
    7851          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7852          100 :                 .await?;
    7853              :         }
    7854              : 
    7855            2 :         Ok(())
    7856            2 :     }
    7857              : 
    7858              :     #[tokio::test]
    7859            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7860            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7861            1 :             .await?
    7862            1 :             .load()
    7863            1 :             .await;
    7864            1 :         let mut tline = tenant
    7865            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7866            1 :             .await?;
    7867              : 
    7868              :         const NUM_KEYS: usize = 1000;
    7869              : 
    7870            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7871              : 
    7872            1 :         let mut keyspace = KeySpaceAccum::new();
    7873              : 
    7874            1 :         let cancel = CancellationToken::new();
    7875              : 
    7876              :         // Track when each page was last modified. Used to assert that
    7877              :         // a read sees the latest page version.
    7878            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7879              : 
    7880            1 :         let mut lsn = Lsn(0x10);
    7881            1 :         #[allow(clippy::needless_range_loop)]
    7882         1001 :         for blknum in 0..NUM_KEYS {
    7883         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7884         1000 :             test_key.field6 = blknum as u32;
    7885         1000 :             let mut writer = tline.writer().await;
    7886         1000 :             writer
    7887         1000 :                 .put(
    7888         1000 :                     test_key,
    7889         1000 :                     lsn,
    7890         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7891         1000 :                     &ctx,
    7892         1000 :                 )
    7893         1000 :                 .await?;
    7894         1000 :             writer.finish_write(lsn);
    7895         1000 :             updated[blknum] = lsn;
    7896         1000 :             drop(writer);
    7897            1 : 
    7898         1000 :             keyspace.add_key(test_key);
    7899            1 :         }
    7900            1 : 
    7901           51 :         for _ in 0..50 {
    7902           50 :             let new_tline_id = TimelineId::generate();
    7903           50 :             tenant
    7904           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7905           50 :                 .await?;
    7906           50 :             tline = tenant
    7907           50 :                 .get_timeline(new_tline_id, true)
    7908           50 :                 .expect("Should have the branched timeline");
    7909            1 : 
    7910        50050 :             for _ in 0..NUM_KEYS {
    7911        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7912        50000 :                 let blknum = rand::rng().random_range(0..NUM_KEYS);
    7913        50000 :                 test_key.field6 = blknum as u32;
    7914        50000 :                 let mut writer = tline.writer().await;
    7915        50000 :                 writer
    7916        50000 :                     .put(
    7917        50000 :                         test_key,
    7918        50000 :                         lsn,
    7919        50000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7920        50000 :                         &ctx,
    7921        50000 :                     )
    7922        50000 :                     .await?;
    7923        50000 :                 println!("updating {blknum} at {lsn}");
    7924        50000 :                 writer.finish_write(lsn);
    7925        50000 :                 drop(writer);
    7926        50000 :                 updated[blknum] = lsn;
    7927            1 :             }
    7928            1 : 
    7929            1 :             // Read all the blocks
    7930        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7931        50000 :                 test_key.field6 = blknum as u32;
    7932        50000 :                 assert_eq!(
    7933        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7934        50000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7935            1 :                 );
    7936            1 :             }
    7937            1 : 
    7938            1 :             // Perform a cycle of flush, compact, and GC
    7939           50 :             tline.freeze_and_flush().await?;
    7940           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7941           50 :             tenant
    7942           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7943           50 :                 .await?;
    7944            1 :         }
    7945            1 : 
    7946            1 :         Ok(())
    7947            1 :     }
    7948              : 
    7949              :     #[tokio::test]
    7950            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7951            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7952            1 :             .await?
    7953            1 :             .load()
    7954            1 :             .await;
    7955            1 :         let mut tline = tenant
    7956            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7957            1 :             .await?;
    7958              : 
    7959              :         const NUM_KEYS: usize = 100;
    7960              :         const NUM_TLINES: usize = 50;
    7961              : 
    7962            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7963              :         // Track page mutation lsns across different timelines.
    7964            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7965              : 
    7966            1 :         let mut lsn = Lsn(0x10);
    7967              : 
    7968            1 :         #[allow(clippy::needless_range_loop)]
    7969           51 :         for idx in 0..NUM_TLINES {
    7970           50 :             let new_tline_id = TimelineId::generate();
    7971           50 :             tenant
    7972           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7973           50 :                 .await?;
    7974           50 :             tline = tenant
    7975           50 :                 .get_timeline(new_tline_id, true)
    7976           50 :                 .expect("Should have the branched timeline");
    7977            1 : 
    7978         5050 :             for _ in 0..NUM_KEYS {
    7979         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7980         5000 :                 let blknum = rand::rng().random_range(0..NUM_KEYS);
    7981         5000 :                 test_key.field6 = blknum as u32;
    7982         5000 :                 let mut writer = tline.writer().await;
    7983         5000 :                 writer
    7984         5000 :                     .put(
    7985         5000 :                         test_key,
    7986         5000 :                         lsn,
    7987         5000 :                         &Value::Image(test_img(&format!("{idx} {blknum} at {lsn}"))),
    7988         5000 :                         &ctx,
    7989         5000 :                     )
    7990         5000 :                     .await?;
    7991         5000 :                 println!("updating [{idx}][{blknum}] at {lsn}");
    7992         5000 :                 writer.finish_write(lsn);
    7993         5000 :                 drop(writer);
    7994         5000 :                 updated[idx][blknum] = lsn;
    7995            1 :             }
    7996            1 :         }
    7997            1 : 
    7998            1 :         // Read pages from leaf timeline across all ancestors.
    7999           50 :         for (idx, lsns) in updated.iter().enumerate() {
    8000         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    8001            1 :                 // Skip empty mutations.
    8002         5000 :                 if lsn.0 == 0 {
    8003         1815 :                     continue;
    8004         3185 :                 }
    8005         3185 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    8006         3185 :                 test_key.field6 = blknum as u32;
    8007         3185 :                 assert_eq!(
    8008         3185 :                     tline.get(test_key, *lsn, &ctx).await?,
    8009         3185 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    8010            1 :                 );
    8011            1 :             }
    8012            1 :         }
    8013            1 :         Ok(())
    8014            1 :     }
    8015              : 
    8016              :     #[tokio::test]
    8017            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    8018            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    8019            1 :             .await?
    8020            1 :             .load()
    8021            1 :             .await;
    8022              : 
    8023            1 :         let initdb_lsn = Lsn(0x20);
    8024            1 :         let (utline, ctx) = tenant
    8025            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    8026            1 :             .await?;
    8027            1 :         let tline = utline.raw_timeline().unwrap();
    8028              : 
    8029              :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    8030            1 :         tline.maybe_spawn_flush_loop();
    8031              : 
    8032              :         // Make sure the timeline has the minimum set of required keys for operation.
    8033              :         // The only operation you can always do on an empty timeline is to `put` new data.
    8034              :         // Except if you `put` at `initdb_lsn`.
    8035              :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    8036              :         // It uses `repartition()`, which assumes some keys to be present.
    8037              :         // Let's make sure the test timeline can handle that case.
    8038              :         {
    8039            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    8040            1 :             assert_eq!(
    8041              :                 timeline::FlushLoopState::Running {
    8042              :                     expect_initdb_optimization: false,
    8043              :                     initdb_optimization_count: 0,
    8044              :                 },
    8045            1 :                 *state
    8046              :             );
    8047            1 :             *state = timeline::FlushLoopState::Running {
    8048            1 :                 expect_initdb_optimization: true,
    8049            1 :                 initdb_optimization_count: 0,
    8050            1 :             };
    8051              :         }
    8052              : 
    8053              :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    8054              :         // As explained above, the optimization requires some keys to be present.
    8055              :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    8056              :         // This is what `create_test_timeline` does, by the way.
    8057            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    8058            1 :         modification
    8059            1 :             .init_empty_test_timeline()
    8060            1 :             .context("init_empty_test_timeline")?;
    8061            1 :         modification
    8062            1 :             .commit(&ctx)
    8063            1 :             .await
    8064            1 :             .context("commit init_empty_test_timeline modification")?;
    8065              : 
    8066              :         // Do the flush. The flush code will check the expectations that we set above.
    8067            1 :         tline.freeze_and_flush().await?;
    8068              : 
    8069              :         // assert freeze_and_flush exercised the initdb optimization
    8070            1 :         {
    8071            1 :             let state = tline.flush_loop_state.lock().unwrap();
    8072            1 :             let timeline::FlushLoopState::Running {
    8073            1 :                 expect_initdb_optimization,
    8074            1 :                 initdb_optimization_count,
    8075            1 :             } = *state
    8076            1 :             else {
    8077            1 :                 panic!("unexpected state: {:?}", *state);
    8078            1 :             };
    8079            1 :             assert!(expect_initdb_optimization);
    8080            1 :             assert!(initdb_optimization_count > 0);
    8081            1 :         }
    8082            1 :         Ok(())
    8083            1 :     }
    8084              : 
    8085              :     #[tokio::test]
    8086            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    8087            1 :         let name = "test_create_guard_crash";
    8088            1 :         let harness = TenantHarness::create(name).await?;
    8089              :         {
    8090            1 :             let (tenant, ctx) = harness.load().await;
    8091            1 :             let (tline, _ctx) = tenant
    8092            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    8093            1 :                 .await?;
    8094              :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    8095            1 :             let raw_tline = tline.raw_timeline().unwrap();
    8096            1 :             raw_tline
    8097            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    8098            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))
    8099            1 :                 .await;
    8100            1 :             std::mem::forget(tline);
    8101              :         }
    8102              : 
    8103            1 :         let (tenant, _) = harness.load().await;
    8104            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    8105            0 :             Ok(_) => panic!("timeline should've been removed during load"),
    8106            1 :             Err(e) => {
    8107            1 :                 assert_eq!(
    8108              :                     e,
    8109            1 :                     GetTimelineError::NotFound {
    8110            1 :                         tenant_id: tenant.tenant_shard_id,
    8111            1 :                         timeline_id: TIMELINE_ID,
    8112            1 :                     }
    8113              :                 )
    8114              :             }
    8115              :         }
    8116              : 
    8117            1 :         assert!(
    8118            1 :             !harness
    8119            1 :                 .conf
    8120            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    8121            1 :                 .exists()
    8122              :         );
    8123              : 
    8124            2 :         Ok(())
    8125            1 :     }
    8126              : 
    8127              :     #[tokio::test]
    8128            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    8129            1 :         let names_algorithms = [
    8130            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    8131            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    8132            1 :         ];
    8133            3 :         for (name, algorithm) in names_algorithms {
    8134            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    8135            1 :         }
    8136            1 :         Ok(())
    8137            1 :     }
    8138              : 
    8139            2 :     async fn test_read_at_max_lsn_algorithm(
    8140            2 :         name: &'static str,
    8141            2 :         compaction_algorithm: CompactionAlgorithm,
    8142            2 :     ) -> anyhow::Result<()> {
    8143            2 :         let mut harness = TenantHarness::create(name).await?;
    8144            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    8145            2 :             kind: compaction_algorithm,
    8146            2 :         });
    8147            2 :         let (tenant, ctx) = harness.load().await;
    8148            2 :         let tline = tenant
    8149            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    8150            2 :             .await?;
    8151              : 
    8152            2 :         let lsn = Lsn(0x10);
    8153            2 :         let compact = false;
    8154            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    8155              : 
    8156            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8157            2 :         let read_lsn = Lsn(u64::MAX - 1);
    8158              : 
    8159            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    8160            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    8161              : 
    8162            2 :         Ok(())
    8163            2 :     }
    8164              : 
    8165              :     #[tokio::test]
    8166            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    8167            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    8168            1 :         let (tenant, ctx) = harness.load().await;
    8169            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8170            1 :         let tline = tenant
    8171            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8172            1 :             .await?;
    8173              : 
    8174              :         const NUM_KEYS: usize = 1000;
    8175              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8176              : 
    8177            1 :         let cancel = CancellationToken::new();
    8178              : 
    8179            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8180            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8181            1 :         let mut test_key = base_key;
    8182              : 
    8183              :         // Track when each page was last modified. Used to assert that
    8184              :         // a read sees the latest page version.
    8185            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    8186              : 
    8187            1 :         let mut lsn = Lsn(0x10);
    8188              :         #[allow(clippy::needless_range_loop)]
    8189         1001 :         for blknum in 0..NUM_KEYS {
    8190         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8191         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8192         1000 :             let mut writer = tline.writer().await;
    8193         1000 :             writer
    8194         1000 :                 .put(
    8195         1000 :                     test_key,
    8196         1000 :                     lsn,
    8197         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8198         1000 :                     &ctx,
    8199         1000 :                 )
    8200         1000 :                 .await?;
    8201         1000 :             writer.finish_write(lsn);
    8202         1000 :             updated[blknum] = lsn;
    8203         1000 :             drop(writer);
    8204              :         }
    8205              : 
    8206            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8207              : 
    8208           12 :         for iter in 0..=10 {
    8209            1 :             // Read all the blocks
    8210        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8211        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8212        11000 :                 assert_eq!(
    8213        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8214        11000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    8215            1 :                 );
    8216            1 :             }
    8217            1 : 
    8218           11 :             let mut cnt = 0;
    8219           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8220            1 : 
    8221        11000 :             for (key, value) in tline
    8222           11 :                 .get_vectored_impl(
    8223           11 :                     query,
    8224           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8225           11 :                     &ctx,
    8226           11 :                 )
    8227           11 :                 .await?
    8228            1 :             {
    8229        11000 :                 let blknum = key.field6 as usize;
    8230        11000 :                 let value = value?;
    8231        11000 :                 assert!(blknum % STEP == 0);
    8232        11000 :                 let blknum = blknum / STEP;
    8233        11000 :                 assert_eq!(
    8234            1 :                     value,
    8235        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8236            1 :                 );
    8237        11000 :                 cnt += 1;
    8238            1 :             }
    8239            1 : 
    8240           11 :             assert_eq!(cnt, NUM_KEYS);
    8241            1 : 
    8242        11011 :             for _ in 0..NUM_KEYS {
    8243        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8244        11000 :                 let blknum = rand::rng().random_range(0..NUM_KEYS);
    8245        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8246        11000 :                 let mut writer = tline.writer().await;
    8247        11000 :                 writer
    8248        11000 :                     .put(
    8249        11000 :                         test_key,
    8250        11000 :                         lsn,
    8251        11000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8252        11000 :                         &ctx,
    8253        11000 :                     )
    8254        11000 :                     .await?;
    8255        11000 :                 writer.finish_write(lsn);
    8256        11000 :                 drop(writer);
    8257        11000 :                 updated[blknum] = lsn;
    8258            1 :             }
    8259            1 : 
    8260            1 :             // Perform two cycles of flush, compact, and GC
    8261           33 :             for round in 0..2 {
    8262           22 :                 tline.freeze_and_flush().await?;
    8263           22 :                 tline
    8264           22 :                     .compact(
    8265           22 :                         &cancel,
    8266           22 :                         if iter % 5 == 0 && round == 0 {
    8267            3 :                             let mut flags = EnumSet::new();
    8268            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8269            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8270            3 :                             flags
    8271            1 :                         } else {
    8272           19 :                             EnumSet::empty()
    8273            1 :                         },
    8274           22 :                         &ctx,
    8275            1 :                     )
    8276           22 :                     .await?;
    8277           22 :                 tenant
    8278           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8279           22 :                     .await?;
    8280            1 :             }
    8281            1 :         }
    8282            1 : 
    8283            1 :         Ok(())
    8284            1 :     }
    8285              : 
    8286              :     #[tokio::test]
    8287            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8288            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8289            1 :         let (tenant, ctx) = harness.load().await;
    8290            1 :         let tline = tenant
    8291            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8292            1 :             .await?;
    8293              : 
    8294            1 :         let cancel = CancellationToken::new();
    8295              : 
    8296            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8297            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8298            1 :         let test_key = base_key;
    8299            1 :         let mut lsn = Lsn(0x10);
    8300              : 
    8301           21 :         for _ in 0..20 {
    8302           20 :             lsn = Lsn(lsn.0 + 0x10);
    8303           20 :             let mut writer = tline.writer().await;
    8304           20 :             writer
    8305           20 :                 .put(
    8306           20 :                     test_key,
    8307           20 :                     lsn,
    8308           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8309           20 :                     &ctx,
    8310           20 :                 )
    8311           20 :                 .await?;
    8312           20 :             writer.finish_write(lsn);
    8313           20 :             drop(writer);
    8314           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8315              :         }
    8316              : 
    8317            1 :         let before_num_l0_delta_files = tline
    8318            1 :             .layers
    8319            1 :             .read(LayerManagerLockHolder::Testing)
    8320            1 :             .await
    8321            1 :             .layer_map()?
    8322            1 :             .level0_deltas()
    8323            1 :             .len();
    8324              : 
    8325            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8326              : 
    8327            1 :         let after_num_l0_delta_files = tline
    8328            1 :             .layers
    8329            1 :             .read(LayerManagerLockHolder::Testing)
    8330            1 :             .await
    8331            1 :             .layer_map()?
    8332            1 :             .level0_deltas()
    8333            1 :             .len();
    8334              : 
    8335            1 :         assert!(
    8336            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8337            0 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8338              :         );
    8339              : 
    8340            1 :         assert_eq!(
    8341            1 :             tline.get(test_key, lsn, &ctx).await?,
    8342            1 :             test_img(&format!("{} at {}", 0, lsn))
    8343              :         );
    8344              : 
    8345            2 :         Ok(())
    8346            1 :     }
    8347              : 
    8348              :     #[tokio::test]
    8349            1 :     async fn test_aux_file_e2e() {
    8350            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8351              : 
    8352            1 :         let (tenant, ctx) = harness.load().await;
    8353            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8354              : 
    8355            1 :         let mut lsn = Lsn(0x08);
    8356              : 
    8357            1 :         let tline: Arc<Timeline> = tenant
    8358            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8359            1 :             .await
    8360            1 :             .unwrap();
    8361              : 
    8362              :         {
    8363            1 :             lsn += 8;
    8364            1 :             let mut modification = tline.begin_modification(lsn);
    8365            1 :             modification
    8366            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8367            1 :                 .await
    8368            1 :                 .unwrap();
    8369            1 :             modification.commit(&ctx).await.unwrap();
    8370              :         }
    8371              : 
    8372              :         // we can read everything from the storage
    8373            1 :         let files = tline
    8374            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8375            1 :             .await
    8376            1 :             .unwrap();
    8377            1 :         assert_eq!(
    8378            1 :             files.get("pg_logical/mappings/test1"),
    8379            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8380              :         );
    8381              : 
    8382              :         {
    8383            1 :             lsn += 8;
    8384            1 :             let mut modification = tline.begin_modification(lsn);
    8385            1 :             modification
    8386            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8387            1 :                 .await
    8388            1 :                 .unwrap();
    8389            1 :             modification.commit(&ctx).await.unwrap();
    8390              :         }
    8391              : 
    8392            1 :         let files = tline
    8393            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8394            1 :             .await
    8395            1 :             .unwrap();
    8396            1 :         assert_eq!(
    8397            1 :             files.get("pg_logical/mappings/test2"),
    8398            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8399              :         );
    8400              : 
    8401            1 :         let child = tenant
    8402            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8403            1 :             .await
    8404            1 :             .unwrap();
    8405              : 
    8406            1 :         let files = child
    8407            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8408            1 :             .await
    8409            1 :             .unwrap();
    8410            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8411            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8412            1 :     }
    8413              : 
    8414              :     #[tokio::test]
    8415            1 :     async fn test_repl_origin_tombstones() {
    8416            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8417            1 :             .await
    8418            1 :             .unwrap();
    8419              : 
    8420            1 :         let (tenant, ctx) = harness.load().await;
    8421            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8422              : 
    8423            1 :         let mut lsn = Lsn(0x08);
    8424              : 
    8425            1 :         let tline: Arc<Timeline> = tenant
    8426            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8427            1 :             .await
    8428            1 :             .unwrap();
    8429              : 
    8430            1 :         let repl_lsn = Lsn(0x10);
    8431              :         {
    8432            1 :             lsn += 8;
    8433            1 :             let mut modification = tline.begin_modification(lsn);
    8434            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8435            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8436            1 :             modification.commit(&ctx).await.unwrap();
    8437              :         }
    8438              : 
    8439              :         // we can read everything from the storage
    8440            1 :         let repl_origins = tline
    8441            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8442            1 :             .await
    8443            1 :             .unwrap();
    8444            1 :         assert_eq!(repl_origins.len(), 1);
    8445            1 :         assert_eq!(repl_origins[&1], lsn);
    8446              : 
    8447              :         {
    8448            1 :             lsn += 8;
    8449            1 :             let mut modification = tline.begin_modification(lsn);
    8450            1 :             modification.put_for_unit_test(
    8451            1 :                 repl_origin_key(3),
    8452            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8453              :             );
    8454            1 :             modification.commit(&ctx).await.unwrap();
    8455              :         }
    8456            1 :         let result = tline
    8457            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8458            1 :             .await;
    8459            1 :         assert!(result.is_err());
    8460            1 :     }
    8461              : 
    8462              :     #[tokio::test]
    8463            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8464            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8465            1 :         let (tenant, ctx) = harness.load().await;
    8466            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8467            1 :         let tline = tenant
    8468            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8469            1 :             .await?;
    8470              : 
    8471              :         const NUM_KEYS: usize = 1000;
    8472              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8473              : 
    8474            1 :         let cancel = CancellationToken::new();
    8475              : 
    8476            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8477            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8478            1 :         let mut test_key = base_key;
    8479            1 :         let mut lsn = Lsn(0x10);
    8480              : 
    8481            4 :         async fn scan_with_statistics(
    8482            4 :             tline: &Timeline,
    8483            4 :             keyspace: &KeySpace,
    8484            4 :             lsn: Lsn,
    8485            4 :             ctx: &RequestContext,
    8486            4 :             io_concurrency: IoConcurrency,
    8487            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8488            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8489            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8490            4 :             let res = tline
    8491            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8492            4 :                 .await?;
    8493            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8494            4 :         }
    8495              : 
    8496         1001 :         for blknum in 0..NUM_KEYS {
    8497         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8498         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8499         1000 :             let mut writer = tline.writer().await;
    8500         1000 :             writer
    8501         1000 :                 .put(
    8502         1000 :                     test_key,
    8503         1000 :                     lsn,
    8504         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8505         1000 :                     &ctx,
    8506         1000 :                 )
    8507         1000 :                 .await?;
    8508         1000 :             writer.finish_write(lsn);
    8509         1000 :             drop(writer);
    8510              :         }
    8511              : 
    8512            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8513              : 
    8514           11 :         for iter in 1..=10 {
    8515        10010 :             for _ in 0..NUM_KEYS {
    8516        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8517        10000 :                 let blknum = rand::rng().random_range(0..NUM_KEYS);
    8518        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8519        10000 :                 let mut writer = tline.writer().await;
    8520        10000 :                 writer
    8521        10000 :                     .put(
    8522        10000 :                         test_key,
    8523        10000 :                         lsn,
    8524        10000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8525        10000 :                         &ctx,
    8526        10000 :                     )
    8527        10000 :                     .await?;
    8528        10000 :                 writer.finish_write(lsn);
    8529        10000 :                 drop(writer);
    8530            1 :             }
    8531            1 : 
    8532           10 :             tline.freeze_and_flush().await?;
    8533            1 :             // Force layers to L1
    8534           10 :             tline
    8535           10 :                 .compact(
    8536           10 :                     &cancel,
    8537           10 :                     {
    8538           10 :                         let mut flags = EnumSet::new();
    8539           10 :                         flags.insert(CompactFlags::ForceL0Compaction);
    8540           10 :                         flags
    8541           10 :                     },
    8542           10 :                     &ctx,
    8543           10 :                 )
    8544           10 :                 .await?;
    8545            1 : 
    8546           10 :             if iter % 5 == 0 {
    8547            2 :                 let scan_lsn = Lsn(lsn.0 + 1);
    8548            2 :                 info!("scanning at {}", scan_lsn);
    8549            2 :                 let (_, before_delta_file_accessed) =
    8550            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8551            2 :                         .await?;
    8552            2 :                 tline
    8553            2 :                     .compact(
    8554            2 :                         &cancel,
    8555            2 :                         {
    8556            2 :                             let mut flags = EnumSet::new();
    8557            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8558            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8559            2 :                             flags.insert(CompactFlags::ForceL0Compaction);
    8560            2 :                             flags
    8561            2 :                         },
    8562            2 :                         &ctx,
    8563            2 :                     )
    8564            2 :                     .await?;
    8565            2 :                 let (_, after_delta_file_accessed) =
    8566            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8567            2 :                         .await?;
    8568            2 :                 assert!(
    8569            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8570            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8571            1 :                 );
    8572            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.
    8573            2 :                 assert!(
    8574            2 :                     after_delta_file_accessed <= 2,
    8575            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8576            1 :                 );
    8577            8 :             }
    8578            1 :         }
    8579            1 : 
    8580            1 :         Ok(())
    8581            1 :     }
    8582              : 
    8583              :     #[tokio::test]
    8584            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8585            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8586            1 :         let (tenant, ctx) = harness.load().await;
    8587              : 
    8588            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8589            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8590            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8591              : 
    8592            1 :         let tline = tenant
    8593            1 :             .create_test_timeline_with_layers(
    8594            1 :                 TIMELINE_ID,
    8595            1 :                 Lsn(0x10),
    8596            1 :                 DEFAULT_PG_VERSION,
    8597            1 :                 &ctx,
    8598            1 :                 Vec::new(), // in-memory layers
    8599            1 :                 Vec::new(), // delta layers
    8600            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8601            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
    8602            1 :             )
    8603            1 :             .await?;
    8604            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8605              : 
    8606            1 :         let child = tenant
    8607            1 :             .branch_timeline_test_with_layers(
    8608            1 :                 &tline,
    8609            1 :                 NEW_TIMELINE_ID,
    8610            1 :                 Some(Lsn(0x20)),
    8611            1 :                 &ctx,
    8612            1 :                 Vec::new(), // delta layers
    8613            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8614            1 :                 Lsn(0x30),
    8615            1 :             )
    8616            1 :             .await
    8617            1 :             .unwrap();
    8618              : 
    8619            1 :         let lsn = Lsn(0x30);
    8620              : 
    8621              :         // test vectored get on parent timeline
    8622            1 :         assert_eq!(
    8623            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8624            1 :             Some(test_img("data key 1"))
    8625              :         );
    8626            1 :         assert!(
    8627            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8628            1 :                 .await
    8629            1 :                 .unwrap_err()
    8630            1 :                 .is_missing_key_error()
    8631              :         );
    8632            1 :         assert!(
    8633            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8634            1 :                 .await
    8635            1 :                 .unwrap_err()
    8636            1 :                 .is_missing_key_error()
    8637              :         );
    8638              : 
    8639              :         // test vectored get on child timeline
    8640            1 :         assert_eq!(
    8641            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8642            1 :             Some(test_img("data key 1"))
    8643              :         );
    8644            1 :         assert_eq!(
    8645            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8646            1 :             Some(test_img("data key 2"))
    8647              :         );
    8648            1 :         assert!(
    8649            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8650            1 :                 .await
    8651            1 :                 .unwrap_err()
    8652            1 :                 .is_missing_key_error()
    8653              :         );
    8654              : 
    8655            2 :         Ok(())
    8656            1 :     }
    8657              : 
    8658              :     #[tokio::test]
    8659            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8660            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8661            1 :         let (tenant, ctx) = harness.load().await;
    8662            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8663              : 
    8664            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8665            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8666            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8667            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8668              : 
    8669            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8670            1 :         let base_inherited_key_child =
    8671            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8672            1 :         let base_inherited_key_nonexist =
    8673            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8674            1 :         let base_inherited_key_overwrite =
    8675            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8676              : 
    8677            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8678            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8679              : 
    8680            1 :         let tline = tenant
    8681            1 :             .create_test_timeline_with_layers(
    8682            1 :                 TIMELINE_ID,
    8683            1 :                 Lsn(0x10),
    8684            1 :                 DEFAULT_PG_VERSION,
    8685            1 :                 &ctx,
    8686            1 :                 Vec::new(), // in-memory layers
    8687            1 :                 Vec::new(), // delta layers
    8688            1 :                 vec![(
    8689            1 :                     Lsn(0x20),
    8690            1 :                     vec![
    8691            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8692            1 :                         (
    8693            1 :                             base_inherited_key_overwrite,
    8694            1 :                             test_img("metadata key overwrite 1a"),
    8695            1 :                         ),
    8696            1 :                         (base_key, test_img("metadata key 1")),
    8697            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8698            1 :                     ],
    8699            1 :                 )], // image layers
    8700            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
    8701            1 :             )
    8702            1 :             .await?;
    8703              : 
    8704            1 :         let child = tenant
    8705            1 :             .branch_timeline_test_with_layers(
    8706            1 :                 &tline,
    8707            1 :                 NEW_TIMELINE_ID,
    8708            1 :                 Some(Lsn(0x20)),
    8709            1 :                 &ctx,
    8710            1 :                 Vec::new(), // delta layers
    8711            1 :                 vec![(
    8712            1 :                     Lsn(0x30),
    8713            1 :                     vec![
    8714            1 :                         (
    8715            1 :                             base_inherited_key_child,
    8716            1 :                             test_img("metadata inherited key 2"),
    8717            1 :                         ),
    8718            1 :                         (
    8719            1 :                             base_inherited_key_overwrite,
    8720            1 :                             test_img("metadata key overwrite 2a"),
    8721            1 :                         ),
    8722            1 :                         (base_key_child, test_img("metadata key 2")),
    8723            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8724            1 :                     ],
    8725            1 :                 )], // image layers
    8726            1 :                 Lsn(0x30),
    8727            1 :             )
    8728            1 :             .await
    8729            1 :             .unwrap();
    8730              : 
    8731            1 :         let lsn = Lsn(0x30);
    8732              : 
    8733              :         // test vectored get on parent timeline
    8734            1 :         assert_eq!(
    8735            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8736            1 :             Some(test_img("metadata key 1"))
    8737              :         );
    8738            1 :         assert_eq!(
    8739            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8740              :             None
    8741              :         );
    8742            1 :         assert_eq!(
    8743            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8744              :             None
    8745              :         );
    8746            1 :         assert_eq!(
    8747            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8748            1 :             Some(test_img("metadata key overwrite 1b"))
    8749              :         );
    8750            1 :         assert_eq!(
    8751            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8752            1 :             Some(test_img("metadata inherited key 1"))
    8753              :         );
    8754            1 :         assert_eq!(
    8755            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8756              :             None
    8757              :         );
    8758            1 :         assert_eq!(
    8759            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8760              :             None
    8761              :         );
    8762            1 :         assert_eq!(
    8763            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8764            1 :             Some(test_img("metadata key overwrite 1a"))
    8765              :         );
    8766              : 
    8767              :         // test vectored get on child timeline
    8768            1 :         assert_eq!(
    8769            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8770              :             None
    8771              :         );
    8772            1 :         assert_eq!(
    8773            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8774            1 :             Some(test_img("metadata key 2"))
    8775              :         );
    8776            1 :         assert_eq!(
    8777            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8778              :             None
    8779              :         );
    8780            1 :         assert_eq!(
    8781            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8782            1 :             Some(test_img("metadata inherited key 1"))
    8783              :         );
    8784            1 :         assert_eq!(
    8785            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8786            1 :             Some(test_img("metadata inherited key 2"))
    8787              :         );
    8788            1 :         assert_eq!(
    8789            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8790              :             None
    8791              :         );
    8792            1 :         assert_eq!(
    8793            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8794            1 :             Some(test_img("metadata key overwrite 2b"))
    8795              :         );
    8796            1 :         assert_eq!(
    8797            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8798            1 :             Some(test_img("metadata key overwrite 2a"))
    8799              :         );
    8800              : 
    8801              :         // test vectored scan on parent timeline
    8802            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8803            1 :         let query =
    8804            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8805            1 :         let res = tline
    8806            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8807            1 :             .await?;
    8808              : 
    8809            1 :         assert_eq!(
    8810            1 :             res.into_iter()
    8811            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8812            1 :                 .collect::<Vec<_>>(),
    8813            1 :             vec![
    8814            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8815            1 :                 (
    8816            1 :                     base_inherited_key_overwrite,
    8817            1 :                     test_img("metadata key overwrite 1a")
    8818            1 :                 ),
    8819            1 :                 (base_key, test_img("metadata key 1")),
    8820            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8821              :             ]
    8822              :         );
    8823              : 
    8824              :         // test vectored scan on child timeline
    8825            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8826            1 :         let query =
    8827            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8828            1 :         let res = child
    8829            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8830            1 :             .await?;
    8831              : 
    8832            1 :         assert_eq!(
    8833            1 :             res.into_iter()
    8834            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8835            1 :                 .collect::<Vec<_>>(),
    8836            1 :             vec![
    8837            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8838            1 :                 (
    8839            1 :                     base_inherited_key_child,
    8840            1 :                     test_img("metadata inherited key 2")
    8841            1 :                 ),
    8842            1 :                 (
    8843            1 :                     base_inherited_key_overwrite,
    8844            1 :                     test_img("metadata key overwrite 2a")
    8845            1 :                 ),
    8846            1 :                 (base_key_child, test_img("metadata key 2")),
    8847            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8848              :             ]
    8849              :         );
    8850              : 
    8851            2 :         Ok(())
    8852            1 :     }
    8853              : 
    8854           28 :     async fn get_vectored_impl_wrapper(
    8855           28 :         tline: &Arc<Timeline>,
    8856           28 :         key: Key,
    8857           28 :         lsn: Lsn,
    8858           28 :         ctx: &RequestContext,
    8859           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8860           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8861           28 :             tline.conf.get_vectored_concurrent_io,
    8862           28 :             tline.gate.enter().unwrap(),
    8863              :         );
    8864           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8865           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8866           28 :         let mut res = tline
    8867           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8868           28 :             .await?;
    8869           25 :         Ok(res.pop_last().map(|(k, v)| {
    8870           16 :             assert_eq!(k, key);
    8871           16 :             v.unwrap()
    8872           16 :         }))
    8873           28 :     }
    8874              : 
    8875              :     #[tokio::test]
    8876            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8877            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8878            1 :         let (tenant, ctx) = harness.load().await;
    8879            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8880            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8881            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8882            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8883              : 
    8884              :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8885              :         // Lsn 0x30 key0, key3, no key1+key2
    8886              :         // Lsn 0x20 key1+key2 tomestones
    8887              :         // Lsn 0x10 key1 in image, key2 in delta
    8888            1 :         let tline = tenant
    8889            1 :             .create_test_timeline_with_layers(
    8890            1 :                 TIMELINE_ID,
    8891            1 :                 Lsn(0x10),
    8892            1 :                 DEFAULT_PG_VERSION,
    8893            1 :                 &ctx,
    8894            1 :                 Vec::new(), // in-memory layers
    8895            1 :                 // delta layers
    8896            1 :                 vec![
    8897            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8898            1 :                         Lsn(0x10)..Lsn(0x20),
    8899            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8900            1 :                     ),
    8901            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8902            1 :                         Lsn(0x20)..Lsn(0x30),
    8903            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8904            1 :                     ),
    8905            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8906            1 :                         Lsn(0x20)..Lsn(0x30),
    8907            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8908            1 :                     ),
    8909            1 :                 ],
    8910            1 :                 // image layers
    8911            1 :                 vec![
    8912            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8913            1 :                     (
    8914            1 :                         Lsn(0x30),
    8915            1 :                         vec![
    8916            1 :                             (key0, test_img("metadata key 0")),
    8917            1 :                             (key3, test_img("metadata key 3")),
    8918            1 :                         ],
    8919            1 :                     ),
    8920            1 :                 ],
    8921            1 :                 Lsn(0x30),
    8922            1 :             )
    8923            1 :             .await?;
    8924              : 
    8925            1 :         let lsn = Lsn(0x30);
    8926            1 :         let old_lsn = Lsn(0x20);
    8927              : 
    8928            1 :         assert_eq!(
    8929            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8930            1 :             Some(test_img("metadata key 0"))
    8931              :         );
    8932            1 :         assert_eq!(
    8933            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8934              :             None,
    8935              :         );
    8936            1 :         assert_eq!(
    8937            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8938              :             None,
    8939              :         );
    8940            1 :         assert_eq!(
    8941            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8942            1 :             Some(Bytes::new()),
    8943              :         );
    8944            1 :         assert_eq!(
    8945            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8946            1 :             Some(Bytes::new()),
    8947              :         );
    8948            1 :         assert_eq!(
    8949            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8950            1 :             Some(test_img("metadata key 3"))
    8951              :         );
    8952              : 
    8953            2 :         Ok(())
    8954            1 :     }
    8955              : 
    8956              :     #[tokio::test]
    8957            1 :     async fn test_metadata_tombstone_image_creation() {
    8958            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8959            1 :             .await
    8960            1 :             .unwrap();
    8961            1 :         let (tenant, ctx) = harness.load().await;
    8962            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8963              : 
    8964            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8965            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8966            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8967            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8968              : 
    8969            1 :         let tline = tenant
    8970            1 :             .create_test_timeline_with_layers(
    8971            1 :                 TIMELINE_ID,
    8972            1 :                 Lsn(0x10),
    8973            1 :                 DEFAULT_PG_VERSION,
    8974            1 :                 &ctx,
    8975            1 :                 Vec::new(), // in-memory layers
    8976            1 :                 // delta layers
    8977            1 :                 vec![
    8978            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8979            1 :                         Lsn(0x10)..Lsn(0x20),
    8980            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8981            1 :                     ),
    8982            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8983            1 :                         Lsn(0x20)..Lsn(0x30),
    8984            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8985            1 :                     ),
    8986            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8987            1 :                         Lsn(0x20)..Lsn(0x30),
    8988            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8989            1 :                     ),
    8990            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8991            1 :                         Lsn(0x30)..Lsn(0x40),
    8992            1 :                         vec![
    8993            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8994            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8995            1 :                         ],
    8996            1 :                     ),
    8997            1 :                 ],
    8998            1 :                 // image layers
    8999            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9000            1 :                 Lsn(0x40),
    9001            1 :             )
    9002            1 :             .await
    9003            1 :             .unwrap();
    9004              : 
    9005            1 :         let cancel = CancellationToken::new();
    9006              : 
    9007              :         // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
    9008            1 :         tline.force_set_disk_consistent_lsn(Lsn(0x40));
    9009            1 :         tline
    9010            1 :             .compact(
    9011            1 :                 &cancel,
    9012            1 :                 {
    9013            1 :                     let mut flags = EnumSet::new();
    9014            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9015            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9016            1 :                     flags
    9017            1 :                 },
    9018            1 :                 &ctx,
    9019            1 :             )
    9020            1 :             .await
    9021            1 :             .unwrap();
    9022              :         // Image layers are created at repartition LSN
    9023            1 :         let images = tline
    9024            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    9025            1 :             .await
    9026            1 :             .unwrap()
    9027            1 :             .into_iter()
    9028            9 :             .filter(|(k, _)| k.is_metadata_key())
    9029            1 :             .collect::<Vec<_>>();
    9030            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    9031            1 :     }
    9032              : 
    9033              :     #[tokio::test]
    9034            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    9035            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    9036            1 :             .await
    9037            1 :             .unwrap();
    9038            1 :         let (tenant, ctx) = harness.load().await;
    9039            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9040              : 
    9041            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    9042            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    9043              : 
    9044            1 :         let tline = tenant
    9045            1 :             .create_test_timeline_with_layers(
    9046            1 :                 TIMELINE_ID,
    9047            1 :                 Lsn(0x10),
    9048            1 :                 DEFAULT_PG_VERSION,
    9049            1 :                 &ctx,
    9050            1 :                 Vec::new(), // in-memory layers
    9051            1 :                 // delta layers
    9052            1 :                 vec![
    9053            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9054            1 :                         Lsn(0x10)..Lsn(0x20),
    9055            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    9056            1 :                     ),
    9057            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9058            1 :                         Lsn(0x20)..Lsn(0x30),
    9059            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    9060            1 :                     ),
    9061            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9062            1 :                         Lsn(0x20)..Lsn(0x30),
    9063            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    9064            1 :                     ),
    9065            1 :                 ],
    9066            1 :                 // image layers
    9067            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9068            1 :                 Lsn(0x30),
    9069            1 :             )
    9070            1 :             .await
    9071            1 :             .unwrap();
    9072              : 
    9073            1 :         let cancel = CancellationToken::new();
    9074              : 
    9075            1 :         tline
    9076            1 :             .compact(
    9077            1 :                 &cancel,
    9078            1 :                 {
    9079            1 :                     let mut flags = EnumSet::new();
    9080            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9081            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9082            1 :                     flags
    9083            1 :                 },
    9084            1 :                 &ctx,
    9085            1 :             )
    9086            1 :             .await
    9087            1 :             .unwrap();
    9088              : 
    9089              :         // Image layers are created at last_record_lsn
    9090            1 :         let images = tline
    9091            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9092            1 :             .await
    9093            1 :             .unwrap()
    9094            1 :             .into_iter()
    9095            7 :             .filter(|(k, _)| k.is_metadata_key())
    9096            1 :             .collect::<Vec<_>>();
    9097            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    9098            1 :     }
    9099              : 
    9100              :     #[tokio::test]
    9101            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    9102            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    9103            1 :         let (tenant, ctx) = harness.load().await;
    9104            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9105              : 
    9106           51 :         fn get_key(id: u32) -> Key {
    9107              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9108           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9109           51 :             key.field6 = id;
    9110           51 :             key
    9111           51 :         }
    9112              : 
    9113              :         // We create
    9114              :         // - one bottom-most image layer,
    9115              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9116              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9117              :         // - a delta layer D3 above the horizon.
    9118              :         //
    9119              :         //                             | D3 |
    9120              :         //  | D1 |
    9121              :         // -|    |-- gc horizon -----------------
    9122              :         //  |    |                | D2 |
    9123              :         // --------- img layer ------------------
    9124              :         //
    9125              :         // What we should expact from this compaction is:
    9126              :         //                             | D3 |
    9127              :         //  | Part of D1 |
    9128              :         // --------- img layer with D1+D2 at GC horizon------------------
    9129              : 
    9130              :         // img layer at 0x10
    9131            1 :         let img_layer = (0..10)
    9132           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9133            1 :             .collect_vec();
    9134              : 
    9135            1 :         let delta1 = vec![
    9136            1 :             (
    9137            1 :                 get_key(1),
    9138            1 :                 Lsn(0x20),
    9139            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    9140            1 :             ),
    9141            1 :             (
    9142            1 :                 get_key(2),
    9143            1 :                 Lsn(0x30),
    9144            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    9145            1 :             ),
    9146            1 :             (
    9147            1 :                 get_key(3),
    9148            1 :                 Lsn(0x40),
    9149            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    9150            1 :             ),
    9151              :         ];
    9152            1 :         let delta2 = vec![
    9153            1 :             (
    9154            1 :                 get_key(5),
    9155            1 :                 Lsn(0x20),
    9156            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    9157            1 :             ),
    9158            1 :             (
    9159            1 :                 get_key(6),
    9160            1 :                 Lsn(0x20),
    9161            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    9162            1 :             ),
    9163              :         ];
    9164            1 :         let delta3 = vec![
    9165            1 :             (
    9166            1 :                 get_key(8),
    9167            1 :                 Lsn(0x48),
    9168            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    9169            1 :             ),
    9170            1 :             (
    9171            1 :                 get_key(9),
    9172            1 :                 Lsn(0x48),
    9173            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    9174            1 :             ),
    9175              :         ];
    9176              : 
    9177            1 :         let tline = tenant
    9178            1 :             .create_test_timeline_with_layers(
    9179            1 :                 TIMELINE_ID,
    9180            1 :                 Lsn(0x10),
    9181            1 :                 DEFAULT_PG_VERSION,
    9182            1 :                 &ctx,
    9183            1 :                 Vec::new(), // in-memory layers
    9184            1 :                 vec![
    9185            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9186            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9187            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9188            1 :                 ], // delta layers
    9189            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9190            1 :                 Lsn(0x50),
    9191            1 :             )
    9192            1 :             .await?;
    9193              :         {
    9194            1 :             tline
    9195            1 :                 .applied_gc_cutoff_lsn
    9196            1 :                 .lock_for_write()
    9197            1 :                 .store_and_unlock(Lsn(0x30))
    9198            1 :                 .wait()
    9199            1 :                 .await;
    9200              :             // Update GC info
    9201            1 :             let mut guard = tline.gc_info.write().unwrap();
    9202            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    9203            1 :             guard.cutoffs.space = Lsn(0x30);
    9204              :         }
    9205              : 
    9206            1 :         let expected_result = [
    9207            1 :             Bytes::from_static(b"value 0@0x10"),
    9208            1 :             Bytes::from_static(b"value 1@0x20"),
    9209            1 :             Bytes::from_static(b"value 2@0x30"),
    9210            1 :             Bytes::from_static(b"value 3@0x40"),
    9211            1 :             Bytes::from_static(b"value 4@0x10"),
    9212            1 :             Bytes::from_static(b"value 5@0x20"),
    9213            1 :             Bytes::from_static(b"value 6@0x20"),
    9214            1 :             Bytes::from_static(b"value 7@0x10"),
    9215            1 :             Bytes::from_static(b"value 8@0x48"),
    9216            1 :             Bytes::from_static(b"value 9@0x48"),
    9217            1 :         ];
    9218              : 
    9219           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9220           10 :             assert_eq!(
    9221           10 :                 tline
    9222           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9223           10 :                     .await
    9224           10 :                     .unwrap(),
    9225              :                 expected
    9226              :             );
    9227              :         }
    9228              : 
    9229            1 :         let cancel = CancellationToken::new();
    9230            1 :         tline
    9231            1 :             .compact_with_gc(
    9232            1 :                 &cancel,
    9233            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
    9234            1 :                 &ctx,
    9235            1 :             )
    9236            1 :             .await
    9237            1 :             .unwrap();
    9238              : 
    9239           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9240           10 :             assert_eq!(
    9241           10 :                 tline
    9242           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9243           10 :                     .await
    9244           10 :                     .unwrap(),
    9245              :                 expected
    9246              :             );
    9247              :         }
    9248              : 
    9249              :         // Check if the image layer at the GC horizon contains exactly what we want
    9250            1 :         let image_at_gc_horizon = tline
    9251            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9252            1 :             .await
    9253            1 :             .unwrap()
    9254            1 :             .into_iter()
    9255           17 :             .filter(|(k, _)| k.is_metadata_key())
    9256            1 :             .collect::<Vec<_>>();
    9257              : 
    9258            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9259            1 :         let expected_result = [
    9260            1 :             Bytes::from_static(b"value 0@0x10"),
    9261            1 :             Bytes::from_static(b"value 1@0x20"),
    9262            1 :             Bytes::from_static(b"value 2@0x30"),
    9263            1 :             Bytes::from_static(b"value 3@0x10"),
    9264            1 :             Bytes::from_static(b"value 4@0x10"),
    9265            1 :             Bytes::from_static(b"value 5@0x20"),
    9266            1 :             Bytes::from_static(b"value 6@0x20"),
    9267            1 :             Bytes::from_static(b"value 7@0x10"),
    9268            1 :             Bytes::from_static(b"value 8@0x10"),
    9269            1 :             Bytes::from_static(b"value 9@0x10"),
    9270            1 :         ];
    9271           11 :         for idx in 0..10 {
    9272           10 :             assert_eq!(
    9273           10 :                 image_at_gc_horizon[idx],
    9274           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9275              :             );
    9276              :         }
    9277              : 
    9278              :         // Check if old layers are removed / new layers have the expected LSN
    9279            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9280            1 :         assert_eq!(
    9281              :             all_layers,
    9282            1 :             vec![
    9283              :                 // Image layer at GC horizon
    9284            1 :                 PersistentLayerKey {
    9285            1 :                     key_range: Key::MIN..Key::MAX,
    9286            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9287            1 :                     is_delta: false
    9288            1 :                 },
    9289              :                 // The delta layer below the horizon
    9290            1 :                 PersistentLayerKey {
    9291            1 :                     key_range: get_key(3)..get_key(4),
    9292            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9293            1 :                     is_delta: true
    9294            1 :                 },
    9295              :                 // The delta3 layer that should not be picked for the compaction
    9296            1 :                 PersistentLayerKey {
    9297            1 :                     key_range: get_key(8)..get_key(10),
    9298            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9299            1 :                     is_delta: true
    9300            1 :                 }
    9301              :             ]
    9302              :         );
    9303              : 
    9304              :         // increase GC horizon and compact again
    9305              :         {
    9306            1 :             tline
    9307            1 :                 .applied_gc_cutoff_lsn
    9308            1 :                 .lock_for_write()
    9309            1 :                 .store_and_unlock(Lsn(0x40))
    9310            1 :                 .wait()
    9311            1 :                 .await;
    9312              :             // Update GC info
    9313            1 :             let mut guard = tline.gc_info.write().unwrap();
    9314            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9315            1 :             guard.cutoffs.space = Lsn(0x40);
    9316              :         }
    9317            1 :         tline
    9318            1 :             .compact_with_gc(
    9319            1 :                 &cancel,
    9320            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
    9321            1 :                 &ctx,
    9322            1 :             )
    9323            1 :             .await
    9324            1 :             .unwrap();
    9325              : 
    9326            2 :         Ok(())
    9327            1 :     }
    9328              : 
    9329              :     #[cfg(feature = "testing")]
    9330              :     #[tokio::test]
    9331            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9332            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9333            1 :         let (tenant, ctx) = harness.load().await;
    9334              : 
    9335           17 :         fn get_key(id: u32) -> Key {
    9336              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9337           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9338           17 :             key.field6 = id;
    9339           17 :             key
    9340           17 :         }
    9341              : 
    9342            1 :         let delta1 = vec![
    9343            1 :             (
    9344            1 :                 get_key(1),
    9345            1 :                 Lsn(0x20),
    9346            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9347            1 :             ),
    9348            1 :             (
    9349            1 :                 get_key(1),
    9350            1 :                 Lsn(0x30),
    9351            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9352            1 :             ),
    9353            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9354            1 :             (
    9355            1 :                 get_key(2),
    9356            1 :                 Lsn(0x20),
    9357            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9358            1 :             ),
    9359            1 :             (
    9360            1 :                 get_key(2),
    9361            1 :                 Lsn(0x30),
    9362            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9363            1 :             ),
    9364            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9365            1 :             (
    9366            1 :                 get_key(3),
    9367            1 :                 Lsn(0x20),
    9368            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9369            1 :             ),
    9370            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9371            1 :             (
    9372            1 :                 get_key(4),
    9373            1 :                 Lsn(0x20),
    9374            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9375            1 :             ),
    9376            1 :             (
    9377            1 :                 get_key(4),
    9378            1 :                 Lsn(0x30),
    9379            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9380            1 :             ),
    9381            1 :             (
    9382            1 :                 get_key(5),
    9383            1 :                 Lsn(0x20),
    9384            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9385            1 :             ),
    9386            1 :             (
    9387            1 :                 get_key(5),
    9388            1 :                 Lsn(0x30),
    9389            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9390            1 :             ),
    9391              :         ];
    9392            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9393              : 
    9394            1 :         let tline = tenant
    9395            1 :             .create_test_timeline_with_layers(
    9396            1 :                 TIMELINE_ID,
    9397            1 :                 Lsn(0x10),
    9398            1 :                 DEFAULT_PG_VERSION,
    9399            1 :                 &ctx,
    9400            1 :                 Vec::new(), // in-memory layers
    9401            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9402            1 :                     Lsn(0x10)..Lsn(0x40),
    9403            1 :                     delta1,
    9404            1 :                 )], // delta layers
    9405            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9406            1 :                 Lsn(0x50),
    9407            1 :             )
    9408            1 :             .await?;
    9409              : 
    9410            1 :         assert_eq!(
    9411            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9412            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9413              :         );
    9414            1 :         assert_eq!(
    9415            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9416            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9417              :         );
    9418              : 
    9419              :         // Need to remove the limit of "Neon WAL redo requires base image".
    9420              : 
    9421            1 :         assert_eq!(
    9422            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9423            1 :             Bytes::from_static(b"c")
    9424              :         );
    9425            1 :         assert_eq!(
    9426            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9427            1 :             Bytes::from_static(b"ij")
    9428              :         );
    9429              : 
    9430              :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9431              :         // cannot enable this assertion in the unit test.
    9432              :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9433              : 
    9434            2 :         Ok(())
    9435            1 :     }
    9436              : 
    9437              :     #[tokio::test]
    9438            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9439            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9440            1 :             .await
    9441            1 :             .unwrap()
    9442            1 :             .load()
    9443            1 :             .await;
    9444              :         // set a non-zero lease length to test the feature
    9445            1 :         tenant
    9446            1 :             .update_tenant_config(|mut conf| {
    9447            1 :                 conf.lsn_lease_length = Some(LsnLease::DEFAULT_LENGTH);
    9448            1 :                 Ok(conf)
    9449            1 :             })
    9450            1 :             .unwrap();
    9451              : 
    9452            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9453              : 
    9454            1 :         let end_lsn = Lsn(0x100);
    9455            1 :         let image_layers = (0x20..=0x90)
    9456            1 :             .step_by(0x10)
    9457            8 :             .map(|n| (Lsn(n), vec![(key, test_img(&format!("data key at {n:x}")))]))
    9458            1 :             .collect();
    9459              : 
    9460            1 :         let timeline = tenant
    9461            1 :             .create_test_timeline_with_layers(
    9462            1 :                 TIMELINE_ID,
    9463            1 :                 Lsn(0x10),
    9464            1 :                 DEFAULT_PG_VERSION,
    9465            1 :                 &ctx,
    9466            1 :                 Vec::new(), // in-memory layers
    9467            1 :                 Vec::new(),
    9468            1 :                 image_layers,
    9469            1 :                 end_lsn,
    9470            1 :             )
    9471            1 :             .await?;
    9472              : 
    9473            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9474            1 :         let mut leases = Vec::new();
    9475            3 :         leased_lsns.iter().for_each(|n| {
    9476            3 :             leases.push(
    9477            3 :                 timeline
    9478            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9479            3 :                     .expect("lease request should succeed"),
    9480              :             );
    9481            3 :         });
    9482              : 
    9483            1 :         let updated_lease_0 = timeline
    9484            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9485            1 :             .expect("lease renewal should succeed");
    9486            1 :         assert_eq!(
    9487            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9488            0 :             " Renewing with shorter lease should not change the lease."
    9489              :         );
    9490              : 
    9491            1 :         let updated_lease_1 = timeline
    9492            1 :             .renew_lsn_lease(
    9493            1 :                 Lsn(leased_lsns[1]),
    9494            1 :                 timeline.get_lsn_lease_length() * 2,
    9495            1 :                 &ctx,
    9496            1 :             )
    9497            1 :             .expect("lease renewal should succeed");
    9498            1 :         assert!(
    9499            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9500            0 :             "Renewing with a long lease should renew lease with later expiration time."
    9501              :         );
    9502              : 
    9503              :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9504            1 :         info!(
    9505            0 :             "applied_gc_cutoff_lsn: {}",
    9506            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9507              :         );
    9508            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9509              : 
    9510            1 :         let res = tenant
    9511            1 :             .gc_iteration(
    9512            1 :                 Some(TIMELINE_ID),
    9513            1 :                 0,
    9514            1 :                 Duration::ZERO,
    9515            1 :                 &CancellationToken::new(),
    9516            1 :                 &ctx,
    9517            1 :             )
    9518            1 :             .await
    9519            1 :             .unwrap();
    9520              : 
    9521              :         // Keeping everything <= Lsn(0x80) b/c leases:
    9522              :         // 0/10: initdb layer
    9523              :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9524            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9525              :         // Keeping 0/90 b/c it is the latest layer.
    9526            1 :         assert_eq!(res.layers_not_updated, 1);
    9527              :         // Removed 0/80.
    9528            1 :         assert_eq!(res.layers_removed, 1);
    9529              : 
    9530              :         // Make lease on a already GC-ed LSN.
    9531              :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9532            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9533            1 :         timeline
    9534            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9535            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9536              : 
    9537              :         // Should still be able to renew a currently valid lease
    9538              :         // Assumption: original lease to is still valid for 0/50.
    9539              :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9540            1 :         timeline
    9541            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9542            1 :             .expect("lease renewal with validation should succeed");
    9543              : 
    9544            2 :         Ok(())
    9545            1 :     }
    9546              : 
    9547              :     #[tokio::test]
    9548            1 :     async fn test_failed_flush_should_not_update_disk_consistent_lsn() -> anyhow::Result<()> {
    9549              :         //
    9550              :         // Setup
    9551              :         //
    9552            1 :         let harness = TenantHarness::create_custom(
    9553            1 :             "test_failed_flush_should_not_upload_disk_consistent_lsn",
    9554            1 :             pageserver_api::models::TenantConfig::default(),
    9555            1 :             TenantId::generate(),
    9556            1 :             ShardIdentity::new(ShardNumber(0), ShardCount(4), ShardStripeSize(128)).unwrap(),
    9557            1 :             Generation::new(1),
    9558            1 :         )
    9559            1 :         .await?;
    9560            1 :         let (tenant, ctx) = harness.load().await;
    9561              : 
    9562            1 :         let timeline = tenant
    9563            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9564            1 :             .await?;
    9565            1 :         assert_eq!(timeline.get_shard_identity().count, ShardCount(4));
    9566            1 :         let mut writer = timeline.writer().await;
    9567            1 :         writer
    9568            1 :             .put(
    9569            1 :                 *TEST_KEY,
    9570            1 :                 Lsn(0x20),
    9571            1 :                 &Value::Image(test_img("foo at 0x20")),
    9572            1 :                 &ctx,
    9573            1 :             )
    9574            1 :             .await?;
    9575            1 :         writer.finish_write(Lsn(0x20));
    9576            1 :         drop(writer);
    9577            1 :         timeline.freeze_and_flush().await.unwrap();
    9578              : 
    9579            1 :         timeline.remote_client.wait_completion().await.unwrap();
    9580            1 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    9581            1 :         let remote_consistent_lsn = timeline.get_remote_consistent_lsn_projected();
    9582            1 :         assert_eq!(Some(disk_consistent_lsn), remote_consistent_lsn);
    9583              : 
    9584              :         //
    9585              :         // Test
    9586              :         //
    9587              : 
    9588            1 :         let mut writer = timeline.writer().await;
    9589            1 :         writer
    9590            1 :             .put(
    9591            1 :                 *TEST_KEY,
    9592            1 :                 Lsn(0x30),
    9593            1 :                 &Value::Image(test_img("foo at 0x30")),
    9594            1 :                 &ctx,
    9595            1 :             )
    9596            1 :             .await?;
    9597            1 :         writer.finish_write(Lsn(0x30));
    9598            1 :         drop(writer);
    9599              : 
    9600            1 :         fail::cfg(
    9601              :             "flush-layer-before-update-remote-consistent-lsn",
    9602            1 :             "return()",
    9603              :         )
    9604            1 :         .unwrap();
    9605              : 
    9606            1 :         let flush_res = timeline.freeze_and_flush().await;
    9607              :         // if flush failed, the disk/remote consistent LSN should not be updated
    9608            1 :         assert!(flush_res.is_err());
    9609            1 :         assert_eq!(disk_consistent_lsn, timeline.get_disk_consistent_lsn());
    9610            1 :         assert_eq!(
    9611              :             remote_consistent_lsn,
    9612            1 :             timeline.get_remote_consistent_lsn_projected()
    9613              :         );
    9614              : 
    9615            2 :         Ok(())
    9616            1 :     }
    9617              : 
    9618              :     #[cfg(feature = "testing")]
    9619              :     #[tokio::test]
    9620            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9621            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9622            2 :             "test_simple_bottom_most_compaction_deltas_1",
    9623            2 :             false,
    9624            2 :         )
    9625            2 :         .await
    9626            1 :     }
    9627              : 
    9628              :     #[cfg(feature = "testing")]
    9629              :     #[tokio::test]
    9630            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9631            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9632            2 :             "test_simple_bottom_most_compaction_deltas_2",
    9633            2 :             true,
    9634            2 :         )
    9635            2 :         .await
    9636            1 :     }
    9637              : 
    9638              :     #[cfg(feature = "testing")]
    9639            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9640            2 :         test_name: &'static str,
    9641            2 :         use_delta_bottom_layer: bool,
    9642            2 :     ) -> anyhow::Result<()> {
    9643            2 :         let harness = TenantHarness::create(test_name).await?;
    9644            2 :         let (tenant, ctx) = harness.load().await;
    9645              : 
    9646          138 :         fn get_key(id: u32) -> Key {
    9647              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9648          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9649          138 :             key.field6 = id;
    9650          138 :             key
    9651          138 :         }
    9652              : 
    9653              :         // We create
    9654              :         // - one bottom-most image layer,
    9655              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9656              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9657              :         // - a delta layer D3 above the horizon.
    9658              :         //
    9659              :         //                             | D3 |
    9660              :         //  | D1 |
    9661              :         // -|    |-- gc horizon -----------------
    9662              :         //  |    |                | D2 |
    9663              :         // --------- img layer ------------------
    9664              :         //
    9665              :         // What we should expact from this compaction is:
    9666              :         //                             | D3 |
    9667              :         //  | Part of D1 |
    9668              :         // --------- img layer with D1+D2 at GC horizon------------------
    9669              : 
    9670              :         // img layer at 0x10
    9671            2 :         let img_layer = (0..10)
    9672           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9673            2 :             .collect_vec();
    9674              :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9675            2 :         let delta4 = (0..10)
    9676           20 :             .map(|id| {
    9677           20 :                 (
    9678           20 :                     get_key(id),
    9679           20 :                     Lsn(0x08),
    9680           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9681           20 :                 )
    9682           20 :             })
    9683            2 :             .collect_vec();
    9684              : 
    9685            2 :         let delta1 = vec![
    9686            2 :             (
    9687            2 :                 get_key(1),
    9688            2 :                 Lsn(0x20),
    9689            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9690            2 :             ),
    9691            2 :             (
    9692            2 :                 get_key(2),
    9693            2 :                 Lsn(0x30),
    9694            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9695            2 :             ),
    9696            2 :             (
    9697            2 :                 get_key(3),
    9698            2 :                 Lsn(0x28),
    9699            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9700            2 :             ),
    9701            2 :             (
    9702            2 :                 get_key(3),
    9703            2 :                 Lsn(0x30),
    9704            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9705            2 :             ),
    9706            2 :             (
    9707            2 :                 get_key(3),
    9708            2 :                 Lsn(0x40),
    9709            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9710            2 :             ),
    9711              :         ];
    9712            2 :         let delta2 = vec![
    9713            2 :             (
    9714            2 :                 get_key(5),
    9715            2 :                 Lsn(0x20),
    9716            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9717            2 :             ),
    9718            2 :             (
    9719            2 :                 get_key(6),
    9720            2 :                 Lsn(0x20),
    9721            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9722            2 :             ),
    9723              :         ];
    9724            2 :         let delta3 = vec![
    9725            2 :             (
    9726            2 :                 get_key(8),
    9727            2 :                 Lsn(0x48),
    9728            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9729            2 :             ),
    9730            2 :             (
    9731            2 :                 get_key(9),
    9732            2 :                 Lsn(0x48),
    9733            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9734            2 :             ),
    9735              :         ];
    9736              : 
    9737            2 :         let tline = if use_delta_bottom_layer {
    9738            1 :             tenant
    9739            1 :                 .create_test_timeline_with_layers(
    9740            1 :                     TIMELINE_ID,
    9741            1 :                     Lsn(0x08),
    9742            1 :                     DEFAULT_PG_VERSION,
    9743            1 :                     &ctx,
    9744            1 :                     Vec::new(), // in-memory layers
    9745            1 :                     vec![
    9746            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9747            1 :                             Lsn(0x08)..Lsn(0x10),
    9748            1 :                             delta4,
    9749            1 :                         ),
    9750            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9751            1 :                             Lsn(0x20)..Lsn(0x48),
    9752            1 :                             delta1,
    9753            1 :                         ),
    9754            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9755            1 :                             Lsn(0x20)..Lsn(0x48),
    9756            1 :                             delta2,
    9757            1 :                         ),
    9758            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9759            1 :                             Lsn(0x48)..Lsn(0x50),
    9760            1 :                             delta3,
    9761            1 :                         ),
    9762            1 :                     ], // delta layers
    9763            1 :                     vec![],     // image layers
    9764            1 :                     Lsn(0x50),
    9765            1 :                 )
    9766            1 :                 .await?
    9767              :         } else {
    9768            1 :             tenant
    9769            1 :                 .create_test_timeline_with_layers(
    9770            1 :                     TIMELINE_ID,
    9771            1 :                     Lsn(0x10),
    9772            1 :                     DEFAULT_PG_VERSION,
    9773            1 :                     &ctx,
    9774            1 :                     Vec::new(), // in-memory layers
    9775            1 :                     vec![
    9776            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9777            1 :                             Lsn(0x10)..Lsn(0x48),
    9778            1 :                             delta1,
    9779            1 :                         ),
    9780            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9781            1 :                             Lsn(0x10)..Lsn(0x48),
    9782            1 :                             delta2,
    9783            1 :                         ),
    9784            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9785            1 :                             Lsn(0x48)..Lsn(0x50),
    9786            1 :                             delta3,
    9787            1 :                         ),
    9788            1 :                     ], // delta layers
    9789            1 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9790            1 :                     Lsn(0x50),
    9791            1 :                 )
    9792            1 :                 .await?
    9793              :         };
    9794              :         {
    9795            2 :             tline
    9796            2 :                 .applied_gc_cutoff_lsn
    9797            2 :                 .lock_for_write()
    9798            2 :                 .store_and_unlock(Lsn(0x30))
    9799            2 :                 .wait()
    9800            2 :                 .await;
    9801              :             // Update GC info
    9802            2 :             let mut guard = tline.gc_info.write().unwrap();
    9803            2 :             *guard = GcInfo {
    9804            2 :                 retain_lsns: vec![],
    9805            2 :                 cutoffs: GcCutoffs {
    9806            2 :                     time: Some(Lsn(0x30)),
    9807            2 :                     space: Lsn(0x30),
    9808            2 :                 },
    9809            2 :                 leases: Default::default(),
    9810            2 :                 within_ancestor_pitr: false,
    9811            2 :             };
    9812              :         }
    9813              : 
    9814            2 :         let expected_result = [
    9815            2 :             Bytes::from_static(b"value 0@0x10"),
    9816            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9817            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9818            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9819            2 :             Bytes::from_static(b"value 4@0x10"),
    9820            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9821            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9822            2 :             Bytes::from_static(b"value 7@0x10"),
    9823            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9824            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9825            2 :         ];
    9826              : 
    9827            2 :         let expected_result_at_gc_horizon = [
    9828            2 :             Bytes::from_static(b"value 0@0x10"),
    9829            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9830            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9831            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9832            2 :             Bytes::from_static(b"value 4@0x10"),
    9833            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9834            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9835            2 :             Bytes::from_static(b"value 7@0x10"),
    9836            2 :             Bytes::from_static(b"value 8@0x10"),
    9837            2 :             Bytes::from_static(b"value 9@0x10"),
    9838            2 :         ];
    9839              : 
    9840           22 :         for idx in 0..10 {
    9841           20 :             assert_eq!(
    9842           20 :                 tline
    9843           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9844           20 :                     .await
    9845           20 :                     .unwrap(),
    9846           20 :                 &expected_result[idx]
    9847              :             );
    9848           20 :             assert_eq!(
    9849           20 :                 tline
    9850           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9851           20 :                     .await
    9852           20 :                     .unwrap(),
    9853           20 :                 &expected_result_at_gc_horizon[idx]
    9854              :             );
    9855              :         }
    9856              : 
    9857            2 :         let cancel = CancellationToken::new();
    9858            2 :         tline
    9859            2 :             .compact_with_gc(
    9860            2 :                 &cancel,
    9861            2 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
    9862            2 :                 &ctx,
    9863            2 :             )
    9864            2 :             .await
    9865            2 :             .unwrap();
    9866              : 
    9867           22 :         for idx in 0..10 {
    9868           20 :             assert_eq!(
    9869           20 :                 tline
    9870           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9871           20 :                     .await
    9872           20 :                     .unwrap(),
    9873           20 :                 &expected_result[idx]
    9874              :             );
    9875           20 :             assert_eq!(
    9876           20 :                 tline
    9877           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9878           20 :                     .await
    9879           20 :                     .unwrap(),
    9880           20 :                 &expected_result_at_gc_horizon[idx]
    9881              :             );
    9882              :         }
    9883              : 
    9884              :         // increase GC horizon and compact again
    9885              :         {
    9886            2 :             tline
    9887            2 :                 .applied_gc_cutoff_lsn
    9888            2 :                 .lock_for_write()
    9889            2 :                 .store_and_unlock(Lsn(0x40))
    9890            2 :                 .wait()
    9891            2 :                 .await;
    9892              :             // Update GC info
    9893            2 :             let mut guard = tline.gc_info.write().unwrap();
    9894            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9895            2 :             guard.cutoffs.space = Lsn(0x40);
    9896              :         }
    9897            2 :         tline
    9898            2 :             .compact_with_gc(
    9899            2 :                 &cancel,
    9900            2 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
    9901            2 :                 &ctx,
    9902            2 :             )
    9903            2 :             .await
    9904            2 :             .unwrap();
    9905              : 
    9906            2 :         Ok(())
    9907            2 :     }
    9908              : 
    9909              :     #[cfg(feature = "testing")]
    9910              :     #[tokio::test]
    9911            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9912            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9913            1 :         let (tenant, ctx) = harness.load().await;
    9914            1 :         let tline = tenant
    9915            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9916            1 :             .await?;
    9917            1 :         tline.force_advance_lsn(Lsn(0x70));
    9918            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9919            1 :         let history = vec![
    9920            1 :             (
    9921            1 :                 key,
    9922            1 :                 Lsn(0x10),
    9923            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9924            1 :             ),
    9925            1 :             (
    9926            1 :                 key,
    9927            1 :                 Lsn(0x20),
    9928            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9929            1 :             ),
    9930            1 :             (
    9931            1 :                 key,
    9932            1 :                 Lsn(0x30),
    9933            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9934            1 :             ),
    9935            1 :             (
    9936            1 :                 key,
    9937            1 :                 Lsn(0x40),
    9938            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9939            1 :             ),
    9940            1 :             (
    9941            1 :                 key,
    9942            1 :                 Lsn(0x50),
    9943            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9944            1 :             ),
    9945            1 :             (
    9946            1 :                 key,
    9947            1 :                 Lsn(0x60),
    9948            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9949            1 :             ),
    9950            1 :             (
    9951            1 :                 key,
    9952            1 :                 Lsn(0x70),
    9953            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9954            1 :             ),
    9955            1 :             (
    9956            1 :                 key,
    9957            1 :                 Lsn(0x80),
    9958            1 :                 Value::Image(Bytes::copy_from_slice(
    9959            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9960            1 :                 )),
    9961            1 :             ),
    9962            1 :             (
    9963            1 :                 key,
    9964            1 :                 Lsn(0x90),
    9965            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9966            1 :             ),
    9967              :         ];
    9968            1 :         let res = tline
    9969            1 :             .generate_key_retention(
    9970            1 :                 key,
    9971            1 :                 &history,
    9972            1 :                 Lsn(0x60),
    9973            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9974            1 :                 3,
    9975            1 :                 None,
    9976            1 :                 true,
    9977            1 :             )
    9978            1 :             .await
    9979            1 :             .unwrap();
    9980            1 :         let expected_res = KeyHistoryRetention {
    9981            1 :             below_horizon: vec![
    9982            1 :                 (
    9983            1 :                     Lsn(0x20),
    9984            1 :                     KeyLogAtLsn(vec![(
    9985            1 :                         Lsn(0x20),
    9986            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9987            1 :                     )]),
    9988            1 :                 ),
    9989            1 :                 (
    9990            1 :                     Lsn(0x40),
    9991            1 :                     KeyLogAtLsn(vec![
    9992            1 :                         (
    9993            1 :                             Lsn(0x30),
    9994            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9995            1 :                         ),
    9996            1 :                         (
    9997            1 :                             Lsn(0x40),
    9998            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9999            1 :                         ),
   10000            1 :                     ]),
   10001            1 :                 ),
   10002            1 :                 (
   10003            1 :                     Lsn(0x50),
   10004            1 :                     KeyLogAtLsn(vec![(
   10005            1 :                         Lsn(0x50),
   10006            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
   10007            1 :                     )]),
   10008            1 :                 ),
   10009            1 :                 (
   10010            1 :                     Lsn(0x60),
   10011            1 :                     KeyLogAtLsn(vec![(
   10012            1 :                         Lsn(0x60),
   10013            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10014            1 :                     )]),
   10015            1 :                 ),
   10016            1 :             ],
   10017            1 :             above_horizon: KeyLogAtLsn(vec![
   10018            1 :                 (
   10019            1 :                     Lsn(0x70),
   10020            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10021            1 :                 ),
   10022            1 :                 (
   10023            1 :                     Lsn(0x80),
   10024            1 :                     Value::Image(Bytes::copy_from_slice(
   10025            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10026            1 :                     )),
   10027            1 :                 ),
   10028            1 :                 (
   10029            1 :                     Lsn(0x90),
   10030            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10031            1 :                 ),
   10032            1 :             ]),
   10033            1 :         };
   10034            1 :         assert_eq!(res, expected_res);
   10035              : 
   10036              :         // We expect GC-compaction to run with the original GC. This would create a situation that
   10037              :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
   10038              :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
   10039              :         // For example, we have
   10040              :         // ```plain
   10041              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
   10042              :         // ```
   10043              :         // Now the GC horizon moves up, and we have
   10044              :         // ```plain
   10045              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
   10046              :         // ```
   10047              :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
   10048              :         // We will end up with
   10049              :         // ```plain
   10050              :         // delta @ 0x30, image @ 0x40 (gc_horizon)
   10051              :         // ```
   10052              :         // Now we run the GC-compaction, and this key does not have a full history.
   10053              :         // We should be able to handle this partial history and drop everything before the
   10054              :         // gc_horizon image.
   10055              : 
   10056            1 :         let history = vec![
   10057            1 :             (
   10058            1 :                 key,
   10059            1 :                 Lsn(0x20),
   10060            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10061            1 :             ),
   10062            1 :             (
   10063            1 :                 key,
   10064            1 :                 Lsn(0x30),
   10065            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10066            1 :             ),
   10067            1 :             (
   10068            1 :                 key,
   10069            1 :                 Lsn(0x40),
   10070            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10071            1 :             ),
   10072            1 :             (
   10073            1 :                 key,
   10074            1 :                 Lsn(0x50),
   10075            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10076            1 :             ),
   10077            1 :             (
   10078            1 :                 key,
   10079            1 :                 Lsn(0x60),
   10080            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10081            1 :             ),
   10082            1 :             (
   10083            1 :                 key,
   10084            1 :                 Lsn(0x70),
   10085            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10086            1 :             ),
   10087            1 :             (
   10088            1 :                 key,
   10089            1 :                 Lsn(0x80),
   10090            1 :                 Value::Image(Bytes::copy_from_slice(
   10091            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10092            1 :                 )),
   10093            1 :             ),
   10094            1 :             (
   10095            1 :                 key,
   10096            1 :                 Lsn(0x90),
   10097            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10098            1 :             ),
   10099              :         ];
   10100            1 :         let res = tline
   10101            1 :             .generate_key_retention(
   10102            1 :                 key,
   10103            1 :                 &history,
   10104            1 :                 Lsn(0x60),
   10105            1 :                 &[Lsn(0x40), Lsn(0x50)],
   10106            1 :                 3,
   10107            1 :                 None,
   10108            1 :                 true,
   10109            1 :             )
   10110            1 :             .await
   10111            1 :             .unwrap();
   10112            1 :         let expected_res = KeyHistoryRetention {
   10113            1 :             below_horizon: vec![
   10114            1 :                 (
   10115            1 :                     Lsn(0x40),
   10116            1 :                     KeyLogAtLsn(vec![(
   10117            1 :                         Lsn(0x40),
   10118            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10119            1 :                     )]),
   10120            1 :                 ),
   10121            1 :                 (
   10122            1 :                     Lsn(0x50),
   10123            1 :                     KeyLogAtLsn(vec![(
   10124            1 :                         Lsn(0x50),
   10125            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10126            1 :                     )]),
   10127            1 :                 ),
   10128            1 :                 (
   10129            1 :                     Lsn(0x60),
   10130            1 :                     KeyLogAtLsn(vec![(
   10131            1 :                         Lsn(0x60),
   10132            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10133            1 :                     )]),
   10134            1 :                 ),
   10135            1 :             ],
   10136            1 :             above_horizon: KeyLogAtLsn(vec![
   10137            1 :                 (
   10138            1 :                     Lsn(0x70),
   10139            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10140            1 :                 ),
   10141            1 :                 (
   10142            1 :                     Lsn(0x80),
   10143            1 :                     Value::Image(Bytes::copy_from_slice(
   10144            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10145            1 :                     )),
   10146            1 :                 ),
   10147            1 :                 (
   10148            1 :                     Lsn(0x90),
   10149            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10150            1 :                 ),
   10151            1 :             ]),
   10152            1 :         };
   10153            1 :         assert_eq!(res, expected_res);
   10154              : 
   10155              :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
   10156              :         // the ancestor image in the test case.
   10157              : 
   10158            1 :         let history = vec![
   10159            1 :             (
   10160            1 :                 key,
   10161            1 :                 Lsn(0x20),
   10162            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10163            1 :             ),
   10164            1 :             (
   10165            1 :                 key,
   10166            1 :                 Lsn(0x30),
   10167            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10168            1 :             ),
   10169            1 :             (
   10170            1 :                 key,
   10171            1 :                 Lsn(0x40),
   10172            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10173            1 :             ),
   10174            1 :             (
   10175            1 :                 key,
   10176            1 :                 Lsn(0x70),
   10177            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10178            1 :             ),
   10179              :         ];
   10180            1 :         let res = tline
   10181            1 :             .generate_key_retention(
   10182            1 :                 key,
   10183            1 :                 &history,
   10184            1 :                 Lsn(0x60),
   10185            1 :                 &[],
   10186            1 :                 3,
   10187            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10188            1 :                 true,
   10189            1 :             )
   10190            1 :             .await
   10191            1 :             .unwrap();
   10192            1 :         let expected_res = KeyHistoryRetention {
   10193            1 :             below_horizon: vec![(
   10194            1 :                 Lsn(0x60),
   10195            1 :                 KeyLogAtLsn(vec![(
   10196            1 :                     Lsn(0x60),
   10197            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
   10198            1 :                 )]),
   10199            1 :             )],
   10200            1 :             above_horizon: KeyLogAtLsn(vec![(
   10201            1 :                 Lsn(0x70),
   10202            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10203            1 :             )]),
   10204            1 :         };
   10205            1 :         assert_eq!(res, expected_res);
   10206              : 
   10207            1 :         let history = vec![
   10208            1 :             (
   10209            1 :                 key,
   10210            1 :                 Lsn(0x20),
   10211            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10212            1 :             ),
   10213            1 :             (
   10214            1 :                 key,
   10215            1 :                 Lsn(0x40),
   10216            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10217            1 :             ),
   10218            1 :             (
   10219            1 :                 key,
   10220            1 :                 Lsn(0x60),
   10221            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10222            1 :             ),
   10223            1 :             (
   10224            1 :                 key,
   10225            1 :                 Lsn(0x70),
   10226            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10227            1 :             ),
   10228              :         ];
   10229            1 :         let res = tline
   10230            1 :             .generate_key_retention(
   10231            1 :                 key,
   10232            1 :                 &history,
   10233            1 :                 Lsn(0x60),
   10234            1 :                 &[Lsn(0x30)],
   10235            1 :                 3,
   10236            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10237            1 :                 true,
   10238            1 :             )
   10239            1 :             .await
   10240            1 :             .unwrap();
   10241            1 :         let expected_res = KeyHistoryRetention {
   10242            1 :             below_horizon: vec![
   10243            1 :                 (
   10244            1 :                     Lsn(0x30),
   10245            1 :                     KeyLogAtLsn(vec![(
   10246            1 :                         Lsn(0x20),
   10247            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10248            1 :                     )]),
   10249            1 :                 ),
   10250            1 :                 (
   10251            1 :                     Lsn(0x60),
   10252            1 :                     KeyLogAtLsn(vec![(
   10253            1 :                         Lsn(0x60),
   10254            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
   10255            1 :                     )]),
   10256            1 :                 ),
   10257            1 :             ],
   10258            1 :             above_horizon: KeyLogAtLsn(vec![(
   10259            1 :                 Lsn(0x70),
   10260            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10261            1 :             )]),
   10262            1 :         };
   10263            1 :         assert_eq!(res, expected_res);
   10264              : 
   10265            2 :         Ok(())
   10266            1 :     }
   10267              : 
   10268              :     #[cfg(feature = "testing")]
   10269              :     #[tokio::test]
   10270            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
   10271            1 :         let harness =
   10272            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
   10273            1 :         let (tenant, ctx) = harness.load().await;
   10274              : 
   10275          259 :         fn get_key(id: u32) -> Key {
   10276              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10277          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10278          259 :             key.field6 = id;
   10279          259 :             key
   10280          259 :         }
   10281              : 
   10282            1 :         let img_layer = (0..10)
   10283           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10284            1 :             .collect_vec();
   10285              : 
   10286            1 :         let delta1 = vec![
   10287            1 :             (
   10288            1 :                 get_key(1),
   10289            1 :                 Lsn(0x20),
   10290            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10291            1 :             ),
   10292            1 :             (
   10293            1 :                 get_key(2),
   10294            1 :                 Lsn(0x30),
   10295            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10296            1 :             ),
   10297            1 :             (
   10298            1 :                 get_key(3),
   10299            1 :                 Lsn(0x28),
   10300            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10301            1 :             ),
   10302            1 :             (
   10303            1 :                 get_key(3),
   10304            1 :                 Lsn(0x30),
   10305            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10306            1 :             ),
   10307            1 :             (
   10308            1 :                 get_key(3),
   10309            1 :                 Lsn(0x40),
   10310            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10311            1 :             ),
   10312              :         ];
   10313            1 :         let delta2 = vec![
   10314            1 :             (
   10315            1 :                 get_key(5),
   10316            1 :                 Lsn(0x20),
   10317            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10318            1 :             ),
   10319            1 :             (
   10320            1 :                 get_key(6),
   10321            1 :                 Lsn(0x20),
   10322            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10323            1 :             ),
   10324              :         ];
   10325            1 :         let delta3 = vec![
   10326            1 :             (
   10327            1 :                 get_key(8),
   10328            1 :                 Lsn(0x48),
   10329            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10330            1 :             ),
   10331            1 :             (
   10332            1 :                 get_key(9),
   10333            1 :                 Lsn(0x48),
   10334            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10335            1 :             ),
   10336              :         ];
   10337              : 
   10338            1 :         let tline = tenant
   10339            1 :             .create_test_timeline_with_layers(
   10340            1 :                 TIMELINE_ID,
   10341            1 :                 Lsn(0x10),
   10342            1 :                 DEFAULT_PG_VERSION,
   10343            1 :                 &ctx,
   10344            1 :                 Vec::new(), // in-memory layers
   10345            1 :                 vec![
   10346            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10347            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10348            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10349            1 :                 ], // delta layers
   10350            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10351            1 :                 Lsn(0x50),
   10352            1 :             )
   10353            1 :             .await?;
   10354              :         {
   10355            1 :             tline
   10356            1 :                 .applied_gc_cutoff_lsn
   10357            1 :                 .lock_for_write()
   10358            1 :                 .store_and_unlock(Lsn(0x30))
   10359            1 :                 .wait()
   10360            1 :                 .await;
   10361              :             // Update GC info
   10362            1 :             let mut guard = tline.gc_info.write().unwrap();
   10363            1 :             *guard = GcInfo {
   10364            1 :                 retain_lsns: vec![
   10365            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10366            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10367            1 :                 ],
   10368            1 :                 cutoffs: GcCutoffs {
   10369            1 :                     time: Some(Lsn(0x30)),
   10370            1 :                     space: Lsn(0x30),
   10371            1 :                 },
   10372            1 :                 leases: Default::default(),
   10373            1 :                 within_ancestor_pitr: false,
   10374            1 :             };
   10375              :         }
   10376              : 
   10377            1 :         let expected_result = [
   10378            1 :             Bytes::from_static(b"value 0@0x10"),
   10379            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10380            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10381            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10382            1 :             Bytes::from_static(b"value 4@0x10"),
   10383            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10384            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10385            1 :             Bytes::from_static(b"value 7@0x10"),
   10386            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10387            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10388            1 :         ];
   10389              : 
   10390            1 :         let expected_result_at_gc_horizon = [
   10391            1 :             Bytes::from_static(b"value 0@0x10"),
   10392            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10393            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10394            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10395            1 :             Bytes::from_static(b"value 4@0x10"),
   10396            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10397            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10398            1 :             Bytes::from_static(b"value 7@0x10"),
   10399            1 :             Bytes::from_static(b"value 8@0x10"),
   10400            1 :             Bytes::from_static(b"value 9@0x10"),
   10401            1 :         ];
   10402              : 
   10403            1 :         let expected_result_at_lsn_20 = [
   10404            1 :             Bytes::from_static(b"value 0@0x10"),
   10405            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10406            1 :             Bytes::from_static(b"value 2@0x10"),
   10407            1 :             Bytes::from_static(b"value 3@0x10"),
   10408            1 :             Bytes::from_static(b"value 4@0x10"),
   10409            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10410            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10411            1 :             Bytes::from_static(b"value 7@0x10"),
   10412            1 :             Bytes::from_static(b"value 8@0x10"),
   10413            1 :             Bytes::from_static(b"value 9@0x10"),
   10414            1 :         ];
   10415              : 
   10416            1 :         let expected_result_at_lsn_10 = [
   10417            1 :             Bytes::from_static(b"value 0@0x10"),
   10418            1 :             Bytes::from_static(b"value 1@0x10"),
   10419            1 :             Bytes::from_static(b"value 2@0x10"),
   10420            1 :             Bytes::from_static(b"value 3@0x10"),
   10421            1 :             Bytes::from_static(b"value 4@0x10"),
   10422            1 :             Bytes::from_static(b"value 5@0x10"),
   10423            1 :             Bytes::from_static(b"value 6@0x10"),
   10424            1 :             Bytes::from_static(b"value 7@0x10"),
   10425            1 :             Bytes::from_static(b"value 8@0x10"),
   10426            1 :             Bytes::from_static(b"value 9@0x10"),
   10427            1 :         ];
   10428              : 
   10429            6 :         let verify_result = || async {
   10430            6 :             let gc_horizon = {
   10431            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10432            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10433              :             };
   10434           66 :             for idx in 0..10 {
   10435           60 :                 assert_eq!(
   10436           60 :                     tline
   10437           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10438           60 :                         .await
   10439           60 :                         .unwrap(),
   10440           60 :                     &expected_result[idx]
   10441              :                 );
   10442           60 :                 assert_eq!(
   10443           60 :                     tline
   10444           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10445           60 :                         .await
   10446           60 :                         .unwrap(),
   10447           60 :                     &expected_result_at_gc_horizon[idx]
   10448              :                 );
   10449           60 :                 assert_eq!(
   10450           60 :                     tline
   10451           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10452           60 :                         .await
   10453           60 :                         .unwrap(),
   10454           60 :                     &expected_result_at_lsn_20[idx]
   10455              :                 );
   10456           60 :                 assert_eq!(
   10457           60 :                     tline
   10458           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10459           60 :                         .await
   10460           60 :                         .unwrap(),
   10461           60 :                     &expected_result_at_lsn_10[idx]
   10462              :                 );
   10463              :             }
   10464           12 :         };
   10465              : 
   10466            1 :         verify_result().await;
   10467              : 
   10468            1 :         let cancel = CancellationToken::new();
   10469            1 :         let mut dryrun_flags = EnumSet::new();
   10470            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10471              : 
   10472            1 :         tline
   10473            1 :             .compact_with_gc(
   10474            1 :                 &cancel,
   10475            1 :                 CompactOptions {
   10476            1 :                     flags: dryrun_flags,
   10477            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   10478            1 :                 },
   10479            1 :                 &ctx,
   10480            1 :             )
   10481            1 :             .await
   10482            1 :             .unwrap();
   10483              :         // 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
   10484              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10485            1 :         verify_result().await;
   10486              : 
   10487            1 :         tline
   10488            1 :             .compact_with_gc(
   10489            1 :                 &cancel,
   10490            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10491            1 :                 &ctx,
   10492            1 :             )
   10493            1 :             .await
   10494            1 :             .unwrap();
   10495            1 :         verify_result().await;
   10496              : 
   10497              :         // compact again
   10498            1 :         tline
   10499            1 :             .compact_with_gc(
   10500            1 :                 &cancel,
   10501            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10502            1 :                 &ctx,
   10503            1 :             )
   10504            1 :             .await
   10505            1 :             .unwrap();
   10506            1 :         verify_result().await;
   10507              : 
   10508              :         // increase GC horizon and compact again
   10509              :         {
   10510            1 :             tline
   10511            1 :                 .applied_gc_cutoff_lsn
   10512            1 :                 .lock_for_write()
   10513            1 :                 .store_and_unlock(Lsn(0x38))
   10514            1 :                 .wait()
   10515            1 :                 .await;
   10516              :             // Update GC info
   10517            1 :             let mut guard = tline.gc_info.write().unwrap();
   10518            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10519            1 :             guard.cutoffs.space = Lsn(0x38);
   10520              :         }
   10521            1 :         tline
   10522            1 :             .compact_with_gc(
   10523            1 :                 &cancel,
   10524            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10525            1 :                 &ctx,
   10526            1 :             )
   10527            1 :             .await
   10528            1 :             .unwrap();
   10529            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10530              : 
   10531              :         // not increasing the GC horizon and compact again
   10532            1 :         tline
   10533            1 :             .compact_with_gc(
   10534            1 :                 &cancel,
   10535            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10536            1 :                 &ctx,
   10537            1 :             )
   10538            1 :             .await
   10539            1 :             .unwrap();
   10540            1 :         verify_result().await;
   10541              : 
   10542            2 :         Ok(())
   10543            1 :     }
   10544              : 
   10545              :     #[cfg(feature = "testing")]
   10546              :     #[tokio::test]
   10547            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10548            1 :     {
   10549            1 :         let harness =
   10550            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10551            1 :                 .await?;
   10552            1 :         let (tenant, ctx) = harness.load().await;
   10553              : 
   10554          176 :         fn get_key(id: u32) -> Key {
   10555              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10556          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10557          176 :             key.field6 = id;
   10558          176 :             key
   10559          176 :         }
   10560              : 
   10561            1 :         let img_layer = (0..10)
   10562           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10563            1 :             .collect_vec();
   10564              : 
   10565            1 :         let delta1 = vec![
   10566            1 :             (
   10567            1 :                 get_key(1),
   10568            1 :                 Lsn(0x20),
   10569            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10570            1 :             ),
   10571            1 :             (
   10572            1 :                 get_key(1),
   10573            1 :                 Lsn(0x28),
   10574            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10575            1 :             ),
   10576              :         ];
   10577            1 :         let delta2 = vec![
   10578            1 :             (
   10579            1 :                 get_key(1),
   10580            1 :                 Lsn(0x30),
   10581            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10582            1 :             ),
   10583            1 :             (
   10584            1 :                 get_key(1),
   10585            1 :                 Lsn(0x38),
   10586            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10587            1 :             ),
   10588              :         ];
   10589            1 :         let delta3 = vec![
   10590            1 :             (
   10591            1 :                 get_key(8),
   10592            1 :                 Lsn(0x48),
   10593            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10594            1 :             ),
   10595            1 :             (
   10596            1 :                 get_key(9),
   10597            1 :                 Lsn(0x48),
   10598            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10599            1 :             ),
   10600              :         ];
   10601              : 
   10602            1 :         let tline = tenant
   10603            1 :             .create_test_timeline_with_layers(
   10604            1 :                 TIMELINE_ID,
   10605            1 :                 Lsn(0x10),
   10606            1 :                 DEFAULT_PG_VERSION,
   10607            1 :                 &ctx,
   10608            1 :                 Vec::new(), // in-memory layers
   10609            1 :                 vec![
   10610            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10611            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10612            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10613            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10614            1 :                 ], // delta layers
   10615            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10616            1 :                 Lsn(0x50),
   10617            1 :             )
   10618            1 :             .await?;
   10619              :         {
   10620            1 :             tline
   10621            1 :                 .applied_gc_cutoff_lsn
   10622            1 :                 .lock_for_write()
   10623            1 :                 .store_and_unlock(Lsn(0x30))
   10624            1 :                 .wait()
   10625            1 :                 .await;
   10626              :             // Update GC info
   10627            1 :             let mut guard = tline.gc_info.write().unwrap();
   10628            1 :             *guard = GcInfo {
   10629            1 :                 retain_lsns: vec![
   10630            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10631            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10632            1 :                 ],
   10633            1 :                 cutoffs: GcCutoffs {
   10634            1 :                     time: Some(Lsn(0x30)),
   10635            1 :                     space: Lsn(0x30),
   10636            1 :                 },
   10637            1 :                 leases: Default::default(),
   10638            1 :                 within_ancestor_pitr: false,
   10639            1 :             };
   10640              :         }
   10641              : 
   10642            1 :         let expected_result = [
   10643            1 :             Bytes::from_static(b"value 0@0x10"),
   10644            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10645            1 :             Bytes::from_static(b"value 2@0x10"),
   10646            1 :             Bytes::from_static(b"value 3@0x10"),
   10647            1 :             Bytes::from_static(b"value 4@0x10"),
   10648            1 :             Bytes::from_static(b"value 5@0x10"),
   10649            1 :             Bytes::from_static(b"value 6@0x10"),
   10650            1 :             Bytes::from_static(b"value 7@0x10"),
   10651            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10652            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10653            1 :         ];
   10654              : 
   10655            1 :         let expected_result_at_gc_horizon = [
   10656            1 :             Bytes::from_static(b"value 0@0x10"),
   10657            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10658            1 :             Bytes::from_static(b"value 2@0x10"),
   10659            1 :             Bytes::from_static(b"value 3@0x10"),
   10660            1 :             Bytes::from_static(b"value 4@0x10"),
   10661            1 :             Bytes::from_static(b"value 5@0x10"),
   10662            1 :             Bytes::from_static(b"value 6@0x10"),
   10663            1 :             Bytes::from_static(b"value 7@0x10"),
   10664            1 :             Bytes::from_static(b"value 8@0x10"),
   10665            1 :             Bytes::from_static(b"value 9@0x10"),
   10666            1 :         ];
   10667              : 
   10668            1 :         let expected_result_at_lsn_20 = [
   10669            1 :             Bytes::from_static(b"value 0@0x10"),
   10670            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10671            1 :             Bytes::from_static(b"value 2@0x10"),
   10672            1 :             Bytes::from_static(b"value 3@0x10"),
   10673            1 :             Bytes::from_static(b"value 4@0x10"),
   10674            1 :             Bytes::from_static(b"value 5@0x10"),
   10675            1 :             Bytes::from_static(b"value 6@0x10"),
   10676            1 :             Bytes::from_static(b"value 7@0x10"),
   10677            1 :             Bytes::from_static(b"value 8@0x10"),
   10678            1 :             Bytes::from_static(b"value 9@0x10"),
   10679            1 :         ];
   10680              : 
   10681            1 :         let expected_result_at_lsn_10 = [
   10682            1 :             Bytes::from_static(b"value 0@0x10"),
   10683            1 :             Bytes::from_static(b"value 1@0x10"),
   10684            1 :             Bytes::from_static(b"value 2@0x10"),
   10685            1 :             Bytes::from_static(b"value 3@0x10"),
   10686            1 :             Bytes::from_static(b"value 4@0x10"),
   10687            1 :             Bytes::from_static(b"value 5@0x10"),
   10688            1 :             Bytes::from_static(b"value 6@0x10"),
   10689            1 :             Bytes::from_static(b"value 7@0x10"),
   10690            1 :             Bytes::from_static(b"value 8@0x10"),
   10691            1 :             Bytes::from_static(b"value 9@0x10"),
   10692            1 :         ];
   10693              : 
   10694            4 :         let verify_result = || async {
   10695            4 :             let gc_horizon = {
   10696            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10697            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10698              :             };
   10699           44 :             for idx in 0..10 {
   10700           40 :                 assert_eq!(
   10701           40 :                     tline
   10702           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10703           40 :                         .await
   10704           40 :                         .unwrap(),
   10705           40 :                     &expected_result[idx]
   10706              :                 );
   10707           40 :                 assert_eq!(
   10708           40 :                     tline
   10709           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10710           40 :                         .await
   10711           40 :                         .unwrap(),
   10712           40 :                     &expected_result_at_gc_horizon[idx]
   10713              :                 );
   10714           40 :                 assert_eq!(
   10715           40 :                     tline
   10716           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10717           40 :                         .await
   10718           40 :                         .unwrap(),
   10719           40 :                     &expected_result_at_lsn_20[idx]
   10720              :                 );
   10721           40 :                 assert_eq!(
   10722           40 :                     tline
   10723           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10724           40 :                         .await
   10725           40 :                         .unwrap(),
   10726           40 :                     &expected_result_at_lsn_10[idx]
   10727              :                 );
   10728              :             }
   10729            8 :         };
   10730              : 
   10731            1 :         verify_result().await;
   10732              : 
   10733            1 :         let cancel = CancellationToken::new();
   10734            1 :         let mut dryrun_flags = EnumSet::new();
   10735            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10736              : 
   10737            1 :         tline
   10738            1 :             .compact_with_gc(
   10739            1 :                 &cancel,
   10740            1 :                 CompactOptions {
   10741            1 :                     flags: dryrun_flags,
   10742            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   10743            1 :                 },
   10744            1 :                 &ctx,
   10745            1 :             )
   10746            1 :             .await
   10747            1 :             .unwrap();
   10748              :         // 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
   10749              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10750            1 :         verify_result().await;
   10751              : 
   10752            1 :         tline
   10753            1 :             .compact_with_gc(
   10754            1 :                 &cancel,
   10755            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10756            1 :                 &ctx,
   10757            1 :             )
   10758            1 :             .await
   10759            1 :             .unwrap();
   10760            1 :         verify_result().await;
   10761              : 
   10762              :         // compact again
   10763            1 :         tline
   10764            1 :             .compact_with_gc(
   10765            1 :                 &cancel,
   10766            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10767            1 :                 &ctx,
   10768            1 :             )
   10769            1 :             .await
   10770            1 :             .unwrap();
   10771            1 :         verify_result().await;
   10772              : 
   10773            2 :         Ok(())
   10774            1 :     }
   10775              : 
   10776              :     #[cfg(feature = "testing")]
   10777              :     #[tokio::test]
   10778            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10779              :         use models::CompactLsnRange;
   10780              : 
   10781            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10782            1 :         let (tenant, ctx) = harness.load().await;
   10783              : 
   10784           83 :         fn get_key(id: u32) -> Key {
   10785           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10786           83 :             key.field6 = id;
   10787           83 :             key
   10788           83 :         }
   10789              : 
   10790            1 :         let img_layer = (0..10)
   10791           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10792            1 :             .collect_vec();
   10793              : 
   10794            1 :         let delta1 = vec![
   10795            1 :             (
   10796            1 :                 get_key(1),
   10797            1 :                 Lsn(0x20),
   10798            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10799            1 :             ),
   10800            1 :             (
   10801            1 :                 get_key(2),
   10802            1 :                 Lsn(0x30),
   10803            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10804            1 :             ),
   10805            1 :             (
   10806            1 :                 get_key(3),
   10807            1 :                 Lsn(0x28),
   10808            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10809            1 :             ),
   10810            1 :             (
   10811            1 :                 get_key(3),
   10812            1 :                 Lsn(0x30),
   10813            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10814            1 :             ),
   10815            1 :             (
   10816            1 :                 get_key(3),
   10817            1 :                 Lsn(0x40),
   10818            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10819            1 :             ),
   10820              :         ];
   10821            1 :         let delta2 = vec![
   10822            1 :             (
   10823            1 :                 get_key(5),
   10824            1 :                 Lsn(0x20),
   10825            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10826            1 :             ),
   10827            1 :             (
   10828            1 :                 get_key(6),
   10829            1 :                 Lsn(0x20),
   10830            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10831            1 :             ),
   10832              :         ];
   10833            1 :         let delta3 = vec![
   10834            1 :             (
   10835            1 :                 get_key(8),
   10836            1 :                 Lsn(0x48),
   10837            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10838            1 :             ),
   10839            1 :             (
   10840            1 :                 get_key(9),
   10841            1 :                 Lsn(0x48),
   10842            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10843            1 :             ),
   10844              :         ];
   10845              : 
   10846            1 :         let parent_tline = tenant
   10847            1 :             .create_test_timeline_with_layers(
   10848            1 :                 TIMELINE_ID,
   10849            1 :                 Lsn(0x10),
   10850            1 :                 DEFAULT_PG_VERSION,
   10851            1 :                 &ctx,
   10852            1 :                 vec![],                       // in-memory layers
   10853            1 :                 vec![],                       // delta layers
   10854            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10855            1 :                 Lsn(0x18),
   10856            1 :             )
   10857            1 :             .await?;
   10858              : 
   10859            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10860              : 
   10861            1 :         let branch_tline = tenant
   10862            1 :             .branch_timeline_test_with_layers(
   10863            1 :                 &parent_tline,
   10864            1 :                 NEW_TIMELINE_ID,
   10865            1 :                 Some(Lsn(0x18)),
   10866            1 :                 &ctx,
   10867            1 :                 vec![
   10868            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10869            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10870            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10871            1 :                 ], // delta layers
   10872            1 :                 vec![], // image layers
   10873            1 :                 Lsn(0x50),
   10874            1 :             )
   10875            1 :             .await?;
   10876              : 
   10877            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10878              : 
   10879              :         {
   10880            1 :             parent_tline
   10881            1 :                 .applied_gc_cutoff_lsn
   10882            1 :                 .lock_for_write()
   10883            1 :                 .store_and_unlock(Lsn(0x10))
   10884            1 :                 .wait()
   10885            1 :                 .await;
   10886              :             // Update GC info
   10887            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10888            1 :             *guard = GcInfo {
   10889            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10890            1 :                 cutoffs: GcCutoffs {
   10891            1 :                     time: Some(Lsn(0x10)),
   10892            1 :                     space: Lsn(0x10),
   10893            1 :                 },
   10894            1 :                 leases: Default::default(),
   10895            1 :                 within_ancestor_pitr: false,
   10896            1 :             };
   10897              :         }
   10898              : 
   10899              :         {
   10900            1 :             branch_tline
   10901            1 :                 .applied_gc_cutoff_lsn
   10902            1 :                 .lock_for_write()
   10903            1 :                 .store_and_unlock(Lsn(0x50))
   10904            1 :                 .wait()
   10905            1 :                 .await;
   10906              :             // Update GC info
   10907            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10908            1 :             *guard = GcInfo {
   10909            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10910            1 :                 cutoffs: GcCutoffs {
   10911            1 :                     time: Some(Lsn(0x50)),
   10912            1 :                     space: Lsn(0x50),
   10913            1 :                 },
   10914            1 :                 leases: Default::default(),
   10915            1 :                 within_ancestor_pitr: false,
   10916            1 :             };
   10917              :         }
   10918              : 
   10919            1 :         let expected_result_at_gc_horizon = [
   10920            1 :             Bytes::from_static(b"value 0@0x10"),
   10921            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10922            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10923            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10924            1 :             Bytes::from_static(b"value 4@0x10"),
   10925            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10926            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10927            1 :             Bytes::from_static(b"value 7@0x10"),
   10928            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10929            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10930            1 :         ];
   10931              : 
   10932            1 :         let expected_result_at_lsn_40 = [
   10933            1 :             Bytes::from_static(b"value 0@0x10"),
   10934            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10935            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10936            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10937            1 :             Bytes::from_static(b"value 4@0x10"),
   10938            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10939            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10940            1 :             Bytes::from_static(b"value 7@0x10"),
   10941            1 :             Bytes::from_static(b"value 8@0x10"),
   10942            1 :             Bytes::from_static(b"value 9@0x10"),
   10943            1 :         ];
   10944              : 
   10945            3 :         let verify_result = || async {
   10946           33 :             for idx in 0..10 {
   10947           30 :                 assert_eq!(
   10948           30 :                     branch_tline
   10949           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10950           30 :                         .await
   10951           30 :                         .unwrap(),
   10952           30 :                     &expected_result_at_gc_horizon[idx]
   10953              :                 );
   10954           30 :                 assert_eq!(
   10955           30 :                     branch_tline
   10956           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10957           30 :                         .await
   10958           30 :                         .unwrap(),
   10959           30 :                     &expected_result_at_lsn_40[idx]
   10960              :                 );
   10961              :             }
   10962            6 :         };
   10963              : 
   10964            1 :         verify_result().await;
   10965              : 
   10966            1 :         let cancel = CancellationToken::new();
   10967            1 :         branch_tline
   10968            1 :             .compact_with_gc(
   10969            1 :                 &cancel,
   10970            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   10971            1 :                 &ctx,
   10972            1 :             )
   10973            1 :             .await
   10974            1 :             .unwrap();
   10975              : 
   10976            1 :         verify_result().await;
   10977              : 
   10978              :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10979              :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10980            1 :         branch_tline
   10981            1 :             .compact_with_gc(
   10982            1 :                 &cancel,
   10983            1 :                 CompactOptions {
   10984            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10985            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   10986            1 :                 },
   10987            1 :                 &ctx,
   10988            1 :             )
   10989            1 :             .await
   10990            1 :             .unwrap();
   10991              : 
   10992            1 :         verify_result().await;
   10993              : 
   10994            2 :         Ok(())
   10995            1 :     }
   10996              : 
   10997              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10998              :     // Create an image arrangement where we have to read at different LSN ranges
   10999              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   11000              :     // a delta layer. Like so:
   11001              :     //
   11002              :     //     A      B
   11003              :     // +----------------+ -> delta_layer
   11004              :     // |                |                           ^ lsn
   11005              :     // |       =========|-> nested_image_layer      |
   11006              :     // |       C        |                           |
   11007              :     // +----------------+                           |
   11008              :     // ======== -> baseline_image_layer             +-------> key
   11009              :     //
   11010              :     //
   11011              :     // When querying the key range [A, B) we need to read at different LSN ranges
   11012              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   11013              :     #[cfg(feature = "testing")]
   11014              :     #[tokio::test]
   11015            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   11016            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   11017            1 :         let (tenant, ctx) = harness.load().await;
   11018              : 
   11019            1 :         let will_init_keys = [2, 6];
   11020           22 :         fn get_key(id: u32) -> Key {
   11021           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11022           22 :             key.field6 = id;
   11023           22 :             key
   11024           22 :         }
   11025              : 
   11026            1 :         let mut expected_key_values = HashMap::new();
   11027              : 
   11028            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11029            1 :         let mut baseline_img_layer = Vec::new();
   11030            6 :         for i in 0..5 {
   11031            5 :             let key = get_key(i);
   11032            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11033              : 
   11034            5 :             let removed = expected_key_values.insert(key, value.clone());
   11035            5 :             assert!(removed.is_none());
   11036              : 
   11037            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11038              :         }
   11039              : 
   11040            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11041            1 :         let mut nested_img_layer = Vec::new();
   11042            6 :         for i in 5..10 {
   11043            5 :             let key = get_key(i);
   11044            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11045              : 
   11046            5 :             let removed = expected_key_values.insert(key, value.clone());
   11047            5 :             assert!(removed.is_none());
   11048              : 
   11049            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11050              :         }
   11051              : 
   11052            1 :         let mut delta_layer_spec = Vec::default();
   11053            1 :         let delta_layer_start_lsn = Lsn(0x20);
   11054            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   11055              : 
   11056           11 :         for i in 0..10 {
   11057           10 :             let key = get_key(i);
   11058           10 :             let key_in_nested = nested_img_layer
   11059           10 :                 .iter()
   11060           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   11061           10 :             let lsn = {
   11062           10 :                 if key_in_nested {
   11063            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   11064              :                 } else {
   11065            5 :                     delta_layer_start_lsn
   11066              :                 }
   11067              :             };
   11068              : 
   11069           10 :             let will_init = will_init_keys.contains(&i);
   11070           10 :             if will_init {
   11071            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11072            2 : 
   11073            2 :                 expected_key_values.insert(key, "".to_string());
   11074            8 :             } else {
   11075            8 :                 let delta = format!("@{lsn}");
   11076            8 :                 delta_layer_spec.push((
   11077            8 :                     key,
   11078            8 :                     lsn,
   11079            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11080            8 :                 ));
   11081            8 : 
   11082            8 :                 expected_key_values
   11083            8 :                     .get_mut(&key)
   11084            8 :                     .expect("An image exists for each key")
   11085            8 :                     .push_str(delta.as_str());
   11086            8 :             }
   11087           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   11088              :         }
   11089              : 
   11090            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   11091              : 
   11092            1 :         assert!(
   11093            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   11094            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   11095              :         );
   11096              : 
   11097            1 :         let tline = tenant
   11098            1 :             .create_test_timeline_with_layers(
   11099            1 :                 TIMELINE_ID,
   11100            1 :                 baseline_image_layer_lsn,
   11101            1 :                 DEFAULT_PG_VERSION,
   11102            1 :                 &ctx,
   11103            1 :                 vec![], // in-memory layers
   11104            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   11105            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   11106            1 :                     delta_layer_spec,
   11107            1 :                 )], // delta layers
   11108            1 :                 vec![
   11109            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11110            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11111            1 :                 ], // image layers
   11112            1 :                 delta_layer_end_lsn,
   11113            1 :             )
   11114            1 :             .await?;
   11115              : 
   11116            1 :         let query = VersionedKeySpaceQuery::uniform(
   11117            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11118            1 :             delta_layer_end_lsn,
   11119              :         );
   11120              : 
   11121            1 :         let results = tline
   11122            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11123            1 :             .await
   11124            1 :             .expect("No vectored errors");
   11125           11 :         for (key, res) in results {
   11126           10 :             let value = res.expect("No key errors");
   11127           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11128           10 :             assert_eq!(value, Bytes::from(expected_value));
   11129            1 :         }
   11130            1 : 
   11131            1 :         Ok(())
   11132            1 :     }
   11133              : 
   11134              :     #[cfg(feature = "testing")]
   11135              :     #[tokio::test]
   11136            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   11137            1 :         let harness =
   11138            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   11139            1 :         let (tenant, ctx) = harness.load().await;
   11140              : 
   11141            1 :         let will_init_keys = [2, 6];
   11142           32 :         fn get_key(id: u32) -> Key {
   11143           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11144           32 :             key.field6 = id;
   11145           32 :             key
   11146           32 :         }
   11147              : 
   11148            1 :         let mut expected_key_values = HashMap::new();
   11149              : 
   11150            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11151            1 :         let mut baseline_img_layer = Vec::new();
   11152            6 :         for i in 0..5 {
   11153            5 :             let key = get_key(i);
   11154            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11155              : 
   11156            5 :             let removed = expected_key_values.insert(key, value.clone());
   11157            5 :             assert!(removed.is_none());
   11158              : 
   11159            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11160              :         }
   11161              : 
   11162            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11163            1 :         let mut nested_img_layer = Vec::new();
   11164            6 :         for i in 5..10 {
   11165            5 :             let key = get_key(i);
   11166            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11167              : 
   11168            5 :             let removed = expected_key_values.insert(key, value.clone());
   11169            5 :             assert!(removed.is_none());
   11170              : 
   11171            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11172              :         }
   11173              : 
   11174            1 :         let frozen_layer = {
   11175            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   11176            1 :             let mut data = Vec::new();
   11177           11 :             for i in 0..10 {
   11178           10 :                 let key = get_key(i);
   11179           10 :                 let key_in_nested = nested_img_layer
   11180           10 :                     .iter()
   11181           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   11182           10 :                 let lsn = {
   11183           10 :                     if key_in_nested {
   11184            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   11185              :                     } else {
   11186            5 :                         lsn_range.start
   11187              :                     }
   11188              :                 };
   11189              : 
   11190           10 :                 let will_init = will_init_keys.contains(&i);
   11191           10 :                 if will_init {
   11192            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11193            2 : 
   11194            2 :                     expected_key_values.insert(key, "".to_string());
   11195            8 :                 } else {
   11196            8 :                     let delta = format!("@{lsn}");
   11197            8 :                     data.push((
   11198            8 :                         key,
   11199            8 :                         lsn,
   11200            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11201            8 :                     ));
   11202            8 : 
   11203            8 :                     expected_key_values
   11204            8 :                         .get_mut(&key)
   11205            8 :                         .expect("An image exists for each key")
   11206            8 :                         .push_str(delta.as_str());
   11207            8 :                 }
   11208              :             }
   11209              : 
   11210            1 :             InMemoryLayerTestDesc {
   11211            1 :                 lsn_range,
   11212            1 :                 is_open: false,
   11213            1 :                 data,
   11214            1 :             }
   11215              :         };
   11216              : 
   11217            1 :         let (open_layer, last_record_lsn) = {
   11218            1 :             let start_lsn = Lsn(0x70);
   11219            1 :             let mut data = Vec::new();
   11220            1 :             let mut end_lsn = Lsn(0);
   11221           11 :             for i in 0..10 {
   11222           10 :                 let key = get_key(i);
   11223           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   11224           10 :                 let delta = format!("@{lsn}");
   11225           10 :                 data.push((
   11226           10 :                     key,
   11227           10 :                     lsn,
   11228           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11229           10 :                 ));
   11230           10 : 
   11231           10 :                 expected_key_values
   11232           10 :                     .get_mut(&key)
   11233           10 :                     .expect("An image exists for each key")
   11234           10 :                     .push_str(delta.as_str());
   11235           10 : 
   11236           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   11237           10 :             }
   11238              : 
   11239            1 :             (
   11240            1 :                 InMemoryLayerTestDesc {
   11241            1 :                     lsn_range: start_lsn..Lsn::MAX,
   11242            1 :                     is_open: true,
   11243            1 :                     data,
   11244            1 :                 },
   11245            1 :                 end_lsn,
   11246            1 :             )
   11247              :         };
   11248              : 
   11249            1 :         assert!(
   11250            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   11251            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   11252              :         );
   11253              : 
   11254            1 :         let tline = tenant
   11255            1 :             .create_test_timeline_with_layers(
   11256            1 :                 TIMELINE_ID,
   11257            1 :                 baseline_image_layer_lsn,
   11258            1 :                 DEFAULT_PG_VERSION,
   11259            1 :                 &ctx,
   11260            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   11261            1 :                 Vec::new(),                     // delta layers
   11262            1 :                 vec![
   11263            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11264            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11265            1 :                 ], // image layers
   11266            1 :                 last_record_lsn,
   11267            1 :             )
   11268            1 :             .await?;
   11269              : 
   11270            1 :         let query = VersionedKeySpaceQuery::uniform(
   11271            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11272            1 :             last_record_lsn,
   11273              :         );
   11274              : 
   11275            1 :         let results = tline
   11276            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11277            1 :             .await
   11278            1 :             .expect("No vectored errors");
   11279           11 :         for (key, res) in results {
   11280           10 :             let value = res.expect("No key errors");
   11281           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11282           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   11283            1 : 
   11284           10 :             tracing::info!("key={key} value={expected_value}");
   11285            1 :         }
   11286            1 : 
   11287            1 :         Ok(())
   11288            1 :     }
   11289              : 
   11290              :     // A randomized read path test. Generates a layer map according to a deterministic
   11291              :     // specification. Fills the (key, LSN) space in random manner and then performs
   11292              :     // random scattered queries validating the results against in-memory storage.
   11293              :     //
   11294              :     // See this internal Notion page for a diagram of the layer map:
   11295              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   11296              :     //
   11297              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   11298              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   11299              :     // to run multiple instances in parallel:
   11300              :     //
   11301              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   11302              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   11303              :     #[cfg(feature = "testing")]
   11304              :     #[tokio::test]
   11305            1 :     async fn test_read_path() -> anyhow::Result<()> {
   11306              :         use rand::seq::IndexedRandom;
   11307              : 
   11308            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   11309            0 :             let seed: u64 = rand::rng().random();
   11310            0 :             seed
   11311              :         } else {
   11312              :             // Use a hard-coded seed when not in fuzzing mode.
   11313              :             // Note that with the current approach results are not reproducible
   11314              :             // accross platforms and Rust releases.
   11315              :             const SEED: u64 = 0;
   11316            1 :             SEED
   11317              :         };
   11318              : 
   11319            1 :         let mut random = StdRng::seed_from_u64(seed);
   11320              : 
   11321            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   11322              :             const QUERIES: u64 = 5000;
   11323            0 :             let will_init_chance: u8 = random.random_range(0..=10);
   11324            0 :             let gap_chance: u8 = random.random_range(0..=50);
   11325              : 
   11326            0 :             (QUERIES, will_init_chance, gap_chance)
   11327              :         } else {
   11328              :             const QUERIES: u64 = 1000;
   11329              :             const WILL_INIT_CHANCE: u8 = 1;
   11330              :             const GAP_CHANCE: u8 = 5;
   11331              : 
   11332            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   11333              :         };
   11334              : 
   11335            1 :         let harness = TenantHarness::create("test_read_path").await?;
   11336            1 :         let (tenant, ctx) = harness.load().await;
   11337              : 
   11338            1 :         tracing::info!("Using random seed: {seed}");
   11339            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   11340              : 
   11341              :         // Define the layer map shape. Note that this part is not randomized.
   11342              : 
   11343              :         const KEY_DIMENSION_SIZE: u32 = 99;
   11344            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11345            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11346            1 :         let total_key_range = start_key..end_key;
   11347            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11348            1 :         let total_start_lsn = Lsn(104);
   11349            1 :         let last_record_lsn = Lsn(504);
   11350              : 
   11351            1 :         assert!(total_key_range_size % 3 == 0);
   11352              : 
   11353            1 :         let in_memory_layers_shape = vec![
   11354            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11355            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11356              :         ];
   11357              : 
   11358            1 :         let delta_layers_shape = vec![
   11359            1 :             (
   11360            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11361            1 :                 Lsn(200)..Lsn(304),
   11362            1 :             ),
   11363            1 :             (
   11364            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11365            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11366            1 :                 Lsn(200)..Lsn(304),
   11367            1 :             ),
   11368            1 :             (
   11369            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11370            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11371            1 :                 Lsn(200)..Lsn(304),
   11372            1 :             ),
   11373              :         ];
   11374              : 
   11375            1 :         let image_layers_shape = vec![
   11376            1 :             (
   11377            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11378            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11379            1 :                 Lsn(456),
   11380            1 :             ),
   11381            1 :             (
   11382            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11383            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11384            1 :                 Lsn(256),
   11385            1 :             ),
   11386            1 :             (total_key_range.clone(), total_start_lsn),
   11387              :         ];
   11388              : 
   11389            1 :         let specification = TestTimelineSpecification {
   11390            1 :             start_lsn: total_start_lsn,
   11391            1 :             last_record_lsn,
   11392            1 :             in_memory_layers_shape,
   11393            1 :             delta_layers_shape,
   11394            1 :             image_layers_shape,
   11395            1 :             gap_chance,
   11396            1 :             will_init_chance,
   11397            1 :         };
   11398              : 
   11399              :         // Create and randomly fill in the layers according to the specification
   11400            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11401            1 :             &tenant,
   11402            1 :             TIMELINE_ID,
   11403            1 :             DEFAULT_PG_VERSION,
   11404            1 :             specification,
   11405            1 :             &mut random,
   11406            1 :             &ctx,
   11407            1 :         )
   11408            1 :         .await?;
   11409              : 
   11410              :         // Now generate queries based on the interesting lsns that we've collected.
   11411              :         //
   11412              :         // While there's still room in the query, pick and interesting LSN and a random
   11413              :         // key. Then roll the dice to see if the next key should also be included in
   11414              :         // the query. When the roll fails, break the "batch" and pick another point in the
   11415              :         // (key, LSN) space.
   11416              : 
   11417              :         const PICK_NEXT_CHANCE: u8 = 50;
   11418            1 :         for _ in 0..queries {
   11419         1000 :             let query = {
   11420         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11421         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11422            1 : 
   11423        22401 :                 while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11424        21401 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11425        21401 :                     let mut selected_key =
   11426        21401 :                         start_key.add(random.random_range(0..KEY_DIMENSION_SIZE));
   11427            1 : 
   11428        37626 :                     while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11429        37104 :                         if used_keys.contains(&selected_key)
   11430        32144 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11431            1 :                         {
   11432         5104 :                             break;
   11433        32000 :                         }
   11434            1 : 
   11435        32000 :                         keyspaces_at_lsn
   11436        32000 :                             .entry(*selected_lsn)
   11437        32000 :                             .or_default()
   11438        32000 :                             .add_key(selected_key);
   11439        32000 :                         used_keys.insert(selected_key);
   11440            1 : 
   11441        32000 :                         let pick_next = random.random_range(0..=100) <= PICK_NEXT_CHANCE;
   11442        32000 :                         if pick_next {
   11443        16225 :                             selected_key = selected_key.next();
   11444        16225 :                         } else {
   11445        15775 :                             break;
   11446            1 :                         }
   11447            1 :                     }
   11448            1 :                 }
   11449            1 : 
   11450         1000 :                 VersionedKeySpaceQuery::scattered(
   11451         1000 :                     keyspaces_at_lsn
   11452         1000 :                         .into_iter()
   11453        11916 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11454         1000 :                         .collect(),
   11455            1 :                 )
   11456            1 :             };
   11457            1 : 
   11458            1 :             // Run the query and validate the results
   11459            1 : 
   11460         1000 :             let results = tline
   11461         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11462         1000 :                 .await;
   11463            1 : 
   11464         1000 :             let blobs = match results {
   11465         1000 :                 Ok(ok) => ok,
   11466            1 :                 Err(err) => {
   11467            1 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11468            1 :                 }
   11469            1 :             };
   11470            1 : 
   11471        32000 :             for (key, key_res) in blobs.into_iter() {
   11472        32000 :                 match key_res {
   11473        32000 :                     Ok(blob) => {
   11474        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11475        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11476            1 : 
   11477        32000 :                         if blob != expected {
   11478            1 :                             tracing::error!(
   11479            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11480            1 :                             );
   11481        32000 :                         }
   11482            1 : 
   11483        32000 :                         assert_eq!(blob, expected);
   11484            1 :                     }
   11485            1 :                     Err(err) => {
   11486            1 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11487            1 : 
   11488            1 :                         panic!(
   11489            1 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11490            1 :                         );
   11491            1 :                     }
   11492            1 :                 }
   11493            1 :             }
   11494            1 :         }
   11495            1 : 
   11496            1 :         Ok(())
   11497            1 :     }
   11498              : 
   11499          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11500          107 :         (
   11501          107 :             k1.is_delta,
   11502          107 :             k1.key_range.start,
   11503          107 :             k1.key_range.end,
   11504          107 :             k1.lsn_range.start,
   11505          107 :             k1.lsn_range.end,
   11506          107 :         )
   11507          107 :             .cmp(&(
   11508          107 :                 k2.is_delta,
   11509          107 :                 k2.key_range.start,
   11510          107 :                 k2.key_range.end,
   11511          107 :                 k2.lsn_range.start,
   11512          107 :                 k2.lsn_range.end,
   11513          107 :             ))
   11514          107 :     }
   11515              : 
   11516           12 :     async fn inspect_and_sort(
   11517           12 :         tline: &Arc<Timeline>,
   11518           12 :         filter: Option<std::ops::Range<Key>>,
   11519           12 :     ) -> Vec<PersistentLayerKey> {
   11520           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11521           12 :         if let Some(filter) = filter {
   11522           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11523            1 :         }
   11524           12 :         all_layers.sort_by(sort_layer_key);
   11525           12 :         all_layers
   11526           12 :     }
   11527              : 
   11528              :     #[cfg(feature = "testing")]
   11529           11 :     fn check_layer_map_key_eq(
   11530           11 :         mut left: Vec<PersistentLayerKey>,
   11531           11 :         mut right: Vec<PersistentLayerKey>,
   11532           11 :     ) {
   11533           11 :         left.sort_by(sort_layer_key);
   11534           11 :         right.sort_by(sort_layer_key);
   11535           11 :         if left != right {
   11536            0 :             eprintln!("---LEFT---");
   11537            0 :             for left in left.iter() {
   11538            0 :                 eprintln!("{left}");
   11539            0 :             }
   11540            0 :             eprintln!("---RIGHT---");
   11541            0 :             for right in right.iter() {
   11542            0 :                 eprintln!("{right}");
   11543            0 :             }
   11544            0 :             assert_eq!(left, right);
   11545           11 :         }
   11546           11 :     }
   11547              : 
   11548              :     #[cfg(feature = "testing")]
   11549              :     #[tokio::test]
   11550            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11551            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11552            1 :         let (tenant, ctx) = harness.load().await;
   11553              : 
   11554           91 :         fn get_key(id: u32) -> Key {
   11555              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11556           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11557           91 :             key.field6 = id;
   11558           91 :             key
   11559           91 :         }
   11560              : 
   11561              :         // img layer at 0x10
   11562            1 :         let img_layer = (0..10)
   11563           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11564            1 :             .collect_vec();
   11565              : 
   11566            1 :         let delta1 = vec![
   11567            1 :             (
   11568            1 :                 get_key(1),
   11569            1 :                 Lsn(0x20),
   11570            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11571            1 :             ),
   11572            1 :             (
   11573            1 :                 get_key(2),
   11574            1 :                 Lsn(0x30),
   11575            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11576            1 :             ),
   11577            1 :             (
   11578            1 :                 get_key(3),
   11579            1 :                 Lsn(0x40),
   11580            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11581            1 :             ),
   11582              :         ];
   11583            1 :         let delta2 = vec![
   11584            1 :             (
   11585            1 :                 get_key(5),
   11586            1 :                 Lsn(0x20),
   11587            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11588            1 :             ),
   11589            1 :             (
   11590            1 :                 get_key(6),
   11591            1 :                 Lsn(0x20),
   11592            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11593            1 :             ),
   11594              :         ];
   11595            1 :         let delta3 = vec![
   11596            1 :             (
   11597            1 :                 get_key(8),
   11598            1 :                 Lsn(0x48),
   11599            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11600            1 :             ),
   11601            1 :             (
   11602            1 :                 get_key(9),
   11603            1 :                 Lsn(0x48),
   11604            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11605            1 :             ),
   11606              :         ];
   11607              : 
   11608            1 :         let tline = tenant
   11609            1 :             .create_test_timeline_with_layers(
   11610            1 :                 TIMELINE_ID,
   11611            1 :                 Lsn(0x10),
   11612            1 :                 DEFAULT_PG_VERSION,
   11613            1 :                 &ctx,
   11614            1 :                 vec![], // in-memory layers
   11615            1 :                 vec![
   11616            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11617            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11618            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11619            1 :                 ], // delta layers
   11620            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11621            1 :                 Lsn(0x50),
   11622            1 :             )
   11623            1 :             .await?;
   11624              : 
   11625              :         {
   11626            1 :             tline
   11627            1 :                 .applied_gc_cutoff_lsn
   11628            1 :                 .lock_for_write()
   11629            1 :                 .store_and_unlock(Lsn(0x30))
   11630            1 :                 .wait()
   11631            1 :                 .await;
   11632              :             // Update GC info
   11633            1 :             let mut guard = tline.gc_info.write().unwrap();
   11634            1 :             *guard = GcInfo {
   11635            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11636            1 :                 cutoffs: GcCutoffs {
   11637            1 :                     time: Some(Lsn(0x30)),
   11638            1 :                     space: Lsn(0x30),
   11639            1 :                 },
   11640            1 :                 leases: Default::default(),
   11641            1 :                 within_ancestor_pitr: false,
   11642            1 :             };
   11643              :         }
   11644              : 
   11645            1 :         let cancel = CancellationToken::new();
   11646              : 
   11647              :         // Do a partial compaction on key range 0..2
   11648            1 :         tline
   11649            1 :             .compact_with_gc(
   11650            1 :                 &cancel,
   11651            1 :                 CompactOptions {
   11652            1 :                     flags: EnumSet::new(),
   11653            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11654            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   11655            1 :                 },
   11656            1 :                 &ctx,
   11657            1 :             )
   11658            1 :             .await
   11659            1 :             .unwrap();
   11660            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11661            1 :         check_layer_map_key_eq(
   11662            1 :             all_layers,
   11663            1 :             vec![
   11664              :                 // newly-generated image layer for the partial compaction range 0-2
   11665            1 :                 PersistentLayerKey {
   11666            1 :                     key_range: get_key(0)..get_key(2),
   11667            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11668            1 :                     is_delta: false,
   11669            1 :                 },
   11670            1 :                 PersistentLayerKey {
   11671            1 :                     key_range: get_key(0)..get_key(10),
   11672            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11673            1 :                     is_delta: false,
   11674            1 :                 },
   11675              :                 // delta1 is split and the second part is rewritten
   11676            1 :                 PersistentLayerKey {
   11677            1 :                     key_range: get_key(2)..get_key(4),
   11678            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11679            1 :                     is_delta: true,
   11680            1 :                 },
   11681            1 :                 PersistentLayerKey {
   11682            1 :                     key_range: get_key(5)..get_key(7),
   11683            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11684            1 :                     is_delta: true,
   11685            1 :                 },
   11686            1 :                 PersistentLayerKey {
   11687            1 :                     key_range: get_key(8)..get_key(10),
   11688            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11689            1 :                     is_delta: true,
   11690            1 :                 },
   11691              :             ],
   11692              :         );
   11693              : 
   11694              :         // Do a partial compaction on key range 2..4
   11695            1 :         tline
   11696            1 :             .compact_with_gc(
   11697            1 :                 &cancel,
   11698            1 :                 CompactOptions {
   11699            1 :                     flags: EnumSet::new(),
   11700            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11701            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   11702            1 :                 },
   11703            1 :                 &ctx,
   11704            1 :             )
   11705            1 :             .await
   11706            1 :             .unwrap();
   11707            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11708            1 :         check_layer_map_key_eq(
   11709            1 :             all_layers,
   11710            1 :             vec![
   11711            1 :                 PersistentLayerKey {
   11712            1 :                     key_range: get_key(0)..get_key(2),
   11713            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11714            1 :                     is_delta: false,
   11715            1 :                 },
   11716            1 :                 PersistentLayerKey {
   11717            1 :                     key_range: get_key(0)..get_key(10),
   11718            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11719            1 :                     is_delta: false,
   11720            1 :                 },
   11721              :                 // image layer generated for the compaction range 2-4
   11722            1 :                 PersistentLayerKey {
   11723            1 :                     key_range: get_key(2)..get_key(4),
   11724            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11725            1 :                     is_delta: false,
   11726            1 :                 },
   11727              :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11728            1 :                 PersistentLayerKey {
   11729            1 :                     key_range: get_key(2)..get_key(4),
   11730            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11731            1 :                     is_delta: true,
   11732            1 :                 },
   11733            1 :                 PersistentLayerKey {
   11734            1 :                     key_range: get_key(5)..get_key(7),
   11735            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11736            1 :                     is_delta: true,
   11737            1 :                 },
   11738            1 :                 PersistentLayerKey {
   11739            1 :                     key_range: get_key(8)..get_key(10),
   11740            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11741            1 :                     is_delta: true,
   11742            1 :                 },
   11743              :             ],
   11744              :         );
   11745              : 
   11746              :         // Do a partial compaction on key range 4..9
   11747            1 :         tline
   11748            1 :             .compact_with_gc(
   11749            1 :                 &cancel,
   11750            1 :                 CompactOptions {
   11751            1 :                     flags: EnumSet::new(),
   11752            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11753            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   11754            1 :                 },
   11755            1 :                 &ctx,
   11756            1 :             )
   11757            1 :             .await
   11758            1 :             .unwrap();
   11759            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11760            1 :         check_layer_map_key_eq(
   11761            1 :             all_layers,
   11762            1 :             vec![
   11763            1 :                 PersistentLayerKey {
   11764            1 :                     key_range: get_key(0)..get_key(2),
   11765            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11766            1 :                     is_delta: false,
   11767            1 :                 },
   11768            1 :                 PersistentLayerKey {
   11769            1 :                     key_range: get_key(0)..get_key(10),
   11770            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11771            1 :                     is_delta: false,
   11772            1 :                 },
   11773            1 :                 PersistentLayerKey {
   11774            1 :                     key_range: get_key(2)..get_key(4),
   11775            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11776            1 :                     is_delta: false,
   11777            1 :                 },
   11778            1 :                 PersistentLayerKey {
   11779            1 :                     key_range: get_key(2)..get_key(4),
   11780            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11781            1 :                     is_delta: true,
   11782            1 :                 },
   11783              :                 // image layer generated for this compaction range
   11784            1 :                 PersistentLayerKey {
   11785            1 :                     key_range: get_key(4)..get_key(9),
   11786            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11787            1 :                     is_delta: false,
   11788            1 :                 },
   11789            1 :                 PersistentLayerKey {
   11790            1 :                     key_range: get_key(8)..get_key(10),
   11791            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11792            1 :                     is_delta: true,
   11793            1 :                 },
   11794              :             ],
   11795              :         );
   11796              : 
   11797              :         // Do a partial compaction on key range 9..10
   11798            1 :         tline
   11799            1 :             .compact_with_gc(
   11800            1 :                 &cancel,
   11801            1 :                 CompactOptions {
   11802            1 :                     flags: EnumSet::new(),
   11803            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11804            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   11805            1 :                 },
   11806            1 :                 &ctx,
   11807            1 :             )
   11808            1 :             .await
   11809            1 :             .unwrap();
   11810            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11811            1 :         check_layer_map_key_eq(
   11812            1 :             all_layers,
   11813            1 :             vec![
   11814            1 :                 PersistentLayerKey {
   11815            1 :                     key_range: get_key(0)..get_key(2),
   11816            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11817            1 :                     is_delta: false,
   11818            1 :                 },
   11819            1 :                 PersistentLayerKey {
   11820            1 :                     key_range: get_key(0)..get_key(10),
   11821            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11822            1 :                     is_delta: false,
   11823            1 :                 },
   11824            1 :                 PersistentLayerKey {
   11825            1 :                     key_range: get_key(2)..get_key(4),
   11826            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11827            1 :                     is_delta: false,
   11828            1 :                 },
   11829            1 :                 PersistentLayerKey {
   11830            1 :                     key_range: get_key(2)..get_key(4),
   11831            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11832            1 :                     is_delta: true,
   11833            1 :                 },
   11834            1 :                 PersistentLayerKey {
   11835            1 :                     key_range: get_key(4)..get_key(9),
   11836            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11837            1 :                     is_delta: false,
   11838            1 :                 },
   11839              :                 // image layer generated for the compaction range
   11840            1 :                 PersistentLayerKey {
   11841            1 :                     key_range: get_key(9)..get_key(10),
   11842            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11843            1 :                     is_delta: false,
   11844            1 :                 },
   11845            1 :                 PersistentLayerKey {
   11846            1 :                     key_range: get_key(8)..get_key(10),
   11847            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11848            1 :                     is_delta: true,
   11849            1 :                 },
   11850              :             ],
   11851              :         );
   11852              : 
   11853              :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11854            1 :         tline
   11855            1 :             .compact_with_gc(
   11856            1 :                 &cancel,
   11857            1 :                 CompactOptions {
   11858            1 :                     flags: EnumSet::new(),
   11859            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11860            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   11861            1 :                 },
   11862            1 :                 &ctx,
   11863            1 :             )
   11864            1 :             .await
   11865            1 :             .unwrap();
   11866            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11867            1 :         check_layer_map_key_eq(
   11868            1 :             all_layers,
   11869            1 :             vec![
   11870              :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11871            1 :                 PersistentLayerKey {
   11872            1 :                     key_range: get_key(0)..get_key(10),
   11873            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11874            1 :                     is_delta: false,
   11875            1 :                 },
   11876            1 :                 PersistentLayerKey {
   11877            1 :                     key_range: get_key(2)..get_key(4),
   11878            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11879            1 :                     is_delta: true,
   11880            1 :                 },
   11881            1 :                 PersistentLayerKey {
   11882            1 :                     key_range: get_key(8)..get_key(10),
   11883            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11884            1 :                     is_delta: true,
   11885            1 :                 },
   11886              :             ],
   11887              :         );
   11888            2 :         Ok(())
   11889            1 :     }
   11890              : 
   11891              :     #[cfg(feature = "testing")]
   11892              :     #[tokio::test]
   11893            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11894            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11895            1 :             .await
   11896            1 :             .unwrap();
   11897            1 :         let (tenant, ctx) = harness.load().await;
   11898            1 :         let tline_parent = tenant
   11899            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11900            1 :             .await
   11901            1 :             .unwrap();
   11902            1 :         let tline_child = tenant
   11903            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11904            1 :             .await
   11905            1 :             .unwrap();
   11906              :         {
   11907            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11908            1 :             assert_eq!(
   11909            1 :                 gc_info_parent.retain_lsns,
   11910            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11911              :             );
   11912              :         }
   11913              :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11914            1 :         tline_child
   11915            1 :             .remote_client
   11916            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11917            1 :             .unwrap();
   11918            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11919            1 :         offload_timeline(&tenant, &tline_child)
   11920            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11921            1 :             .await.unwrap();
   11922            1 :         let child_timeline_id = tline_child.timeline_id;
   11923            1 :         Arc::try_unwrap(tline_child).unwrap();
   11924              : 
   11925              :         {
   11926            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11927            1 :             assert_eq!(
   11928            1 :                 gc_info_parent.retain_lsns,
   11929            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11930              :             );
   11931              :         }
   11932              : 
   11933            1 :         tenant
   11934            1 :             .get_offloaded_timeline(child_timeline_id)
   11935            1 :             .unwrap()
   11936            1 :             .defuse_for_tenant_drop();
   11937              : 
   11938            2 :         Ok(())
   11939            1 :     }
   11940              : 
   11941              :     #[cfg(feature = "testing")]
   11942              :     #[tokio::test]
   11943            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11944            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11945            1 :         let (tenant, ctx) = harness.load().await;
   11946              : 
   11947          148 :         fn get_key(id: u32) -> Key {
   11948              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11949          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11950          148 :             key.field6 = id;
   11951          148 :             key
   11952          148 :         }
   11953              : 
   11954            1 :         let img_layer = (0..10)
   11955           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11956            1 :             .collect_vec();
   11957              : 
   11958            1 :         let delta1 = vec![(
   11959            1 :             get_key(1),
   11960            1 :             Lsn(0x20),
   11961            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11962            1 :         )];
   11963            1 :         let delta4 = vec![(
   11964            1 :             get_key(1),
   11965            1 :             Lsn(0x28),
   11966            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11967            1 :         )];
   11968            1 :         let delta2 = vec![
   11969            1 :             (
   11970            1 :                 get_key(1),
   11971            1 :                 Lsn(0x30),
   11972            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11973            1 :             ),
   11974            1 :             (
   11975            1 :                 get_key(1),
   11976            1 :                 Lsn(0x38),
   11977            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11978            1 :             ),
   11979              :         ];
   11980            1 :         let delta3 = vec![
   11981            1 :             (
   11982            1 :                 get_key(8),
   11983            1 :                 Lsn(0x48),
   11984            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11985            1 :             ),
   11986            1 :             (
   11987            1 :                 get_key(9),
   11988            1 :                 Lsn(0x48),
   11989            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11990            1 :             ),
   11991              :         ];
   11992              : 
   11993            1 :         let tline = tenant
   11994            1 :             .create_test_timeline_with_layers(
   11995            1 :                 TIMELINE_ID,
   11996            1 :                 Lsn(0x10),
   11997            1 :                 DEFAULT_PG_VERSION,
   11998            1 :                 &ctx,
   11999            1 :                 vec![], // in-memory layers
   12000            1 :                 vec![
   12001            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12002            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12003            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12004            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12005            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12006            1 :                 ], // delta layers
   12007            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12008            1 :                 Lsn(0x50),
   12009            1 :             )
   12010            1 :             .await?;
   12011              :         {
   12012            1 :             tline
   12013            1 :                 .applied_gc_cutoff_lsn
   12014            1 :                 .lock_for_write()
   12015            1 :                 .store_and_unlock(Lsn(0x30))
   12016            1 :                 .wait()
   12017            1 :                 .await;
   12018              :             // Update GC info
   12019            1 :             let mut guard = tline.gc_info.write().unwrap();
   12020            1 :             *guard = GcInfo {
   12021            1 :                 retain_lsns: vec![
   12022            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12023            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12024            1 :                 ],
   12025            1 :                 cutoffs: GcCutoffs {
   12026            1 :                     time: Some(Lsn(0x30)),
   12027            1 :                     space: Lsn(0x30),
   12028            1 :                 },
   12029            1 :                 leases: Default::default(),
   12030            1 :                 within_ancestor_pitr: false,
   12031            1 :             };
   12032              :         }
   12033              : 
   12034            1 :         let expected_result = [
   12035            1 :             Bytes::from_static(b"value 0@0x10"),
   12036            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12037            1 :             Bytes::from_static(b"value 2@0x10"),
   12038            1 :             Bytes::from_static(b"value 3@0x10"),
   12039            1 :             Bytes::from_static(b"value 4@0x10"),
   12040            1 :             Bytes::from_static(b"value 5@0x10"),
   12041            1 :             Bytes::from_static(b"value 6@0x10"),
   12042            1 :             Bytes::from_static(b"value 7@0x10"),
   12043            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12044            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12045            1 :         ];
   12046              : 
   12047            1 :         let expected_result_at_gc_horizon = [
   12048            1 :             Bytes::from_static(b"value 0@0x10"),
   12049            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12050            1 :             Bytes::from_static(b"value 2@0x10"),
   12051            1 :             Bytes::from_static(b"value 3@0x10"),
   12052            1 :             Bytes::from_static(b"value 4@0x10"),
   12053            1 :             Bytes::from_static(b"value 5@0x10"),
   12054            1 :             Bytes::from_static(b"value 6@0x10"),
   12055            1 :             Bytes::from_static(b"value 7@0x10"),
   12056            1 :             Bytes::from_static(b"value 8@0x10"),
   12057            1 :             Bytes::from_static(b"value 9@0x10"),
   12058            1 :         ];
   12059              : 
   12060            1 :         let expected_result_at_lsn_20 = [
   12061            1 :             Bytes::from_static(b"value 0@0x10"),
   12062            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12063            1 :             Bytes::from_static(b"value 2@0x10"),
   12064            1 :             Bytes::from_static(b"value 3@0x10"),
   12065            1 :             Bytes::from_static(b"value 4@0x10"),
   12066            1 :             Bytes::from_static(b"value 5@0x10"),
   12067            1 :             Bytes::from_static(b"value 6@0x10"),
   12068            1 :             Bytes::from_static(b"value 7@0x10"),
   12069            1 :             Bytes::from_static(b"value 8@0x10"),
   12070            1 :             Bytes::from_static(b"value 9@0x10"),
   12071            1 :         ];
   12072              : 
   12073            1 :         let expected_result_at_lsn_10 = [
   12074            1 :             Bytes::from_static(b"value 0@0x10"),
   12075            1 :             Bytes::from_static(b"value 1@0x10"),
   12076            1 :             Bytes::from_static(b"value 2@0x10"),
   12077            1 :             Bytes::from_static(b"value 3@0x10"),
   12078            1 :             Bytes::from_static(b"value 4@0x10"),
   12079            1 :             Bytes::from_static(b"value 5@0x10"),
   12080            1 :             Bytes::from_static(b"value 6@0x10"),
   12081            1 :             Bytes::from_static(b"value 7@0x10"),
   12082            1 :             Bytes::from_static(b"value 8@0x10"),
   12083            1 :             Bytes::from_static(b"value 9@0x10"),
   12084            1 :         ];
   12085              : 
   12086            3 :         let verify_result = || async {
   12087            3 :             let gc_horizon = {
   12088            3 :                 let gc_info = tline.gc_info.read().unwrap();
   12089            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   12090              :             };
   12091           33 :             for idx in 0..10 {
   12092           30 :                 assert_eq!(
   12093           30 :                     tline
   12094           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12095           30 :                         .await
   12096           30 :                         .unwrap(),
   12097           30 :                     &expected_result[idx]
   12098              :                 );
   12099           30 :                 assert_eq!(
   12100           30 :                     tline
   12101           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12102           30 :                         .await
   12103           30 :                         .unwrap(),
   12104           30 :                     &expected_result_at_gc_horizon[idx]
   12105              :                 );
   12106           30 :                 assert_eq!(
   12107           30 :                     tline
   12108           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12109           30 :                         .await
   12110           30 :                         .unwrap(),
   12111           30 :                     &expected_result_at_lsn_20[idx]
   12112              :                 );
   12113           30 :                 assert_eq!(
   12114           30 :                     tline
   12115           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12116           30 :                         .await
   12117           30 :                         .unwrap(),
   12118           30 :                     &expected_result_at_lsn_10[idx]
   12119              :                 );
   12120              :             }
   12121            6 :         };
   12122              : 
   12123            1 :         verify_result().await;
   12124              : 
   12125            1 :         let cancel = CancellationToken::new();
   12126            1 :         tline
   12127            1 :             .compact_with_gc(
   12128            1 :                 &cancel,
   12129            1 :                 CompactOptions {
   12130            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   12131            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   12132            1 :                 },
   12133            1 :                 &ctx,
   12134            1 :             )
   12135            1 :             .await
   12136            1 :             .unwrap();
   12137            1 :         verify_result().await;
   12138              : 
   12139            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12140            1 :         check_layer_map_key_eq(
   12141            1 :             all_layers,
   12142            1 :             vec![
   12143              :                 // The original image layer, not compacted
   12144            1 :                 PersistentLayerKey {
   12145            1 :                     key_range: get_key(0)..get_key(10),
   12146            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12147            1 :                     is_delta: false,
   12148            1 :                 },
   12149              :                 // Delta layer below the specified above_lsn not compacted
   12150            1 :                 PersistentLayerKey {
   12151            1 :                     key_range: get_key(1)..get_key(2),
   12152            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   12153            1 :                     is_delta: true,
   12154            1 :                 },
   12155              :                 // Delta layer compacted above the LSN
   12156            1 :                 PersistentLayerKey {
   12157            1 :                     key_range: get_key(1)..get_key(10),
   12158            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   12159            1 :                     is_delta: true,
   12160            1 :                 },
   12161              :             ],
   12162              :         );
   12163              : 
   12164              :         // compact again
   12165            1 :         tline
   12166            1 :             .compact_with_gc(
   12167            1 :                 &cancel,
   12168            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   12169            1 :                 &ctx,
   12170            1 :             )
   12171            1 :             .await
   12172            1 :             .unwrap();
   12173            1 :         verify_result().await;
   12174              : 
   12175            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12176            1 :         check_layer_map_key_eq(
   12177            1 :             all_layers,
   12178            1 :             vec![
   12179              :                 // The compacted image layer (full key range)
   12180            1 :                 PersistentLayerKey {
   12181            1 :                     key_range: Key::MIN..Key::MAX,
   12182            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12183            1 :                     is_delta: false,
   12184            1 :                 },
   12185              :                 // All other data in the delta layer
   12186            1 :                 PersistentLayerKey {
   12187            1 :                     key_range: get_key(1)..get_key(10),
   12188            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12189            1 :                     is_delta: true,
   12190            1 :                 },
   12191              :             ],
   12192              :         );
   12193              : 
   12194            2 :         Ok(())
   12195            1 :     }
   12196              : 
   12197              :     #[cfg(feature = "testing")]
   12198              :     #[tokio::test]
   12199            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   12200            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   12201            1 :         let (tenant, ctx) = harness.load().await;
   12202              : 
   12203          254 :         fn get_key(id: u32) -> Key {
   12204              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12205          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12206          254 :             key.field6 = id;
   12207          254 :             key
   12208          254 :         }
   12209              : 
   12210            1 :         let img_layer = (0..10)
   12211           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12212            1 :             .collect_vec();
   12213              : 
   12214            1 :         let delta1 = vec![(
   12215            1 :             get_key(1),
   12216            1 :             Lsn(0x20),
   12217            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12218            1 :         )];
   12219            1 :         let delta4 = vec![(
   12220            1 :             get_key(1),
   12221            1 :             Lsn(0x28),
   12222            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   12223            1 :         )];
   12224            1 :         let delta2 = vec![
   12225            1 :             (
   12226            1 :                 get_key(1),
   12227            1 :                 Lsn(0x30),
   12228            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   12229            1 :             ),
   12230            1 :             (
   12231            1 :                 get_key(1),
   12232            1 :                 Lsn(0x38),
   12233            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   12234            1 :             ),
   12235              :         ];
   12236            1 :         let delta3 = vec![
   12237            1 :             (
   12238            1 :                 get_key(8),
   12239            1 :                 Lsn(0x48),
   12240            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12241            1 :             ),
   12242            1 :             (
   12243            1 :                 get_key(9),
   12244            1 :                 Lsn(0x48),
   12245            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12246            1 :             ),
   12247              :         ];
   12248              : 
   12249            1 :         let tline = tenant
   12250            1 :             .create_test_timeline_with_layers(
   12251            1 :                 TIMELINE_ID,
   12252            1 :                 Lsn(0x10),
   12253            1 :                 DEFAULT_PG_VERSION,
   12254            1 :                 &ctx,
   12255            1 :                 vec![], // in-memory layers
   12256            1 :                 vec![
   12257            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12258            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12259            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12260            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12261            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12262            1 :                 ], // delta layers
   12263            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12264            1 :                 Lsn(0x50),
   12265            1 :             )
   12266            1 :             .await?;
   12267              :         {
   12268            1 :             tline
   12269            1 :                 .applied_gc_cutoff_lsn
   12270            1 :                 .lock_for_write()
   12271            1 :                 .store_and_unlock(Lsn(0x30))
   12272            1 :                 .wait()
   12273            1 :                 .await;
   12274              :             // Update GC info
   12275            1 :             let mut guard = tline.gc_info.write().unwrap();
   12276            1 :             *guard = GcInfo {
   12277            1 :                 retain_lsns: vec![
   12278            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12279            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12280            1 :                 ],
   12281            1 :                 cutoffs: GcCutoffs {
   12282            1 :                     time: Some(Lsn(0x30)),
   12283            1 :                     space: Lsn(0x30),
   12284            1 :                 },
   12285            1 :                 leases: Default::default(),
   12286            1 :                 within_ancestor_pitr: false,
   12287            1 :             };
   12288              :         }
   12289              : 
   12290            1 :         let expected_result = [
   12291            1 :             Bytes::from_static(b"value 0@0x10"),
   12292            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12293            1 :             Bytes::from_static(b"value 2@0x10"),
   12294            1 :             Bytes::from_static(b"value 3@0x10"),
   12295            1 :             Bytes::from_static(b"value 4@0x10"),
   12296            1 :             Bytes::from_static(b"value 5@0x10"),
   12297            1 :             Bytes::from_static(b"value 6@0x10"),
   12298            1 :             Bytes::from_static(b"value 7@0x10"),
   12299            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12300            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12301            1 :         ];
   12302              : 
   12303            1 :         let expected_result_at_gc_horizon = [
   12304            1 :             Bytes::from_static(b"value 0@0x10"),
   12305            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12306            1 :             Bytes::from_static(b"value 2@0x10"),
   12307            1 :             Bytes::from_static(b"value 3@0x10"),
   12308            1 :             Bytes::from_static(b"value 4@0x10"),
   12309            1 :             Bytes::from_static(b"value 5@0x10"),
   12310            1 :             Bytes::from_static(b"value 6@0x10"),
   12311            1 :             Bytes::from_static(b"value 7@0x10"),
   12312            1 :             Bytes::from_static(b"value 8@0x10"),
   12313            1 :             Bytes::from_static(b"value 9@0x10"),
   12314            1 :         ];
   12315              : 
   12316            1 :         let expected_result_at_lsn_20 = [
   12317            1 :             Bytes::from_static(b"value 0@0x10"),
   12318            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12319            1 :             Bytes::from_static(b"value 2@0x10"),
   12320            1 :             Bytes::from_static(b"value 3@0x10"),
   12321            1 :             Bytes::from_static(b"value 4@0x10"),
   12322            1 :             Bytes::from_static(b"value 5@0x10"),
   12323            1 :             Bytes::from_static(b"value 6@0x10"),
   12324            1 :             Bytes::from_static(b"value 7@0x10"),
   12325            1 :             Bytes::from_static(b"value 8@0x10"),
   12326            1 :             Bytes::from_static(b"value 9@0x10"),
   12327            1 :         ];
   12328              : 
   12329            1 :         let expected_result_at_lsn_10 = [
   12330            1 :             Bytes::from_static(b"value 0@0x10"),
   12331            1 :             Bytes::from_static(b"value 1@0x10"),
   12332            1 :             Bytes::from_static(b"value 2@0x10"),
   12333            1 :             Bytes::from_static(b"value 3@0x10"),
   12334            1 :             Bytes::from_static(b"value 4@0x10"),
   12335            1 :             Bytes::from_static(b"value 5@0x10"),
   12336            1 :             Bytes::from_static(b"value 6@0x10"),
   12337            1 :             Bytes::from_static(b"value 7@0x10"),
   12338            1 :             Bytes::from_static(b"value 8@0x10"),
   12339            1 :             Bytes::from_static(b"value 9@0x10"),
   12340            1 :         ];
   12341              : 
   12342            5 :         let verify_result = || async {
   12343            5 :             let gc_horizon = {
   12344            5 :                 let gc_info = tline.gc_info.read().unwrap();
   12345            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   12346              :             };
   12347           55 :             for idx in 0..10 {
   12348           50 :                 assert_eq!(
   12349           50 :                     tline
   12350           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12351           50 :                         .await
   12352           50 :                         .unwrap(),
   12353           50 :                     &expected_result[idx]
   12354              :                 );
   12355           50 :                 assert_eq!(
   12356           50 :                     tline
   12357           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12358           50 :                         .await
   12359           50 :                         .unwrap(),
   12360           50 :                     &expected_result_at_gc_horizon[idx]
   12361              :                 );
   12362           50 :                 assert_eq!(
   12363           50 :                     tline
   12364           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12365           50 :                         .await
   12366           50 :                         .unwrap(),
   12367           50 :                     &expected_result_at_lsn_20[idx]
   12368              :                 );
   12369           50 :                 assert_eq!(
   12370           50 :                     tline
   12371           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12372           50 :                         .await
   12373           50 :                         .unwrap(),
   12374           50 :                     &expected_result_at_lsn_10[idx]
   12375              :                 );
   12376              :             }
   12377           10 :         };
   12378              : 
   12379            1 :         verify_result().await;
   12380              : 
   12381            1 :         let cancel = CancellationToken::new();
   12382              : 
   12383            1 :         tline
   12384            1 :             .compact_with_gc(
   12385            1 :                 &cancel,
   12386            1 :                 CompactOptions {
   12387            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12388            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12389            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   12390            1 :                 },
   12391            1 :                 &ctx,
   12392            1 :             )
   12393            1 :             .await
   12394            1 :             .unwrap();
   12395            1 :         verify_result().await;
   12396              : 
   12397            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12398            1 :         check_layer_map_key_eq(
   12399            1 :             all_layers,
   12400            1 :             vec![
   12401              :                 // The original image layer, not compacted
   12402            1 :                 PersistentLayerKey {
   12403            1 :                     key_range: get_key(0)..get_key(10),
   12404            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12405            1 :                     is_delta: false,
   12406            1 :                 },
   12407              :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12408              :                 // the layer 0x28-0x30 into one.
   12409            1 :                 PersistentLayerKey {
   12410            1 :                     key_range: get_key(1)..get_key(2),
   12411            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12412            1 :                     is_delta: true,
   12413            1 :                 },
   12414              :                 // Above the upper bound and untouched
   12415            1 :                 PersistentLayerKey {
   12416            1 :                     key_range: get_key(1)..get_key(2),
   12417            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12418            1 :                     is_delta: true,
   12419            1 :                 },
   12420              :                 // This layer is untouched
   12421            1 :                 PersistentLayerKey {
   12422            1 :                     key_range: get_key(8)..get_key(10),
   12423            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12424            1 :                     is_delta: true,
   12425            1 :                 },
   12426              :             ],
   12427              :         );
   12428              : 
   12429            1 :         tline
   12430            1 :             .compact_with_gc(
   12431            1 :                 &cancel,
   12432            1 :                 CompactOptions {
   12433            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12434            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12435            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   12436            1 :                 },
   12437            1 :                 &ctx,
   12438            1 :             )
   12439            1 :             .await
   12440            1 :             .unwrap();
   12441            1 :         verify_result().await;
   12442              : 
   12443            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12444            1 :         check_layer_map_key_eq(
   12445            1 :             all_layers,
   12446            1 :             vec![
   12447              :                 // The original image layer, not compacted
   12448            1 :                 PersistentLayerKey {
   12449            1 :                     key_range: get_key(0)..get_key(10),
   12450            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12451            1 :                     is_delta: false,
   12452            1 :                 },
   12453              :                 // Not in the compaction key range, uncompacted
   12454            1 :                 PersistentLayerKey {
   12455            1 :                     key_range: get_key(1)..get_key(2),
   12456            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12457            1 :                     is_delta: true,
   12458            1 :                 },
   12459              :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12460            1 :                 PersistentLayerKey {
   12461            1 :                     key_range: get_key(1)..get_key(2),
   12462            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12463            1 :                     is_delta: true,
   12464            1 :                 },
   12465              :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12466              :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12467              :                 // becomes 0x50.
   12468            1 :                 PersistentLayerKey {
   12469            1 :                     key_range: get_key(8)..get_key(10),
   12470            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12471            1 :                     is_delta: true,
   12472            1 :                 },
   12473              :             ],
   12474              :         );
   12475              : 
   12476              :         // compact again
   12477            1 :         tline
   12478            1 :             .compact_with_gc(
   12479            1 :                 &cancel,
   12480            1 :                 CompactOptions {
   12481            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12482            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12483            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   12484            1 :                 },
   12485            1 :                 &ctx,
   12486            1 :             )
   12487            1 :             .await
   12488            1 :             .unwrap();
   12489            1 :         verify_result().await;
   12490              : 
   12491            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12492            1 :         check_layer_map_key_eq(
   12493            1 :             all_layers,
   12494            1 :             vec![
   12495              :                 // The original image layer, not compacted
   12496            1 :                 PersistentLayerKey {
   12497            1 :                     key_range: get_key(0)..get_key(10),
   12498            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12499            1 :                     is_delta: false,
   12500            1 :                 },
   12501              :                 // The range gets compacted
   12502            1 :                 PersistentLayerKey {
   12503            1 :                     key_range: get_key(1)..get_key(2),
   12504            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12505            1 :                     is_delta: true,
   12506            1 :                 },
   12507              :                 // Not touched during this iteration of compaction
   12508            1 :                 PersistentLayerKey {
   12509            1 :                     key_range: get_key(8)..get_key(10),
   12510            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12511            1 :                     is_delta: true,
   12512            1 :                 },
   12513              :             ],
   12514              :         );
   12515              : 
   12516              :         // final full compaction
   12517            1 :         tline
   12518            1 :             .compact_with_gc(
   12519            1 :                 &cancel,
   12520            1 :                 CompactOptions::default_for_gc_compaction_unit_tests(),
   12521            1 :                 &ctx,
   12522            1 :             )
   12523            1 :             .await
   12524            1 :             .unwrap();
   12525            1 :         verify_result().await;
   12526              : 
   12527            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12528            1 :         check_layer_map_key_eq(
   12529            1 :             all_layers,
   12530            1 :             vec![
   12531              :                 // The compacted image layer (full key range)
   12532            1 :                 PersistentLayerKey {
   12533            1 :                     key_range: Key::MIN..Key::MAX,
   12534            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12535            1 :                     is_delta: false,
   12536            1 :                 },
   12537              :                 // All other data in the delta layer
   12538            1 :                 PersistentLayerKey {
   12539            1 :                     key_range: get_key(1)..get_key(10),
   12540            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12541            1 :                     is_delta: true,
   12542            1 :                 },
   12543              :             ],
   12544              :         );
   12545              : 
   12546            2 :         Ok(())
   12547            1 :     }
   12548              : 
   12549              :     #[cfg(feature = "testing")]
   12550              :     #[tokio::test]
   12551            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12552            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12553            1 :         let (tenant, ctx) = harness.load().await;
   12554              : 
   12555           13 :         fn get_key(id: u32) -> Key {
   12556              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12557           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12558           13 :             key.field6 = id;
   12559           13 :             key
   12560           13 :         }
   12561              : 
   12562            1 :         let img_layer = (0..10)
   12563           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12564            1 :             .collect_vec();
   12565              : 
   12566            1 :         let delta1 = vec![
   12567            1 :             (
   12568            1 :                 get_key(1),
   12569            1 :                 Lsn(0x20),
   12570            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12571            1 :             ),
   12572            1 :             (
   12573            1 :                 get_key(1),
   12574            1 :                 Lsn(0x24),
   12575            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12576            1 :             ),
   12577            1 :             (
   12578            1 :                 get_key(1),
   12579            1 :                 Lsn(0x28),
   12580            1 :                 // This record will fail to redo
   12581            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12582            1 :             ),
   12583              :         ];
   12584              : 
   12585            1 :         let tline = tenant
   12586            1 :             .create_test_timeline_with_layers(
   12587            1 :                 TIMELINE_ID,
   12588            1 :                 Lsn(0x10),
   12589            1 :                 DEFAULT_PG_VERSION,
   12590            1 :                 &ctx,
   12591            1 :                 vec![], // in-memory layers
   12592            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12593            1 :                     Lsn(0x20)..Lsn(0x30),
   12594            1 :                     delta1,
   12595            1 :                 )], // delta layers
   12596            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12597            1 :                 Lsn(0x50),
   12598            1 :             )
   12599            1 :             .await?;
   12600              :         {
   12601            1 :             tline
   12602            1 :                 .applied_gc_cutoff_lsn
   12603            1 :                 .lock_for_write()
   12604            1 :                 .store_and_unlock(Lsn(0x30))
   12605            1 :                 .wait()
   12606            1 :                 .await;
   12607              :             // Update GC info
   12608            1 :             let mut guard = tline.gc_info.write().unwrap();
   12609            1 :             *guard = GcInfo {
   12610            1 :                 retain_lsns: vec![],
   12611            1 :                 cutoffs: GcCutoffs {
   12612            1 :                     time: Some(Lsn(0x30)),
   12613            1 :                     space: Lsn(0x30),
   12614            1 :                 },
   12615            1 :                 leases: Default::default(),
   12616            1 :                 within_ancestor_pitr: false,
   12617            1 :             };
   12618              :         }
   12619              : 
   12620            1 :         let cancel = CancellationToken::new();
   12621              : 
   12622              :         // Compaction will fail, but should not fire any critical error.
   12623              :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12624              :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12625              :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12626            1 :         let res = tline
   12627            1 :             .compact_with_gc(
   12628            1 :                 &cancel,
   12629            1 :                 CompactOptions {
   12630            1 :                     compact_key_range: None,
   12631            1 :                     compact_lsn_range: None,
   12632            1 :                     ..CompactOptions::default_for_gc_compaction_unit_tests()
   12633            1 :                 },
   12634            1 :                 &ctx,
   12635            1 :             )
   12636            1 :             .await;
   12637            1 :         assert!(res.is_err());
   12638              : 
   12639            2 :         Ok(())
   12640            1 :     }
   12641              : 
   12642              :     #[cfg(feature = "testing")]
   12643              :     #[tokio::test]
   12644            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12645              :         use pageserver_api::models::TimelineVisibilityState;
   12646              : 
   12647              :         use crate::tenant::size::gather_inputs;
   12648              : 
   12649            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12650            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12651            1 :             pitr_interval: Some(Duration::ZERO),
   12652            1 :             ..Default::default()
   12653            1 :         };
   12654            1 :         let harness = TenantHarness::create_custom(
   12655            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12656            1 :             tenant_conf,
   12657            1 :             TenantId::generate(),
   12658            1 :             ShardIdentity::unsharded(),
   12659            1 :             Generation::new(0xdeadbeef),
   12660            1 :         )
   12661            1 :         .await?;
   12662            1 :         let (tenant, ctx) = harness.load().await;
   12663            1 :         let main_tline = tenant
   12664            1 :             .create_test_timeline_with_layers(
   12665            1 :                 TIMELINE_ID,
   12666            1 :                 Lsn(0x10),
   12667            1 :                 DEFAULT_PG_VERSION,
   12668            1 :                 &ctx,
   12669            1 :                 vec![],
   12670            1 :                 vec![],
   12671            1 :                 vec![],
   12672            1 :                 Lsn(0x100),
   12673            1 :             )
   12674            1 :             .await?;
   12675              : 
   12676            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12677            1 :         tenant
   12678            1 :             .branch_timeline_test_with_layers(
   12679            1 :                 &main_tline,
   12680            1 :                 snapshot1,
   12681            1 :                 Some(Lsn(0x20)),
   12682            1 :                 &ctx,
   12683            1 :                 vec![],
   12684            1 :                 vec![],
   12685            1 :                 Lsn(0x50),
   12686            1 :             )
   12687            1 :             .await?;
   12688            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12689            1 :         tenant
   12690            1 :             .branch_timeline_test_with_layers(
   12691            1 :                 &main_tline,
   12692            1 :                 snapshot2,
   12693            1 :                 Some(Lsn(0x30)),
   12694            1 :                 &ctx,
   12695            1 :                 vec![],
   12696            1 :                 vec![],
   12697            1 :                 Lsn(0x50),
   12698            1 :             )
   12699            1 :             .await?;
   12700            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12701            1 :         tenant
   12702            1 :             .branch_timeline_test_with_layers(
   12703            1 :                 &main_tline,
   12704            1 :                 snapshot3,
   12705            1 :                 Some(Lsn(0x40)),
   12706            1 :                 &ctx,
   12707            1 :                 vec![],
   12708            1 :                 vec![],
   12709            1 :                 Lsn(0x50),
   12710            1 :             )
   12711            1 :             .await?;
   12712            1 :         let limit = Arc::new(Semaphore::new(1));
   12713            1 :         let max_retention_period = None;
   12714            1 :         let mut logical_size_cache = HashMap::new();
   12715            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12716            1 :         let cancel = CancellationToken::new();
   12717              : 
   12718            1 :         let inputs = gather_inputs(
   12719            1 :             &tenant,
   12720            1 :             &limit,
   12721            1 :             max_retention_period,
   12722            1 :             &mut logical_size_cache,
   12723            1 :             cause,
   12724            1 :             &cancel,
   12725            1 :             &ctx,
   12726              :         )
   12727            1 :         .instrument(info_span!(
   12728              :             "gather_inputs",
   12729              :             tenant_id = "unknown",
   12730              :             shard_id = "unknown",
   12731              :         ))
   12732            1 :         .await?;
   12733              :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12734              :         use LsnKind::*;
   12735              :         use tenant_size_model::Segment;
   12736            1 :         let ModelInputs { mut segments, .. } = inputs;
   12737           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12738            6 :         for segment in segments.iter_mut() {
   12739            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12740            6 :             segment.segment.size = None; // We don't care about the size for the test
   12741            6 :         }
   12742            1 :         assert_eq!(
   12743              :             segments,
   12744              :             [
   12745              :                 SegmentMeta {
   12746              :                     segment: Segment {
   12747              :                         parent: None,
   12748              :                         lsn: 0x10,
   12749              :                         size: None,
   12750              :                         needed: false,
   12751              :                     },
   12752              :                     timeline_id: TIMELINE_ID,
   12753              :                     kind: BranchStart,
   12754              :                 },
   12755              :                 SegmentMeta {
   12756              :                     segment: Segment {
   12757              :                         parent: None,
   12758              :                         lsn: 0x20,
   12759              :                         size: None,
   12760              :                         needed: false,
   12761              :                     },
   12762              :                     timeline_id: TIMELINE_ID,
   12763              :                     kind: BranchPoint,
   12764              :                 },
   12765              :                 SegmentMeta {
   12766              :                     segment: Segment {
   12767              :                         parent: None,
   12768              :                         lsn: 0x30,
   12769              :                         size: None,
   12770              :                         needed: false,
   12771              :                     },
   12772              :                     timeline_id: TIMELINE_ID,
   12773              :                     kind: BranchPoint,
   12774              :                 },
   12775              :                 SegmentMeta {
   12776              :                     segment: Segment {
   12777              :                         parent: None,
   12778              :                         lsn: 0x40,
   12779              :                         size: None,
   12780              :                         needed: false,
   12781              :                     },
   12782              :                     timeline_id: TIMELINE_ID,
   12783              :                     kind: BranchPoint,
   12784              :                 },
   12785              :                 SegmentMeta {
   12786              :                     segment: Segment {
   12787              :                         parent: None,
   12788              :                         lsn: 0x100,
   12789              :                         size: None,
   12790              :                         needed: false,
   12791              :                     },
   12792              :                     timeline_id: TIMELINE_ID,
   12793              :                     kind: GcCutOff,
   12794              :                 }, // we need to retain everything above the last branch point
   12795              :                 SegmentMeta {
   12796              :                     segment: Segment {
   12797              :                         parent: None,
   12798              :                         lsn: 0x100,
   12799              :                         size: None,
   12800              :                         needed: true,
   12801              :                     },
   12802              :                     timeline_id: TIMELINE_ID,
   12803              :                     kind: BranchEnd,
   12804              :                 },
   12805              :             ]
   12806              :         );
   12807              : 
   12808            1 :         main_tline
   12809            1 :             .remote_client
   12810            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12811            1 :                 TimelineVisibilityState::Invisible,
   12812            0 :             )?;
   12813            1 :         main_tline.remote_client.wait_completion().await?;
   12814            1 :         let inputs = gather_inputs(
   12815            1 :             &tenant,
   12816            1 :             &limit,
   12817            1 :             max_retention_period,
   12818            1 :             &mut logical_size_cache,
   12819            1 :             cause,
   12820            1 :             &cancel,
   12821            1 :             &ctx,
   12822              :         )
   12823            1 :         .instrument(info_span!(
   12824              :             "gather_inputs",
   12825              :             tenant_id = "unknown",
   12826              :             shard_id = "unknown",
   12827              :         ))
   12828            1 :         .await?;
   12829            1 :         let ModelInputs { mut segments, .. } = inputs;
   12830           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12831            5 :         for segment in segments.iter_mut() {
   12832            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12833            5 :             segment.segment.size = None; // We don't care about the size for the test
   12834            5 :         }
   12835            1 :         assert_eq!(
   12836              :             segments,
   12837              :             [
   12838              :                 SegmentMeta {
   12839              :                     segment: Segment {
   12840              :                         parent: None,
   12841              :                         lsn: 0x10,
   12842              :                         size: None,
   12843              :                         needed: false,
   12844              :                     },
   12845              :                     timeline_id: TIMELINE_ID,
   12846              :                     kind: BranchStart,
   12847              :                 },
   12848              :                 SegmentMeta {
   12849              :                     segment: Segment {
   12850              :                         parent: None,
   12851              :                         lsn: 0x20,
   12852              :                         size: None,
   12853              :                         needed: false,
   12854              :                     },
   12855              :                     timeline_id: TIMELINE_ID,
   12856              :                     kind: BranchPoint,
   12857              :                 },
   12858              :                 SegmentMeta {
   12859              :                     segment: Segment {
   12860              :                         parent: None,
   12861              :                         lsn: 0x30,
   12862              :                         size: None,
   12863              :                         needed: false,
   12864              :                     },
   12865              :                     timeline_id: TIMELINE_ID,
   12866              :                     kind: BranchPoint,
   12867              :                 },
   12868              :                 SegmentMeta {
   12869              :                     segment: Segment {
   12870              :                         parent: None,
   12871              :                         lsn: 0x40,
   12872              :                         size: None,
   12873              :                         needed: false,
   12874              :                     },
   12875              :                     timeline_id: TIMELINE_ID,
   12876              :                     kind: BranchPoint,
   12877              :                 },
   12878              :                 SegmentMeta {
   12879              :                     segment: Segment {
   12880              :                         parent: None,
   12881              :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12882              :                         size: None,
   12883              :                         needed: true,
   12884              :                     },
   12885              :                     timeline_id: TIMELINE_ID,
   12886              :                     kind: BranchEnd,
   12887              :                 },
   12888              :             ]
   12889              :         );
   12890              : 
   12891            2 :         Ok(())
   12892            1 :     }
   12893              : 
   12894              :     #[tokio::test]
   12895            1 :     async fn test_get_force_image_creation_lsn() -> anyhow::Result<()> {
   12896            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12897            1 :             pitr_interval: Some(Duration::from_secs(7 * 3600)),
   12898            1 :             image_layer_force_creation_period: Some(Duration::from_secs(3600)),
   12899            1 :             ..Default::default()
   12900            1 :         };
   12901              : 
   12902            1 :         let tenant_id = TenantId::generate();
   12903              : 
   12904            1 :         let harness = TenantHarness::create_custom(
   12905            1 :             "test_get_force_image_creation_lsn",
   12906            1 :             tenant_conf,
   12907            1 :             tenant_id,
   12908            1 :             ShardIdentity::unsharded(),
   12909            1 :             Generation::new(1),
   12910            1 :         )
   12911            1 :         .await?;
   12912            1 :         let (tenant, ctx) = harness.load().await;
   12913            1 :         let timeline = tenant
   12914            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   12915            1 :             .await?;
   12916            1 :         timeline.gc_info.write().unwrap().cutoffs.time = Some(Lsn(100));
   12917              :         {
   12918            1 :             let writer = timeline.writer().await;
   12919            1 :             writer.finish_write(Lsn(5000));
   12920              :         }
   12921              : 
   12922            1 :         let image_creation_lsn = timeline.get_force_image_creation_lsn().unwrap();
   12923            1 :         assert_eq!(image_creation_lsn, Lsn(4300));
   12924            2 :         Ok(())
   12925            1 :     }
   12926              : }
        

Generated by: LCOV version 2.1-beta