LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 15f04989d2faf4ce76cecb56042184aca56ebae6.info Lines: 77.7 % 8440 6560
Test Date: 2025-07-14 11:50:36 Functions: 63.0 % 487 307

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use std::collections::hash_map::Entry;
      16              : use std::collections::{BTreeMap, HashMap, HashSet};
      17              : use std::fmt::{Debug, Display};
      18              : use std::fs::File;
      19              : use std::future::Future;
      20              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
      21              : use std::sync::{Arc, Mutex, Weak};
      22              : use std::time::{Duration, Instant, SystemTime};
      23              : use std::{fmt, fs};
      24              : 
      25              : use anyhow::{Context, bail};
      26              : use arc_swap::ArcSwap;
      27              : use camino::{Utf8Path, Utf8PathBuf};
      28              : use chrono::NaiveDateTime;
      29              : use enumset::EnumSet;
      30              : use futures::StreamExt;
      31              : use futures::stream::FuturesUnordered;
      32              : use itertools::Itertools as _;
      33              : use once_cell::sync::Lazy;
      34              : pub use pageserver_api::models::TenantState;
      35              : use pageserver_api::models::{self, RelSizeMigration};
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use postgres_ffi::PgMajorVersion;
      42              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      43              : use remote_timeline_client::index::GcCompactionState;
      44              : use remote_timeline_client::manifest::{
      45              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      46              : };
      47              : use remote_timeline_client::{
      48              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      49              :     download_tenant_manifest,
      50              : };
      51              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      52              : use storage_broker::BrokerClientChannel;
      53              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      54              : use timeline::import_pgdata::ImportingTimeline;
      55              : use timeline::layer_manager::LayerManagerLockHolder;
      56              : use timeline::offload::{OffloadError, offload_timeline};
      57              : use timeline::{
      58              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      59              : };
      60              : use tokio::io::BufReader;
      61              : use tokio::sync::{Notify, Semaphore, watch};
      62              : use tokio::task::JoinSet;
      63              : use tokio_util::sync::CancellationToken;
      64              : use tracing::*;
      65              : use upload_queue::NotInitialized;
      66              : use utils::circuit_breaker::CircuitBreaker;
      67              : use utils::crashsafe::path_with_suffix_extension;
      68              : use utils::sync::gate::{Gate, GateGuard};
      69              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      70              : use utils::try_rcu::ArcSwapExt;
      71              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      72              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      73              : 
      74              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
      75              : use self::metadata::TimelineMetadata;
      76              : use self::mgr::{GetActiveTenantError, GetTenantError};
      77              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      78              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      79              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      80              : use self::timeline::{
      81              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      82              : };
      83              : use crate::basebackup_cache::BasebackupCache;
      84              : use crate::config::PageServerConf;
      85              : use crate::context;
      86              : use crate::context::RequestContextBuilder;
      87              : use crate::context::{DownloadBehavior, RequestContext};
      88              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      89              : use crate::feature_resolver::{FeatureResolver, TenantFeatureResolver};
      90              : use crate::l0_flush::L0FlushGlobalState;
      91              : use crate::metrics::{
      92              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      93              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_OFFLOADED_TIMELINES,
      94              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC, TIMELINE_STATE_METRIC,
      95              :     remove_tenant_metrics,
      96              : };
      97              : use crate::task_mgr::TaskKind;
      98              : use crate::tenant::config::LocationMode;
      99              : use crate::tenant::gc_result::GcResult;
     100              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     101              : use crate::tenant::remote_timeline_client::{
     102              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
     103              : };
     104              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
     105              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     106              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     107              : use crate::virtual_file::VirtualFile;
     108              : use crate::walingest::WalLagCooldown;
     109              : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
     110              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     111              : 
     112            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     113              : use utils::crashsafe;
     114              : use utils::generation::Generation;
     115              : use utils::id::TimelineId;
     116              : use utils::lsn::{Lsn, RecordLsn};
     117              : 
     118              : pub mod blob_io;
     119              : pub mod block_io;
     120              : pub mod vectored_blob_io;
     121              : 
     122              : pub mod disk_btree;
     123              : pub(crate) mod ephemeral_file;
     124              : pub mod layer_map;
     125              : 
     126              : pub mod metadata;
     127              : pub mod remote_timeline_client;
     128              : pub mod storage_layer;
     129              : 
     130              : pub mod checks;
     131              : pub mod config;
     132              : pub mod mgr;
     133              : pub mod secondary;
     134              : pub mod tasks;
     135              : pub mod upload_queue;
     136              : 
     137              : pub(crate) mod timeline;
     138              : 
     139              : pub mod size;
     140              : 
     141              : mod gc_block;
     142              : mod gc_result;
     143              : pub(crate) mod throttle;
     144              : 
     145              : #[cfg(test)]
     146              : pub mod debug;
     147              : 
     148              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     149              : 
     150              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     151              : // re-export for use in walreceiver
     152              : pub use crate::tenant::timeline::WalReceiverInfo;
     153              : 
     154              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     155              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     156              : 
     157              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     158              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     159              : 
     160              : /// References to shared objects that are passed into each tenant, such
     161              : /// as the shared remote storage client and process initialization state.
     162              : #[derive(Clone)]
     163              : pub struct TenantSharedResources {
     164              :     pub broker_client: storage_broker::BrokerClientChannel,
     165              :     pub remote_storage: GenericRemoteStorage,
     166              :     pub deletion_queue_client: DeletionQueueClient,
     167              :     pub l0_flush_global_state: L0FlushGlobalState,
     168              :     pub basebackup_cache: Arc<BasebackupCache>,
     169              :     pub feature_resolver: FeatureResolver,
     170              : }
     171              : 
     172              : /// A [`TenantShard`] is really an _attached_ tenant.  The configuration
     173              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     174              : /// in this struct.
     175              : #[derive(Clone)]
     176              : pub(super) struct AttachedTenantConf {
     177              :     tenant_conf: pageserver_api::models::TenantConfig,
     178              :     location: AttachedLocationConfig,
     179              :     /// The deadline before which we are blocked from GC so that
     180              :     /// leases have a chance to be renewed.
     181              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     182              : }
     183              : 
     184              : impl AttachedTenantConf {
     185          119 :     fn new(
     186          119 :         conf: &'static PageServerConf,
     187          119 :         tenant_conf: pageserver_api::models::TenantConfig,
     188          119 :         location: AttachedLocationConfig,
     189          119 :     ) -> Self {
     190              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     191              :         //
     192              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     193              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     194              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     195          119 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     196          119 :             Some(
     197          119 :                 tokio::time::Instant::now()
     198          119 :                     + TenantShard::get_lsn_lease_length_impl(conf, &tenant_conf),
     199          119 :             )
     200              :         } else {
     201              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     202              :             // because we don't do GC in these modes.
     203            0 :             None
     204              :         };
     205              : 
     206          119 :         Self {
     207          119 :             tenant_conf,
     208          119 :             location,
     209          119 :             lsn_lease_deadline,
     210          119 :         }
     211          119 :     }
     212              : 
     213          119 :     fn try_from(
     214          119 :         conf: &'static PageServerConf,
     215          119 :         location_conf: LocationConf,
     216          119 :     ) -> anyhow::Result<Self> {
     217          119 :         match &location_conf.mode {
     218          119 :             LocationMode::Attached(attach_conf) => {
     219          119 :                 Ok(Self::new(conf, location_conf.tenant_conf, *attach_conf))
     220              :             }
     221              :             LocationMode::Secondary(_) => {
     222            0 :                 anyhow::bail!(
     223            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     224              :                 )
     225              :             }
     226              :         }
     227          119 :     }
     228              : 
     229          380 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     230          380 :         self.lsn_lease_deadline
     231          380 :             .map(|d| tokio::time::Instant::now() < d)
     232          380 :             .unwrap_or(false)
     233          380 :     }
     234              : }
     235              : struct TimelinePreload {
     236              :     timeline_id: TimelineId,
     237              :     client: RemoteTimelineClient,
     238              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     239              :     previous_heatmap: Option<PreviousHeatmap>,
     240              : }
     241              : 
     242              : pub(crate) struct TenantPreload {
     243              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     244              :     tenant_manifest: Option<TenantManifest>,
     245              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     246              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     247              : }
     248              : 
     249              : /// When we spawn a tenant, there is a special mode for tenant creation that
     250              : /// avoids trying to read anything from remote storage.
     251              : pub(crate) enum SpawnMode {
     252              :     /// Activate as soon as possible
     253              :     Eager,
     254              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     255              :     Lazy,
     256              : }
     257              : 
     258              : ///
     259              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     260              : ///
     261              : pub struct TenantShard {
     262              :     // Global pageserver config parameters
     263              :     pub conf: &'static PageServerConf,
     264              : 
     265              :     /// The value creation timestamp, used to measure activation delay, see:
     266              :     /// <https://github.com/neondatabase/neon/issues/4025>
     267              :     constructed_at: Instant,
     268              : 
     269              :     state: watch::Sender<TenantState>,
     270              : 
     271              :     // Overridden tenant-specific config parameters.
     272              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     273              :     // about parameters that are not set.
     274              :     // This is necessary to allow global config updates.
     275              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     276              : 
     277              :     tenant_shard_id: TenantShardId,
     278              : 
     279              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     280              :     shard_identity: ShardIdentity,
     281              : 
     282              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     283              :     /// Does not change over the lifetime of the [`TenantShard`] object.
     284              :     ///
     285              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     286              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     287              :     generation: Generation,
     288              : 
     289              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     290              : 
     291              :     /// During timeline creation, we first insert the TimelineId to the
     292              :     /// creating map, then `timelines`, then remove it from the creating map.
     293              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     294              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     295              : 
     296              :     /// Possibly offloaded and archived timelines
     297              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     298              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     299              : 
     300              :     /// Tracks the timelines that are currently importing into this tenant shard.
     301              :     ///
     302              :     /// Note that importing timelines are also present in [`Self::timelines_creating`].
     303              :     /// Keep this in mind when ordering lock acquisition.
     304              :     ///
     305              :     /// Lifetime:
     306              :     /// * An imported timeline is created while scanning the bucket on tenant attach
     307              :     ///   if the index part contains an `import_pgdata` entry and said field marks the import
     308              :     ///   as in progress.
     309              :     /// * Imported timelines are removed when the storage controller calls the post timeline
     310              :     ///   import activation endpoint.
     311              :     timelines_importing: std::sync::Mutex<HashMap<TimelineId, Arc<ImportingTimeline>>>,
     312              : 
     313              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     314              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     315              :     ///
     316              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     317              :     ///
     318              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     319              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     320              :     /// `maybe_upload_tenant_manifest`.
     321              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     322              : 
     323              :     // This mutex prevents creation of new timelines during GC.
     324              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     325              :     // `timelines` mutex during all GC iteration
     326              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     327              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     328              :     // timeout...
     329              :     gc_cs: tokio::sync::Mutex<()>,
     330              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     331              : 
     332              :     /// Provides access to timeline data sitting in the remote storage.
     333              :     pub(crate) remote_storage: GenericRemoteStorage,
     334              : 
     335              :     /// Access to global deletion queue for when this tenant wants to schedule a deletion.
     336              :     deletion_queue_client: DeletionQueueClient,
     337              : 
     338              :     /// A channel to send async requests to prepare a basebackup for the basebackup cache.
     339              :     basebackup_cache: Arc<BasebackupCache>,
     340              : 
     341              :     /// Cached logical sizes updated updated on each [`TenantShard::gather_size_inputs`].
     342              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     343              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     344              : 
     345              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     346              : 
     347              :     /// Track repeated failures to compact, so that we can back off.
     348              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     349              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     350              : 
     351              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     352              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     353              : 
     354              :     /// Scheduled gc-compaction tasks.
     355              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     356              : 
     357              :     /// If the tenant is in Activating state, notify this to encourage it
     358              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     359              :     /// background warmup.
     360              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     361              : 
     362              :     /// Time it took for the tenant to activate. Zero if not active yet.
     363              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     364              : 
     365              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     366              :     // Timelines' cancellation token.
     367              :     pub(crate) cancel: CancellationToken,
     368              : 
     369              :     // Users of the TenantShard such as the page service must take this Gate to avoid
     370              :     // trying to use a TenantShard which is shutting down.
     371              :     pub(crate) gate: Gate,
     372              : 
     373              :     /// Throttle applied at the top of [`Timeline::get`].
     374              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] instance share the same [`throttle::Throttle`] instance.
     375              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     376              : 
     377              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     378              : 
     379              :     /// An ongoing timeline detach concurrency limiter.
     380              :     ///
     381              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     382              :     /// to have two running at the same time. A different one can be started if an earlier one
     383              :     /// has failed for whatever reason.
     384              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     385              : 
     386              :     /// `index_part.json` based gc blocking reason tracking.
     387              :     ///
     388              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     389              :     /// proceeding.
     390              :     pub(crate) gc_block: gc_block::GcBlock,
     391              : 
     392              :     l0_flush_global_state: L0FlushGlobalState,
     393              : 
     394              :     pub(crate) feature_resolver: Arc<TenantFeatureResolver>,
     395              : }
     396              : impl std::fmt::Debug for TenantShard {
     397            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     398            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     399            0 :     }
     400              : }
     401              : 
     402              : pub(crate) enum WalRedoManager {
     403              :     Prod(WalredoManagerId, PostgresRedoManager),
     404              :     #[cfg(test)]
     405              :     Test(harness::TestRedoManager),
     406              : }
     407              : 
     408              : #[derive(thiserror::Error, Debug)]
     409              : #[error("pageserver is shutting down")]
     410              : pub(crate) struct GlobalShutDown;
     411              : 
     412              : impl WalRedoManager {
     413            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     414            0 :         let id = WalredoManagerId::next();
     415            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     416            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     417            0 :         match &mut *guard {
     418            0 :             Some(map) => {
     419            0 :                 map.insert(id, Arc::downgrade(&arc));
     420            0 :                 Ok(arc)
     421              :             }
     422            0 :             None => Err(GlobalShutDown),
     423              :         }
     424            0 :     }
     425              : }
     426              : 
     427              : impl Drop for WalRedoManager {
     428            5 :     fn drop(&mut self) {
     429            5 :         match self {
     430            0 :             Self::Prod(id, _) => {
     431            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     432            0 :                 if let Some(map) = &mut *guard {
     433            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     434            0 :                 }
     435              :             }
     436              :             #[cfg(test)]
     437            5 :             Self::Test(_) => {
     438            5 :                 // Not applicable to test redo manager
     439            5 :             }
     440              :         }
     441            5 :     }
     442              : }
     443              : 
     444              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     445              : /// the walredo processes outside of the regular order.
     446              : ///
     447              : /// This is necessary to work around a systemd bug where it freezes if there are
     448              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     449              : #[allow(clippy::type_complexity)]
     450              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     451              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     452            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     453              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     454              : pub(crate) struct WalredoManagerId(u64);
     455              : impl WalredoManagerId {
     456            0 :     pub fn next() -> Self {
     457              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     458            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     459            0 :         if id == 0 {
     460            0 :             panic!(
     461            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     462              :             );
     463            0 :         }
     464            0 :         Self(id)
     465            0 :     }
     466              : }
     467              : 
     468              : #[cfg(test)]
     469              : impl From<harness::TestRedoManager> for WalRedoManager {
     470          119 :     fn from(mgr: harness::TestRedoManager) -> Self {
     471          119 :         Self::Test(mgr)
     472          119 :     }
     473              : }
     474              : 
     475              : impl WalRedoManager {
     476            3 :     pub(crate) async fn shutdown(&self) -> bool {
     477            3 :         match self {
     478            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     479              :             #[cfg(test)]
     480              :             Self::Test(_) => {
     481              :                 // Not applicable to test redo manager
     482            3 :                 true
     483              :             }
     484              :         }
     485            3 :     }
     486              : 
     487            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     488            0 :         match self {
     489            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     490              :             #[cfg(test)]
     491            0 :             Self::Test(_) => {
     492            0 :                 // Not applicable to test redo manager
     493            0 :             }
     494              :         }
     495            0 :     }
     496              : 
     497              :     /// # Cancel-Safety
     498              :     ///
     499              :     /// This method is cancellation-safe.
     500        26774 :     pub async fn request_redo(
     501        26774 :         &self,
     502        26774 :         key: pageserver_api::key::Key,
     503        26774 :         lsn: Lsn,
     504        26774 :         base_img: Option<(Lsn, bytes::Bytes)>,
     505        26774 :         records: Vec<(Lsn, wal_decoder::models::record::NeonWalRecord)>,
     506        26774 :         pg_version: PgMajorVersion,
     507        26774 :         redo_attempt_type: RedoAttemptType,
     508        26774 :     ) -> Result<bytes::Bytes, walredo::Error> {
     509        26774 :         match self {
     510            0 :             Self::Prod(_, mgr) => {
     511            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     512            0 :                     .await
     513              :             }
     514              :             #[cfg(test)]
     515        26774 :             Self::Test(mgr) => {
     516        26774 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     517        26774 :                     .await
     518              :             }
     519              :         }
     520        26774 :     }
     521              : 
     522            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     523            0 :         match self {
     524            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     525              :             #[cfg(test)]
     526            0 :             WalRedoManager::Test(_) => None,
     527              :         }
     528            0 :     }
     529              : }
     530              : 
     531              : /// A very lightweight memory representation of an offloaded timeline.
     532              : ///
     533              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     534              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     535              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     536              : /// more offloaded timelines than we can manage ones that aren't.
     537              : pub struct OffloadedTimeline {
     538              :     pub tenant_shard_id: TenantShardId,
     539              :     pub timeline_id: TimelineId,
     540              :     pub ancestor_timeline_id: Option<TimelineId>,
     541              :     /// Whether to retain the branch lsn at the ancestor or not
     542              :     pub ancestor_retain_lsn: Option<Lsn>,
     543              : 
     544              :     /// When the timeline was archived.
     545              :     ///
     546              :     /// Present for future flattening deliberations.
     547              :     pub archived_at: NaiveDateTime,
     548              : 
     549              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     550              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     551              :     pub delete_progress: TimelineDeleteProgress,
     552              : 
     553              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     554              :     pub deleted_from_ancestor: AtomicBool,
     555              : 
     556              :     _metrics_guard: OffloadedTimelineMetricsGuard,
     557              : }
     558              : 
     559              : /// Increases the offloaded timeline count metric when created, and decreases when dropped.
     560              : struct OffloadedTimelineMetricsGuard;
     561              : 
     562              : impl OffloadedTimelineMetricsGuard {
     563            1 :     fn new() -> Self {
     564            1 :         TIMELINE_STATE_METRIC
     565            1 :             .with_label_values(&["offloaded"])
     566            1 :             .inc();
     567            1 :         Self
     568            1 :     }
     569              : }
     570              : 
     571              : impl Drop for OffloadedTimelineMetricsGuard {
     572            1 :     fn drop(&mut self) {
     573            1 :         TIMELINE_STATE_METRIC
     574            1 :             .with_label_values(&["offloaded"])
     575            1 :             .dec();
     576            1 :     }
     577              : }
     578              : 
     579              : impl OffloadedTimeline {
     580              :     /// Obtains an offloaded timeline from a given timeline object.
     581              :     ///
     582              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     583              :     /// the timeline is not in a stopped state.
     584              :     /// Panics if the timeline is not archived.
     585            1 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     586            1 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     587            1 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     588            1 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     589            1 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     590            1 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     591            1 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     592            1 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     593              :             } else {
     594            0 :                 (None, None)
     595              :             };
     596            1 :         let archived_at = timeline
     597            1 :             .remote_client
     598            1 :             .archived_at_stopped_queue()?
     599            1 :             .expect("must be called on an archived timeline");
     600            1 :         Ok(Self {
     601            1 :             tenant_shard_id: timeline.tenant_shard_id,
     602            1 :             timeline_id: timeline.timeline_id,
     603            1 :             ancestor_timeline_id,
     604            1 :             ancestor_retain_lsn,
     605            1 :             archived_at,
     606            1 : 
     607            1 :             delete_progress: timeline.delete_progress.clone(),
     608            1 :             deleted_from_ancestor: AtomicBool::new(false),
     609            1 : 
     610            1 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     611            1 :         })
     612            1 :     }
     613            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     614              :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     615              :         // by the `initialize_gc_info` function.
     616              :         let OffloadedTimelineManifest {
     617            0 :             timeline_id,
     618            0 :             ancestor_timeline_id,
     619            0 :             ancestor_retain_lsn,
     620            0 :             archived_at,
     621            0 :         } = *manifest;
     622            0 :         Self {
     623            0 :             tenant_shard_id,
     624            0 :             timeline_id,
     625            0 :             ancestor_timeline_id,
     626            0 :             ancestor_retain_lsn,
     627            0 :             archived_at,
     628            0 :             delete_progress: TimelineDeleteProgress::default(),
     629            0 :             deleted_from_ancestor: AtomicBool::new(false),
     630            0 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     631            0 :         }
     632            0 :     }
     633            1 :     fn manifest(&self) -> OffloadedTimelineManifest {
     634              :         let Self {
     635            1 :             timeline_id,
     636            1 :             ancestor_timeline_id,
     637            1 :             ancestor_retain_lsn,
     638            1 :             archived_at,
     639              :             ..
     640            1 :         } = self;
     641            1 :         OffloadedTimelineManifest {
     642            1 :             timeline_id: *timeline_id,
     643            1 :             ancestor_timeline_id: *ancestor_timeline_id,
     644            1 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     645            1 :             archived_at: *archived_at,
     646            1 :         }
     647            1 :     }
     648              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     649            0 :     fn delete_from_ancestor_with_timelines(
     650            0 :         &self,
     651            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     652            0 :     ) {
     653            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     654            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     655              :         {
     656            0 :             if let Some((_, ancestor_timeline)) = timelines
     657            0 :                 .iter()
     658            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     659              :             {
     660            0 :                 let removal_happened = ancestor_timeline
     661            0 :                     .gc_info
     662            0 :                     .write()
     663            0 :                     .unwrap()
     664            0 :                     .remove_child_offloaded(self.timeline_id);
     665            0 :                 if !removal_happened {
     666            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     667            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     668            0 :                 }
     669            0 :             }
     670            0 :         }
     671            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     672            0 :     }
     673              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     674              :     ///
     675              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     676            1 :     fn defuse_for_tenant_drop(&self) {
     677            1 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     678            1 :     }
     679              : }
     680              : 
     681              : impl fmt::Debug for OffloadedTimeline {
     682            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     683            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     684            0 :     }
     685              : }
     686              : 
     687              : impl Drop for OffloadedTimeline {
     688            1 :     fn drop(&mut self) {
     689            1 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     690            0 :             tracing::warn!(
     691            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     692              :                 self.timeline_id
     693              :             );
     694            1 :         }
     695            1 :     }
     696              : }
     697              : 
     698              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     699              : pub enum MaybeOffloaded {
     700              :     Yes,
     701              :     No,
     702              : }
     703              : 
     704              : #[derive(Clone, Debug)]
     705              : pub enum TimelineOrOffloaded {
     706              :     Timeline(Arc<Timeline>),
     707              :     Offloaded(Arc<OffloadedTimeline>),
     708              :     Importing(Arc<ImportingTimeline>),
     709              : }
     710              : 
     711              : impl TimelineOrOffloaded {
     712            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     713            0 :         match self {
     714            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     715            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     716              :             }
     717            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     718            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     719              :             }
     720            0 :             TimelineOrOffloaded::Importing(importing) => {
     721            0 :                 TimelineOrOffloadedArcRef::Importing(importing)
     722              :             }
     723              :         }
     724            0 :     }
     725            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     726            0 :         self.arc_ref().tenant_shard_id()
     727            0 :     }
     728            0 :     pub fn timeline_id(&self) -> TimelineId {
     729            0 :         self.arc_ref().timeline_id()
     730            0 :     }
     731            1 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     732            1 :         match self {
     733            1 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     734            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     735            0 :             TimelineOrOffloaded::Importing(importing) => &importing.delete_progress,
     736              :         }
     737            1 :     }
     738            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     739            0 :         match self {
     740            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     741            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     742            0 :             TimelineOrOffloaded::Importing(importing) => {
     743            0 :                 Some(importing.timeline.remote_client.clone())
     744              :             }
     745              :         }
     746            0 :     }
     747              : }
     748              : 
     749              : pub enum TimelineOrOffloadedArcRef<'a> {
     750              :     Timeline(&'a Arc<Timeline>),
     751              :     Offloaded(&'a Arc<OffloadedTimeline>),
     752              :     Importing(&'a Arc<ImportingTimeline>),
     753              : }
     754              : 
     755              : impl TimelineOrOffloadedArcRef<'_> {
     756            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     757            0 :         match self {
     758            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     759            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     760            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.tenant_shard_id,
     761              :         }
     762            0 :     }
     763            0 :     pub fn timeline_id(&self) -> TimelineId {
     764            0 :         match self {
     765            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     766            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     767            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.timeline_id,
     768              :         }
     769            0 :     }
     770              : }
     771              : 
     772              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     773            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     774            0 :         Self::Timeline(timeline)
     775            0 :     }
     776              : }
     777              : 
     778              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     779            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     780            0 :         Self::Offloaded(timeline)
     781            0 :     }
     782              : }
     783              : 
     784              : impl<'a> From<&'a Arc<ImportingTimeline>> for TimelineOrOffloadedArcRef<'a> {
     785            0 :     fn from(timeline: &'a Arc<ImportingTimeline>) -> Self {
     786            0 :         Self::Importing(timeline)
     787            0 :     }
     788              : }
     789              : 
     790              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     791              : pub enum GetTimelineError {
     792              :     #[error("Timeline is shutting down")]
     793              :     ShuttingDown,
     794              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     795              :     NotActive {
     796              :         tenant_id: TenantShardId,
     797              :         timeline_id: TimelineId,
     798              :         state: TimelineState,
     799              :     },
     800              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     801              :     NotFound {
     802              :         tenant_id: TenantShardId,
     803              :         timeline_id: TimelineId,
     804              :     },
     805              : }
     806              : 
     807              : #[derive(Debug, thiserror::Error)]
     808              : pub enum LoadLocalTimelineError {
     809              :     #[error("FailedToLoad")]
     810              :     Load(#[source] anyhow::Error),
     811              :     #[error("FailedToResumeDeletion")]
     812              :     ResumeDeletion(#[source] anyhow::Error),
     813              : }
     814              : 
     815              : #[derive(thiserror::Error)]
     816              : pub enum DeleteTimelineError {
     817              :     #[error("NotFound")]
     818              :     NotFound,
     819              : 
     820              :     #[error("HasChildren")]
     821              :     HasChildren(Vec<TimelineId>),
     822              : 
     823              :     #[error("Timeline deletion is already in progress")]
     824              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     825              : 
     826              :     #[error("Cancelled")]
     827              :     Cancelled,
     828              : 
     829              :     #[error(transparent)]
     830              :     Other(#[from] anyhow::Error),
     831              : }
     832              : 
     833              : impl Debug for DeleteTimelineError {
     834            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     835            0 :         match self {
     836            0 :             Self::NotFound => write!(f, "NotFound"),
     837            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     838            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     839            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     840            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     841              :         }
     842            0 :     }
     843              : }
     844              : 
     845              : #[derive(thiserror::Error)]
     846              : pub enum TimelineArchivalError {
     847              :     #[error("NotFound")]
     848              :     NotFound,
     849              : 
     850              :     #[error("Timeout")]
     851              :     Timeout,
     852              : 
     853              :     #[error("Cancelled")]
     854              :     Cancelled,
     855              : 
     856              :     #[error("ancestor is archived: {}", .0)]
     857              :     HasArchivedParent(TimelineId),
     858              : 
     859              :     #[error("HasUnarchivedChildren")]
     860              :     HasUnarchivedChildren(Vec<TimelineId>),
     861              : 
     862              :     #[error("Timeline archival is already in progress")]
     863              :     AlreadyInProgress,
     864              : 
     865              :     #[error(transparent)]
     866              :     Other(anyhow::Error),
     867              : }
     868              : 
     869              : #[derive(thiserror::Error, Debug)]
     870              : pub(crate) enum TenantManifestError {
     871              :     #[error("Remote storage error: {0}")]
     872              :     RemoteStorage(anyhow::Error),
     873              : 
     874              :     #[error("Cancelled")]
     875              :     Cancelled,
     876              : }
     877              : 
     878              : impl From<TenantManifestError> for TimelineArchivalError {
     879            0 :     fn from(e: TenantManifestError) -> Self {
     880            0 :         match e {
     881            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     882            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     883              :         }
     884            0 :     }
     885              : }
     886              : 
     887              : impl Debug for TimelineArchivalError {
     888            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     889            0 :         match self {
     890            0 :             Self::NotFound => write!(f, "NotFound"),
     891            0 :             Self::Timeout => write!(f, "Timeout"),
     892            0 :             Self::Cancelled => write!(f, "Cancelled"),
     893            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     894            0 :             Self::HasUnarchivedChildren(c) => {
     895            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     896              :             }
     897            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     898            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     899              :         }
     900            0 :     }
     901              : }
     902              : 
     903              : pub enum SetStoppingError {
     904              :     AlreadyStopping(completion::Barrier),
     905              :     Broken,
     906              : }
     907              : 
     908              : impl Debug for SetStoppingError {
     909            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     910            0 :         match self {
     911            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     912            0 :             Self::Broken => write!(f, "Broken"),
     913              :         }
     914            0 :     }
     915              : }
     916              : 
     917              : #[derive(thiserror::Error, Debug)]
     918              : pub(crate) enum FinalizeTimelineImportError {
     919              :     #[error("Import task not done yet")]
     920              :     ImportTaskStillRunning,
     921              :     #[error("Shutting down")]
     922              :     ShuttingDown,
     923              : }
     924              : 
     925              : /// Arguments to [`TenantShard::create_timeline`].
     926              : ///
     927              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     928              : /// is `None`, the result of the timeline create call is not deterministic.
     929              : ///
     930              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     931              : #[derive(Debug)]
     932              : pub(crate) enum CreateTimelineParams {
     933              :     Bootstrap(CreateTimelineParamsBootstrap),
     934              :     Branch(CreateTimelineParamsBranch),
     935              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     936              : }
     937              : 
     938              : #[derive(Debug)]
     939              : pub(crate) struct CreateTimelineParamsBootstrap {
     940              :     pub(crate) new_timeline_id: TimelineId,
     941              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     942              :     pub(crate) pg_version: PgMajorVersion,
     943              : }
     944              : 
     945              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     946              : #[derive(Debug)]
     947              : pub(crate) struct CreateTimelineParamsBranch {
     948              :     pub(crate) new_timeline_id: TimelineId,
     949              :     pub(crate) ancestor_timeline_id: TimelineId,
     950              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     951              : }
     952              : 
     953              : #[derive(Debug)]
     954              : pub(crate) struct CreateTimelineParamsImportPgdata {
     955              :     pub(crate) new_timeline_id: TimelineId,
     956              :     pub(crate) location: import_pgdata::index_part_format::Location,
     957              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     958              : }
     959              : 
     960              : /// What is used to determine idempotency of a [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::start_creating_timeline`].
     961              : ///
     962              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     963              : ///
     964              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     965              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     966              : ///
     967              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     968              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     969              : ///
     970              : /// Notes:
     971              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     972              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     973              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     974              : ///
     975              : #[derive(Debug, Clone, PartialEq, Eq)]
     976              : pub(crate) enum CreateTimelineIdempotency {
     977              :     /// NB: special treatment, see comment in [`Self`].
     978              :     FailWithConflict,
     979              :     Bootstrap {
     980              :         pg_version: PgMajorVersion,
     981              :     },
     982              :     /// NB: branches always have the same `pg_version` as their ancestor.
     983              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     984              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     985              :     /// determining the child branch pg_version.
     986              :     Branch {
     987              :         ancestor_timeline_id: TimelineId,
     988              :         ancestor_start_lsn: Lsn,
     989              :     },
     990              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     991              : }
     992              : 
     993              : #[derive(Debug, Clone, PartialEq, Eq)]
     994              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     995              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     996              : }
     997              : 
     998              : /// What is returned by [`TenantShard::start_creating_timeline`].
     999              : #[must_use]
    1000              : enum StartCreatingTimelineResult {
    1001              :     CreateGuard(TimelineCreateGuard),
    1002              :     Idempotent(Arc<Timeline>),
    1003              : }
    1004              : 
    1005              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1006              : enum TimelineInitAndSyncResult {
    1007              :     ReadyToActivate,
    1008              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
    1009              : }
    1010              : 
    1011              : #[must_use]
    1012              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
    1013              :     timeline: Arc<Timeline>,
    1014              :     import_pgdata: import_pgdata::index_part_format::Root,
    1015              :     guard: TimelineCreateGuard,
    1016              : }
    1017              : 
    1018              : /// What is returned by [`TenantShard::create_timeline`].
    1019              : enum CreateTimelineResult {
    1020              :     Created(Arc<Timeline>),
    1021              :     Idempotent(Arc<Timeline>),
    1022              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
    1023              :     /// we return this result, nor will this concrete object ever be added there.
    1024              :     /// Cf method comment on [`TenantShard::create_timeline_import_pgdata`].
    1025              :     ImportSpawned(Arc<Timeline>),
    1026              : }
    1027              : 
    1028              : impl CreateTimelineResult {
    1029            0 :     fn discriminant(&self) -> &'static str {
    1030            0 :         match self {
    1031            0 :             Self::Created(_) => "Created",
    1032            0 :             Self::Idempotent(_) => "Idempotent",
    1033            0 :             Self::ImportSpawned(_) => "ImportSpawned",
    1034              :         }
    1035            0 :     }
    1036            0 :     fn timeline(&self) -> &Arc<Timeline> {
    1037            0 :         match self {
    1038            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1039              :         }
    1040            0 :     }
    1041              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
    1042              :     #[cfg(test)]
    1043          118 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
    1044          118 :         match self {
    1045          118 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1046              :         }
    1047          118 :     }
    1048              : }
    1049              : 
    1050              : #[derive(thiserror::Error, Debug)]
    1051              : pub enum CreateTimelineError {
    1052              :     #[error("creation of timeline with the given ID is in progress")]
    1053              :     AlreadyCreating,
    1054              :     #[error("timeline already exists with different parameters")]
    1055              :     Conflict,
    1056              :     #[error(transparent)]
    1057              :     AncestorLsn(anyhow::Error),
    1058              :     #[error("ancestor timeline is not active")]
    1059              :     AncestorNotActive,
    1060              :     #[error("ancestor timeline is archived")]
    1061              :     AncestorArchived,
    1062              :     #[error("tenant shutting down")]
    1063              :     ShuttingDown,
    1064              :     #[error(transparent)]
    1065              :     Other(#[from] anyhow::Error),
    1066              : }
    1067              : 
    1068              : #[derive(thiserror::Error, Debug)]
    1069              : pub enum InitdbError {
    1070              :     #[error("Operation was cancelled")]
    1071              :     Cancelled,
    1072              :     #[error(transparent)]
    1073              :     Other(anyhow::Error),
    1074              :     #[error(transparent)]
    1075              :     Inner(postgres_initdb::Error),
    1076              : }
    1077              : 
    1078              : enum CreateTimelineCause {
    1079              :     Load,
    1080              :     Delete,
    1081              : }
    1082              : 
    1083              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1084              : enum LoadTimelineCause {
    1085              :     Attach,
    1086              :     Unoffload,
    1087              : }
    1088              : 
    1089              : #[derive(thiserror::Error, Debug)]
    1090              : pub(crate) enum GcError {
    1091              :     // The tenant is shutting down
    1092              :     #[error("tenant shutting down")]
    1093              :     TenantCancelled,
    1094              : 
    1095              :     // The tenant is shutting down
    1096              :     #[error("timeline shutting down")]
    1097              :     TimelineCancelled,
    1098              : 
    1099              :     // The tenant is in a state inelegible to run GC
    1100              :     #[error("not active")]
    1101              :     NotActive,
    1102              : 
    1103              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1104              :     #[error("not active")]
    1105              :     BadLsn { why: String },
    1106              : 
    1107              :     // A remote storage error while scheduling updates after compaction
    1108              :     #[error(transparent)]
    1109              :     Remote(anyhow::Error),
    1110              : 
    1111              :     // An error reading while calculating GC cutoffs
    1112              :     #[error(transparent)]
    1113              :     GcCutoffs(PageReconstructError),
    1114              : 
    1115              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1116              :     #[error("timeline not found")]
    1117              :     TimelineNotFound,
    1118              : }
    1119              : 
    1120              : impl From<PageReconstructError> for GcError {
    1121            0 :     fn from(value: PageReconstructError) -> Self {
    1122            0 :         match value {
    1123            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1124            0 :             other => Self::GcCutoffs(other),
    1125              :         }
    1126            0 :     }
    1127              : }
    1128              : 
    1129              : impl From<NotInitialized> for GcError {
    1130            0 :     fn from(value: NotInitialized) -> Self {
    1131            0 :         match value {
    1132            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1133            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1134              :         }
    1135            0 :     }
    1136              : }
    1137              : 
    1138              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1139            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1140            0 :         GcError::TimelineCancelled
    1141            0 :     }
    1142              : }
    1143              : 
    1144              : #[derive(thiserror::Error, Debug)]
    1145              : pub(crate) enum LoadConfigError {
    1146              :     #[error("TOML deserialization error: '{0}'")]
    1147              :     DeserializeToml(#[from] toml_edit::de::Error),
    1148              : 
    1149              :     #[error("Config not found at {0}")]
    1150              :     NotFound(Utf8PathBuf),
    1151              : }
    1152              : 
    1153              : impl TenantShard {
    1154              :     /// Yet another helper for timeline initialization.
    1155              :     ///
    1156              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1157              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1158              :     /// - Downloads remote index file and adds remote files to the layer map
    1159              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1160              :     ///
    1161              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1162              :     /// it is marked as Active.
    1163              :     #[allow(clippy::too_many_arguments)]
    1164            3 :     async fn timeline_init_and_sync(
    1165            3 :         self: &Arc<Self>,
    1166            3 :         timeline_id: TimelineId,
    1167            3 :         resources: TimelineResources,
    1168            3 :         index_part: IndexPart,
    1169            3 :         metadata: TimelineMetadata,
    1170            3 :         previous_heatmap: Option<PreviousHeatmap>,
    1171            3 :         ancestor: Option<Arc<Timeline>>,
    1172            3 :         cause: LoadTimelineCause,
    1173            3 :         ctx: &RequestContext,
    1174            3 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1175            3 :         let tenant_id = self.tenant_shard_id;
    1176              : 
    1177            3 :         let import_pgdata = index_part.import_pgdata.clone();
    1178            3 :         let idempotency = match &import_pgdata {
    1179            0 :             Some(import_pgdata) => {
    1180            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1181            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1182            0 :                 })
    1183              :             }
    1184              :             None => {
    1185            3 :                 if metadata.ancestor_timeline().is_none() {
    1186            2 :                     CreateTimelineIdempotency::Bootstrap {
    1187            2 :                         pg_version: metadata.pg_version(),
    1188            2 :                     }
    1189              :                 } else {
    1190            1 :                     CreateTimelineIdempotency::Branch {
    1191            1 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1192            1 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1193            1 :                     }
    1194              :                 }
    1195              :             }
    1196              :         };
    1197              : 
    1198            3 :         let (timeline, _timeline_ctx) = self.create_timeline_struct(
    1199            3 :             timeline_id,
    1200            3 :             &metadata,
    1201            3 :             previous_heatmap,
    1202            3 :             ancestor.clone(),
    1203            3 :             resources,
    1204            3 :             CreateTimelineCause::Load,
    1205            3 :             idempotency.clone(),
    1206            3 :             index_part.gc_compaction.clone(),
    1207            3 :             index_part.rel_size_migration.clone(),
    1208            3 :             ctx,
    1209            3 :         )?;
    1210            3 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1211              : 
    1212            3 :         if !disk_consistent_lsn.is_valid() {
    1213              :             // As opposed to normal timelines which get initialised with a disk consitent LSN
    1214              :             // via initdb, imported timelines start from 0. If the import task stops before
    1215              :             // it advances disk consitent LSN, allow it to resume.
    1216            0 :             let in_progress_import = import_pgdata
    1217            0 :                 .as_ref()
    1218            0 :                 .map(|import| !import.is_done())
    1219            0 :                 .unwrap_or(false);
    1220            0 :             if !in_progress_import {
    1221            0 :                 anyhow::bail!("Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn");
    1222            0 :             }
    1223            3 :         }
    1224              : 
    1225            3 :         assert_eq!(
    1226              :             disk_consistent_lsn,
    1227            3 :             metadata.disk_consistent_lsn(),
    1228            0 :             "these are used interchangeably"
    1229              :         );
    1230              : 
    1231            3 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1232              : 
    1233            3 :         timeline
    1234            3 :             .load_layer_map(disk_consistent_lsn, index_part)
    1235            3 :             .await
    1236            3 :             .with_context(|| {
    1237            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1238            0 :             })?;
    1239              : 
    1240              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1241              :         // to the archival operation. To allow warming this timeline up, generate
    1242              :         // a previous heatmap which contains all visible layers in the layer map.
    1243              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1244              :         // for the timeline.
    1245            3 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1246            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1247            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1248            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1249              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1250              :                 // If the current branch point greater than the previous one use the the heatmap
    1251              :                 // we just generated - it should include more layers.
    1252            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1253            0 :                     tline
    1254            0 :                         .previous_heatmap
    1255            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1256            0 :                 } else {
    1257            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1258              :                 }
    1259              : 
    1260            0 :                 match tline.ancestor_timeline() {
    1261            0 :                     Some(ancestor) => {
    1262            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1263              :                             // Ancestor timeline is shutting down.
    1264            0 :                             break;
    1265            0 :                         }
    1266              : 
    1267            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1268              :                     }
    1269            0 :                     None => {
    1270            0 :                         tline_ending_at = None;
    1271            0 :                     }
    1272              :                 }
    1273              :             }
    1274            3 :         }
    1275              : 
    1276            0 :         match import_pgdata {
    1277            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1278            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1279            0 :                 if !guard.insert(timeline_id) {
    1280              :                     // We should never try and load the same timeline twice during startup
    1281            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1282            0 :                 }
    1283            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1284            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1285            0 :                     owning_tenant: self.clone(),
    1286            0 :                     timeline_id,
    1287            0 :                     idempotency,
    1288              :                     // The users of this specific return value don't need the timline_path in there.
    1289            0 :                     timeline_path: timeline
    1290            0 :                         .conf
    1291            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1292              :                 };
    1293            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1294            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1295            0 :                         timeline,
    1296            0 :                         import_pgdata,
    1297            0 :                         guard: timeline_create_guard,
    1298            0 :                     },
    1299            0 :                 ))
    1300              :             }
    1301              :             Some(_) | None => {
    1302              :                 {
    1303            3 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1304            3 :                     match timelines_accessor.entry(timeline_id) {
    1305              :                         // We should never try and load the same timeline twice during startup
    1306              :                         Entry::Occupied(_) => {
    1307            0 :                             unreachable!(
    1308              :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1309              :                             );
    1310              :                         }
    1311            3 :                         Entry::Vacant(v) => {
    1312            3 :                             v.insert(Arc::clone(&timeline));
    1313            3 :                             timeline.maybe_spawn_flush_loop();
    1314            3 :                         }
    1315              :                     }
    1316              :                 }
    1317              : 
    1318            3 :                 if disk_consistent_lsn.is_valid() {
    1319              :                     // Sanity check: a timeline should have some content.
    1320              :                     // Exception: importing timelines might not yet have any
    1321            3 :                     anyhow::ensure!(
    1322            3 :                         ancestor.is_some()
    1323            2 :                             || timeline
    1324            2 :                                 .layers
    1325            2 :                                 .read(LayerManagerLockHolder::LoadLayerMap)
    1326            2 :                                 .await
    1327            2 :                                 .layer_map()
    1328            2 :                                 .expect(
    1329            2 :                                     "currently loading, layer manager cannot be shutdown already"
    1330              :                                 )
    1331            2 :                                 .iter_historic_layers()
    1332            2 :                                 .next()
    1333            2 :                                 .is_some(),
    1334            0 :                         "Timeline has no ancestor and no layer files"
    1335              :                     );
    1336            0 :                 }
    1337              : 
    1338            3 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate)
    1339              :             }
    1340              :         }
    1341            3 :     }
    1342              : 
    1343              :     /// Attach a tenant that's available in cloud storage.
    1344              :     ///
    1345              :     /// This returns quickly, after just creating the in-memory object
    1346              :     /// Tenant struct and launching a background task to download
    1347              :     /// the remote index files.  On return, the tenant is most likely still in
    1348              :     /// Attaching state, and it will become Active once the background task
    1349              :     /// finishes. You can use wait_until_active() to wait for the task to
    1350              :     /// complete.
    1351              :     ///
    1352              :     #[allow(clippy::too_many_arguments)]
    1353            0 :     pub(crate) fn spawn(
    1354            0 :         conf: &'static PageServerConf,
    1355            0 :         tenant_shard_id: TenantShardId,
    1356            0 :         resources: TenantSharedResources,
    1357            0 :         attached_conf: AttachedTenantConf,
    1358            0 :         shard_identity: ShardIdentity,
    1359            0 :         init_order: Option<InitializationOrder>,
    1360            0 :         mode: SpawnMode,
    1361            0 :         ctx: &RequestContext,
    1362            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1363            0 :         let wal_redo_manager =
    1364            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1365              : 
    1366              :         let TenantSharedResources {
    1367            0 :             broker_client,
    1368            0 :             remote_storage,
    1369            0 :             deletion_queue_client,
    1370            0 :             l0_flush_global_state,
    1371            0 :             basebackup_cache,
    1372            0 :             feature_resolver,
    1373            0 :         } = resources;
    1374              : 
    1375            0 :         let attach_mode = attached_conf.location.attach_mode;
    1376            0 :         let generation = attached_conf.location.generation;
    1377              : 
    1378            0 :         let tenant = Arc::new(TenantShard::new(
    1379            0 :             TenantState::Attaching,
    1380            0 :             conf,
    1381            0 :             attached_conf,
    1382            0 :             shard_identity,
    1383            0 :             Some(wal_redo_manager),
    1384            0 :             tenant_shard_id,
    1385            0 :             remote_storage.clone(),
    1386            0 :             deletion_queue_client,
    1387            0 :             l0_flush_global_state,
    1388            0 :             basebackup_cache,
    1389            0 :             feature_resolver,
    1390              :         ));
    1391              : 
    1392              :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1393              :         // we shut down while attaching.
    1394            0 :         let attach_gate_guard = tenant
    1395            0 :             .gate
    1396            0 :             .enter()
    1397            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1398              : 
    1399              :         // Do all the hard work in the background
    1400            0 :         let tenant_clone = Arc::clone(&tenant);
    1401            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1402            0 :         task_mgr::spawn(
    1403            0 :             &tokio::runtime::Handle::current(),
    1404            0 :             TaskKind::Attach,
    1405            0 :             tenant_shard_id,
    1406            0 :             None,
    1407            0 :             "attach tenant",
    1408            0 :             async move {
    1409              : 
    1410            0 :                 info!(
    1411              :                     ?attach_mode,
    1412            0 :                     "Attaching tenant"
    1413              :                 );
    1414              : 
    1415            0 :                 let _gate_guard = attach_gate_guard;
    1416              : 
    1417              :                 // Is this tenant being spawned as part of process startup?
    1418            0 :                 let starting_up = init_order.is_some();
    1419            0 :                 scopeguard::defer! {
    1420              :                     if starting_up {
    1421              :                         TENANT.startup_complete.inc();
    1422              :                     }
    1423              :                 }
    1424              : 
    1425            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1426            0 :                     t.state.send_modify(|state| match state {
    1427              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1428              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1429              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1430              :                         // logs don't show this happening in production, remove the Stopping cases.
    1431            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1432            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1433              :                         }
    1434              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1435            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1436            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1437              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1438            0 :                             *state = TenantState::Stopping { progress: None };
    1439              :                         }
    1440              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1441              :                         // Stopping. Retain its progress.
    1442              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1443            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1444            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1445            0 :                             info!("attach cancelled, already Stopping: {err}");
    1446              :                         }
    1447              :                         // Mark the tenant as broken.
    1448              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1449            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1450            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1451              :                         }
    1452              :                         // The attach task owns the tenant state until activated.
    1453            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1454            0 :                     });
    1455            0 :                 }
    1456              : 
    1457              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1458            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1459            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1460            0 :                     return Ok(());
    1461            0 :                 }
    1462              : 
    1463            0 :                 let mut init_order = init_order;
    1464              :                 // take the completion because initial tenant loading will complete when all of
    1465              :                 // these tasks complete.
    1466            0 :                 let _completion = init_order
    1467            0 :                     .as_mut()
    1468            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1469            0 :                 let remote_load_completion = init_order
    1470            0 :                     .as_mut()
    1471            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1472              : 
    1473              :                 enum AttachType<'a> {
    1474              :                     /// We are attaching this tenant lazily in the background.
    1475              :                     Warmup {
    1476              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1477              :                         during_startup: bool
    1478              :                     },
    1479              :                     /// We are attaching this tenant as soon as we can, because for example an
    1480              :                     /// endpoint tried to access it.
    1481              :                     OnDemand,
    1482              :                     /// During normal operations after startup, we are attaching a tenant, and
    1483              :                     /// eager attach was requested.
    1484              :                     Normal,
    1485              :                 }
    1486              : 
    1487            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1488              :                     // Before doing any I/O, wait for at least one of:
    1489              :                     // - A client attempting to access to this tenant (on-demand loading)
    1490              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1491              : 
    1492            0 :                     tokio::select!(
    1493            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1494            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1495            0 :                             tracing::info!("Activating tenant (on-demand)");
    1496            0 :                             AttachType::OnDemand
    1497              :                         },
    1498            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1499            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1500            0 :                             tracing::info!("Activating tenant (warmup)");
    1501            0 :                             AttachType::Warmup {
    1502            0 :                                 _permit,
    1503            0 :                                 during_startup: init_order.is_some()
    1504            0 :                             }
    1505              :                         }
    1506            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1507              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1508              :                             // stayed in Activating for such a long time that shutdown found it in
    1509              :                             // that state.
    1510            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1511              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1512            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1513            0 :                             return Ok(());
    1514              :                         },
    1515              :                     )
    1516              :                 } else {
    1517              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1518              :                     // concurrent_tenant_warmup queue
    1519            0 :                     AttachType::Normal
    1520              :                 };
    1521              : 
    1522            0 :                 let preload = match &mode {
    1523              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1524            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1525            0 :                         let res = tenant_clone
    1526            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1527            0 :                             .await;
    1528            0 :                         match res {
    1529            0 :                             Ok(p) => Some(p),
    1530            0 :                             Err(e) => {
    1531            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1532            0 :                                 return Ok(());
    1533              :                             }
    1534              :                         }
    1535              :                     }
    1536              : 
    1537              :                 };
    1538              : 
    1539              :                 // Remote preload is complete.
    1540            0 :                 drop(remote_load_completion);
    1541              : 
    1542              : 
    1543              :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1544            0 :                 let attach_start = std::time::Instant::now();
    1545            0 :                 let attached = {
    1546            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1547            0 :                     tenant_clone.attach(preload, &ctx).await
    1548              :                 };
    1549            0 :                 let attach_duration = attach_start.elapsed();
    1550            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1551              : 
    1552            0 :                 match attached {
    1553              :                     Ok(()) => {
    1554            0 :                         info!("attach finished, activating");
    1555            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1556              :                     }
    1557            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1558              :                 }
    1559              : 
    1560              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1561              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1562              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1563              :                 //
    1564              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1565              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1566              :                 // then warmup will wait for that before proceeding to the next tenant.
    1567            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1568            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1569            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1570            0 :                     while futs.next().await.is_some() {}
    1571            0 :                     tracing::info!("Warm-up complete");
    1572            0 :                 }
    1573              : 
    1574            0 :                 Ok(())
    1575            0 :             }
    1576            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1577              :         );
    1578            0 :         Ok(tenant)
    1579            0 :     }
    1580              : 
    1581              :     #[instrument(skip_all)]
    1582              :     pub(crate) async fn preload(
    1583              :         self: &Arc<Self>,
    1584              :         remote_storage: &GenericRemoteStorage,
    1585              :         cancel: CancellationToken,
    1586              :     ) -> anyhow::Result<TenantPreload> {
    1587              :         span::debug_assert_current_span_has_tenant_id();
    1588              :         // Get list of remote timelines
    1589              :         // download index files for every tenant timeline
    1590              :         info!("listing remote timelines");
    1591              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1592              :             remote_storage,
    1593              :             self.tenant_shard_id,
    1594              :             cancel.clone(),
    1595              :         )
    1596              :         .await?;
    1597              : 
    1598              :         let tenant_manifest = match download_tenant_manifest(
    1599              :             remote_storage,
    1600              :             &self.tenant_shard_id,
    1601              :             self.generation,
    1602              :             &cancel,
    1603              :         )
    1604              :         .await
    1605              :         {
    1606              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1607              :             Err(DownloadError::NotFound) => None,
    1608              :             Err(err) => return Err(err.into()),
    1609              :         };
    1610              : 
    1611              :         info!(
    1612              :             "found {} timelines ({} offloaded timelines)",
    1613              :             remote_timeline_ids.len(),
    1614              :             tenant_manifest
    1615              :                 .as_ref()
    1616            3 :                 .map(|m| m.offloaded_timelines.len())
    1617              :                 .unwrap_or(0)
    1618              :         );
    1619              : 
    1620              :         for k in other_keys {
    1621              :             warn!("Unexpected non timeline key {k}");
    1622              :         }
    1623              : 
    1624              :         // Avoid downloading IndexPart of offloaded timelines.
    1625              :         let mut offloaded_with_prefix = HashSet::new();
    1626              :         if let Some(tenant_manifest) = &tenant_manifest {
    1627              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1628              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1629              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1630              :                 } else {
    1631              :                     // We'll take care later of timelines in the manifest without a prefix
    1632              :                 }
    1633              :             }
    1634              :         }
    1635              : 
    1636              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1637              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1638              :         // will kick the secondary in any case and cause a download.
    1639              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1640              : 
    1641              :         let timelines = self
    1642              :             .load_timelines_metadata(
    1643              :                 remote_timeline_ids,
    1644              :                 remote_storage,
    1645              :                 maybe_heatmap_at,
    1646              :                 cancel,
    1647              :             )
    1648              :             .await?;
    1649              : 
    1650              :         Ok(TenantPreload {
    1651              :             tenant_manifest,
    1652              :             timelines: timelines
    1653              :                 .into_iter()
    1654            3 :                 .map(|(id, tl)| (id, Some(tl)))
    1655            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1656              :                 .collect(),
    1657              :         })
    1658              :     }
    1659              : 
    1660          119 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1661          119 :         if !self.conf.load_previous_heatmap {
    1662            0 :             return None;
    1663          119 :         }
    1664              : 
    1665          119 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1666          119 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1667            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1668            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1669            0 :                 Err(err) => {
    1670            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1671            0 :                     None
    1672              :                 }
    1673              :             },
    1674          119 :             Err(err) => match err.kind() {
    1675          119 :                 std::io::ErrorKind::NotFound => None,
    1676              :                 _ => {
    1677            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1678            0 :                     None
    1679              :                 }
    1680              :             },
    1681              :         }
    1682          119 :     }
    1683              : 
    1684              :     ///
    1685              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1686              :     ///
    1687              :     /// No background tasks are started as part of this routine.
    1688              :     ///
    1689          119 :     async fn attach(
    1690          119 :         self: &Arc<TenantShard>,
    1691          119 :         preload: Option<TenantPreload>,
    1692          119 :         ctx: &RequestContext,
    1693          119 :     ) -> anyhow::Result<()> {
    1694          119 :         span::debug_assert_current_span_has_tenant_id();
    1695              : 
    1696          119 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1697              : 
    1698          119 :         let Some(preload) = preload else {
    1699            0 :             anyhow::bail!(
    1700            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1701              :             );
    1702              :         };
    1703              : 
    1704          119 :         let mut offloaded_timeline_ids = HashSet::new();
    1705          119 :         let mut offloaded_timelines_list = Vec::new();
    1706          119 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1707            3 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1708            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1709            0 :                 let offloaded_timeline =
    1710            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1711            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1712            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1713            0 :             }
    1714          116 :         }
    1715              :         // Complete deletions for offloaded timeline id's from manifest.
    1716              :         // The manifest will be uploaded later in this function.
    1717          119 :         offloaded_timelines_list
    1718          119 :             .retain(|(offloaded_id, offloaded)| {
    1719              :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1720              :                 // If there is dangling references in another location, they need to be cleaned up.
    1721            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1722            0 :                 if delete {
    1723            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1724            0 :                     offloaded.defuse_for_tenant_drop();
    1725            0 :                 }
    1726            0 :                 !delete
    1727            0 :         });
    1728              : 
    1729          119 :         let mut timelines_to_resume_deletions = vec![];
    1730              : 
    1731          119 :         let mut remote_index_and_client = HashMap::new();
    1732          119 :         let mut timeline_ancestors = HashMap::new();
    1733          119 :         let mut existent_timelines = HashSet::new();
    1734          122 :         for (timeline_id, preload) in preload.timelines {
    1735            3 :             let Some(preload) = preload else { continue };
    1736              :             // This is an invariant of the `preload` function's API
    1737            3 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1738            3 :             let index_part = match preload.index_part {
    1739            3 :                 Ok(i) => {
    1740            3 :                     debug!("remote index part exists for timeline {timeline_id}");
    1741              :                     // We found index_part on the remote, this is the standard case.
    1742            3 :                     existent_timelines.insert(timeline_id);
    1743            3 :                     i
    1744              :                 }
    1745              :                 Err(DownloadError::NotFound) => {
    1746              :                     // There is no index_part on the remote. We only get here
    1747              :                     // if there is some prefix for the timeline in the remote storage.
    1748              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1749              :                     // remnant from a prior incomplete creation or deletion attempt.
    1750              :                     // Delete the local directory as the deciding criterion for a
    1751              :                     // timeline's existence is presence of index_part.
    1752            0 :                     info!(%timeline_id, "index_part not found on remote");
    1753            0 :                     continue;
    1754              :                 }
    1755            0 :                 Err(DownloadError::Fatal(why)) => {
    1756              :                     // If, while loading one remote timeline, we saw an indication that our generation
    1757              :                     // number is likely invalid, then we should not load the whole tenant.
    1758            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1759            0 :                     anyhow::bail!(why.to_string());
    1760              :                 }
    1761            0 :                 Err(e) => {
    1762              :                     // Some (possibly ephemeral) error happened during index_part download.
    1763              :                     // Pretend the timeline exists to not delete the timeline directory,
    1764              :                     // as it might be a temporary issue and we don't want to re-download
    1765              :                     // everything after it resolves.
    1766            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1767              : 
    1768            0 :                     existent_timelines.insert(timeline_id);
    1769            0 :                     continue;
    1770              :                 }
    1771              :             };
    1772            3 :             match index_part {
    1773            3 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1774            3 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1775            3 :                     remote_index_and_client.insert(
    1776            3 :                         timeline_id,
    1777            3 :                         (index_part, preload.client, preload.previous_heatmap),
    1778            3 :                     );
    1779            3 :                 }
    1780            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1781            0 :                     info!(
    1782            0 :                         "timeline {} is deleted, picking to resume deletion",
    1783              :                         timeline_id
    1784              :                     );
    1785            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1786              :                 }
    1787              :             }
    1788              :         }
    1789              : 
    1790          119 :         let mut gc_blocks = HashMap::new();
    1791              : 
    1792              :         // For every timeline, download the metadata file, scan the local directory,
    1793              :         // and build a layer map that contains an entry for each remote and local
    1794              :         // layer file.
    1795          119 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1796          122 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1797            3 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1798            3 :                 .remove(&timeline_id)
    1799            3 :                 .expect("just put it in above");
    1800              : 
    1801            3 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1802              :                 // could just filter these away, but it helps while testing
    1803            0 :                 anyhow::ensure!(
    1804            0 :                     !blocking.reasons.is_empty(),
    1805            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1806              :                 );
    1807            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1808            0 :                 assert!(prev.is_none());
    1809            3 :             }
    1810              : 
    1811              :             // TODO again handle early failure
    1812            3 :             let effect = self
    1813            3 :                 .load_remote_timeline(
    1814            3 :                     timeline_id,
    1815            3 :                     index_part,
    1816            3 :                     remote_metadata,
    1817            3 :                     previous_heatmap,
    1818            3 :                     self.get_timeline_resources_for(remote_client),
    1819            3 :                     LoadTimelineCause::Attach,
    1820            3 :                     ctx,
    1821            3 :                 )
    1822            3 :                 .await
    1823            3 :                 .with_context(|| {
    1824            0 :                     format!(
    1825            0 :                         "failed to load remote timeline {} for tenant {}",
    1826            0 :                         timeline_id, self.tenant_shard_id
    1827              :                     )
    1828            0 :                 })?;
    1829              : 
    1830            3 :             match effect {
    1831            3 :                 TimelineInitAndSyncResult::ReadyToActivate => {
    1832            3 :                     // activation happens later, on Tenant::activate
    1833            3 :                 }
    1834              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1835              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1836            0 :                         timeline,
    1837            0 :                         import_pgdata,
    1838            0 :                         guard,
    1839              :                     },
    1840              :                 ) => {
    1841            0 :                     let timeline_id = timeline.timeline_id;
    1842            0 :                     let import_task_gate = Gate::default();
    1843            0 :                     let import_task_guard = import_task_gate.enter().unwrap();
    1844            0 :                     let import_task_handle =
    1845            0 :                         tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1846            0 :                             timeline.clone(),
    1847            0 :                             import_pgdata,
    1848            0 :                             guard,
    1849            0 :                             import_task_guard,
    1850            0 :                             ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1851              :                         ));
    1852              : 
    1853            0 :                     let prev = self.timelines_importing.lock().unwrap().insert(
    1854            0 :                         timeline_id,
    1855            0 :                         Arc::new(ImportingTimeline {
    1856            0 :                             timeline: timeline.clone(),
    1857            0 :                             import_task_handle,
    1858            0 :                             import_task_gate,
    1859            0 :                             delete_progress: TimelineDeleteProgress::default(),
    1860            0 :                         }),
    1861            0 :                     );
    1862              : 
    1863            0 :                     assert!(prev.is_none());
    1864              :                 }
    1865              :             }
    1866              :         }
    1867              : 
    1868              :         // At this point we've initialized all timelines and are tracking them.
    1869              :         // Now compute the layer visibility for all (not offloaded) timelines.
    1870          119 :         let compute_visiblity_for = {
    1871          119 :             let timelines_accessor = self.timelines.lock().unwrap();
    1872          119 :             let mut timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    1873              : 
    1874          119 :             timelines_offloaded_accessor.extend(offloaded_timelines_list.into_iter());
    1875              : 
    1876              :             // Before activation, populate each Timeline's GcInfo with information about its children
    1877          119 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    1878              : 
    1879          119 :             timelines_accessor.values().cloned().collect::<Vec<_>>()
    1880              :         };
    1881              : 
    1882          122 :         for tl in compute_visiblity_for {
    1883            3 :             tl.update_layer_visibility().await.with_context(|| {
    1884            0 :                 format!(
    1885            0 :                     "failed initial timeline visibility computation {} for tenant {}",
    1886            0 :                     tl.timeline_id, self.tenant_shard_id
    1887              :                 )
    1888            0 :             })?;
    1889              :         }
    1890              : 
    1891              :         // Walk through deleted timelines, resume deletion
    1892          119 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1893            0 :             remote_timeline_client
    1894            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1895            0 :                 .context("init queue stopped")
    1896            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1897              : 
    1898            0 :             DeleteTimelineFlow::resume_deletion(
    1899            0 :                 Arc::clone(self),
    1900            0 :                 timeline_id,
    1901            0 :                 &index_part.metadata,
    1902            0 :                 remote_timeline_client,
    1903            0 :                 ctx,
    1904              :             )
    1905            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1906            0 :             .await
    1907            0 :             .context("resume_deletion")
    1908            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1909              :         }
    1910              : 
    1911              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1912              :         //
    1913              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1914              :         // offloaded timelines, which are included in the manifest.
    1915              :         {
    1916          119 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1917          119 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1918          119 :             *guard = preload.tenant_manifest;
    1919              :         }
    1920          119 :         self.maybe_upload_tenant_manifest().await?;
    1921              : 
    1922              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1923              :         // IndexPart is the source of truth.
    1924          119 :         self.clean_up_timelines(&existent_timelines)?;
    1925              : 
    1926          119 :         self.gc_block.set_scanned(gc_blocks);
    1927              : 
    1928          119 :         fail::fail_point!("attach-before-activate", |_| {
    1929            0 :             anyhow::bail!("attach-before-activate");
    1930            0 :         });
    1931          119 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1932              : 
    1933          119 :         info!("Done");
    1934              : 
    1935          119 :         Ok(())
    1936          119 :     }
    1937              : 
    1938              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1939              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1940              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1941          119 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1942          119 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1943              : 
    1944          119 :         let entries = match timelines_dir.read_dir_utf8() {
    1945          119 :             Ok(d) => d,
    1946            0 :             Err(e) => {
    1947            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1948            0 :                     return Ok(());
    1949              :                 } else {
    1950            0 :                     return Err(e).context("list timelines directory for tenant");
    1951              :                 }
    1952              :             }
    1953              :         };
    1954              : 
    1955          123 :         for entry in entries {
    1956            4 :             let entry = entry.context("read timeline dir entry")?;
    1957            4 :             let entry_path = entry.path();
    1958              : 
    1959            4 :             let purge = if crate::is_temporary(entry_path) {
    1960            0 :                 true
    1961              :             } else {
    1962            4 :                 match TimelineId::try_from(entry_path.file_name()) {
    1963            4 :                     Ok(i) => {
    1964              :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1965            4 :                         !existent_timelines.contains(&i)
    1966              :                     }
    1967            0 :                     Err(e) => {
    1968            0 :                         tracing::warn!(
    1969            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1970              :                         );
    1971              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1972            0 :                         false
    1973              :                     }
    1974              :                 }
    1975              :             };
    1976              : 
    1977            4 :             if purge {
    1978            1 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1979            1 :                 if let Err(e) = match entry.file_type() {
    1980            1 :                     Ok(t) => if t.is_dir() {
    1981            1 :                         std::fs::remove_dir_all(entry_path)
    1982              :                     } else {
    1983            0 :                         std::fs::remove_file(entry_path)
    1984              :                     }
    1985            1 :                     .or_else(fs_ext::ignore_not_found),
    1986            0 :                     Err(e) => Err(e),
    1987              :                 } {
    1988            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1989            1 :                 }
    1990            3 :             }
    1991              :         }
    1992              : 
    1993          119 :         Ok(())
    1994          119 :     }
    1995              : 
    1996              :     /// Get sum of all remote timelines sizes
    1997              :     ///
    1998              :     /// This function relies on the index_part instead of listing the remote storage
    1999            0 :     pub fn remote_size(&self) -> u64 {
    2000            0 :         let mut size = 0;
    2001              : 
    2002            0 :         for timeline in self.list_timelines() {
    2003            0 :             size += timeline.remote_client.get_remote_physical_size();
    2004            0 :         }
    2005              : 
    2006            0 :         size
    2007            0 :     }
    2008              : 
    2009              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    2010              :     #[allow(clippy::too_many_arguments)]
    2011              :     async fn load_remote_timeline(
    2012              :         self: &Arc<Self>,
    2013              :         timeline_id: TimelineId,
    2014              :         index_part: IndexPart,
    2015              :         remote_metadata: TimelineMetadata,
    2016              :         previous_heatmap: Option<PreviousHeatmap>,
    2017              :         resources: TimelineResources,
    2018              :         cause: LoadTimelineCause,
    2019              :         ctx: &RequestContext,
    2020              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    2021              :         span::debug_assert_current_span_has_tenant_id();
    2022              : 
    2023              :         info!("downloading index file for timeline {}", timeline_id);
    2024              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    2025              :             .await
    2026              :             .context("Failed to create new timeline directory")?;
    2027              : 
    2028              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    2029              :             let timelines = self.timelines.lock().unwrap();
    2030              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    2031            0 :                 || {
    2032            0 :                     anyhow::anyhow!(
    2033            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    2034              :                     )
    2035            0 :                 },
    2036              :             )?))
    2037              :         } else {
    2038              :             None
    2039              :         };
    2040              : 
    2041              :         self.timeline_init_and_sync(
    2042              :             timeline_id,
    2043              :             resources,
    2044              :             index_part,
    2045              :             remote_metadata,
    2046              :             previous_heatmap,
    2047              :             ancestor,
    2048              :             cause,
    2049              :             ctx,
    2050              :         )
    2051              :         .await
    2052              :     }
    2053              : 
    2054          119 :     async fn load_timelines_metadata(
    2055          119 :         self: &Arc<TenantShard>,
    2056          119 :         timeline_ids: HashSet<TimelineId>,
    2057          119 :         remote_storage: &GenericRemoteStorage,
    2058          119 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    2059          119 :         cancel: CancellationToken,
    2060          119 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    2061          119 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    2062              : 
    2063          119 :         let mut part_downloads = JoinSet::new();
    2064          122 :         for timeline_id in timeline_ids {
    2065            3 :             let cancel_clone = cancel.clone();
    2066              : 
    2067            3 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    2068            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    2069            0 :                     heatmap: h,
    2070            0 :                     read_at: hs.1,
    2071            0 :                     end_lsn: None,
    2072            0 :                 })
    2073            0 :             });
    2074            3 :             part_downloads.spawn(
    2075            3 :                 self.load_timeline_metadata(
    2076            3 :                     timeline_id,
    2077            3 :                     remote_storage.clone(),
    2078            3 :                     previous_timeline_heatmap,
    2079            3 :                     cancel_clone,
    2080              :                 )
    2081            3 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    2082              :             );
    2083              :         }
    2084              : 
    2085          119 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    2086              : 
    2087              :         loop {
    2088          122 :             tokio::select!(
    2089          122 :                 next = part_downloads.join_next() => {
    2090          122 :                     match next {
    2091            3 :                         Some(result) => {
    2092            3 :                             let preload = result.context("join preload task")?;
    2093            3 :                             timeline_preloads.insert(preload.timeline_id, preload);
    2094              :                         },
    2095              :                         None => {
    2096          119 :                             break;
    2097              :                         }
    2098              :                     }
    2099              :                 },
    2100          122 :                 _ = cancel.cancelled() => {
    2101            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2102              :                 }
    2103              :             )
    2104              :         }
    2105              : 
    2106          119 :         Ok(timeline_preloads)
    2107          119 :     }
    2108              : 
    2109            3 :     fn build_timeline_client(
    2110            3 :         &self,
    2111            3 :         timeline_id: TimelineId,
    2112            3 :         remote_storage: GenericRemoteStorage,
    2113            3 :     ) -> RemoteTimelineClient {
    2114            3 :         RemoteTimelineClient::new(
    2115            3 :             remote_storage.clone(),
    2116            3 :             self.deletion_queue_client.clone(),
    2117            3 :             self.conf,
    2118            3 :             self.tenant_shard_id,
    2119            3 :             timeline_id,
    2120            3 :             self.generation,
    2121            3 :             &self.tenant_conf.load().location,
    2122              :         )
    2123            3 :     }
    2124              : 
    2125            3 :     fn load_timeline_metadata(
    2126            3 :         self: &Arc<TenantShard>,
    2127            3 :         timeline_id: TimelineId,
    2128            3 :         remote_storage: GenericRemoteStorage,
    2129            3 :         previous_heatmap: Option<PreviousHeatmap>,
    2130            3 :         cancel: CancellationToken,
    2131            3 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2132            3 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2133            3 :         async move {
    2134            3 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2135            3 :             debug!("starting index part download");
    2136              : 
    2137            3 :             let index_part = client.download_index_file(&cancel).await;
    2138              : 
    2139            3 :             debug!("finished index part download");
    2140              : 
    2141            3 :             TimelinePreload {
    2142            3 :                 client,
    2143            3 :                 timeline_id,
    2144            3 :                 index_part,
    2145            3 :                 previous_heatmap,
    2146            3 :             }
    2147            3 :         }
    2148            3 :     }
    2149              : 
    2150            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2151            0 :         timeline_id: TimelineId,
    2152            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2153            0 :     ) -> Result<(), TimelineArchivalError> {
    2154            0 :         let children: Vec<TimelineId> = timelines
    2155            0 :             .iter()
    2156            0 :             .filter_map(|(id, entry)| {
    2157            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2158            0 :                     return None;
    2159            0 :                 }
    2160            0 :                 if entry.is_archived() == Some(true) {
    2161            0 :                     return None;
    2162            0 :                 }
    2163            0 :                 Some(*id)
    2164            0 :             })
    2165            0 :             .collect();
    2166              : 
    2167            0 :         if !children.is_empty() {
    2168            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2169            0 :         }
    2170            0 :         Ok(())
    2171            0 :     }
    2172              : 
    2173            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2174            0 :         ancestor_timeline_id: TimelineId,
    2175            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2176            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2177            0 :             '_,
    2178            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2179            0 :         >,
    2180            0 :     ) -> Result<(), TimelineArchivalError> {
    2181            0 :         let has_archived_parent =
    2182            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2183            0 :                 ancestor_timeline.is_archived() == Some(true)
    2184            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2185            0 :                 true
    2186              :             } else {
    2187            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2188            0 :                 if cfg!(debug_assertions) {
    2189            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2190            0 :                 }
    2191            0 :                 return Err(TimelineArchivalError::NotFound);
    2192              :             };
    2193            0 :         if has_archived_parent {
    2194            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2195            0 :                 ancestor_timeline_id,
    2196            0 :             ));
    2197            0 :         }
    2198            0 :         Ok(())
    2199            0 :     }
    2200              : 
    2201            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2202            0 :         timeline: &Arc<Timeline>,
    2203            0 :     ) -> Result<(), TimelineArchivalError> {
    2204            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2205            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2206            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2207            0 :                     ancestor_timeline.timeline_id,
    2208            0 :                 ));
    2209            0 :             }
    2210            0 :         }
    2211            0 :         Ok(())
    2212            0 :     }
    2213              : 
    2214              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2215              :     ///
    2216              :     /// Counterpart to [`offload_timeline`].
    2217            0 :     async fn unoffload_timeline(
    2218            0 :         self: &Arc<Self>,
    2219            0 :         timeline_id: TimelineId,
    2220            0 :         broker_client: storage_broker::BrokerClientChannel,
    2221            0 :         ctx: RequestContext,
    2222            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2223            0 :         info!("unoffloading timeline");
    2224              : 
    2225              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2226              :         // We expect callers of this function to ensure this.
    2227            0 :         match self.current_state() {
    2228              :             TenantState::Activating { .. }
    2229              :             | TenantState::Attaching
    2230              :             | TenantState::Broken { .. } => {
    2231            0 :                 panic!("Timeline expected to be active")
    2232              :             }
    2233            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2234            0 :             TenantState::Active => {}
    2235              :         }
    2236            0 :         let cancel = self.cancel.clone();
    2237              : 
    2238              :         // Protect against concurrent attempts to use this TimelineId
    2239              :         // We don't care much about idempotency, as it's ensured a layer above.
    2240            0 :         let allow_offloaded = true;
    2241            0 :         let _create_guard = self
    2242            0 :             .create_timeline_create_guard(
    2243            0 :                 timeline_id,
    2244            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2245            0 :                 allow_offloaded,
    2246              :             )
    2247            0 :             .map_err(|err| match err {
    2248            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2249              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2250            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2251              :                 }
    2252            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2253            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2254            0 :             })?;
    2255              : 
    2256            0 :         let timeline_preload = self
    2257            0 :             .load_timeline_metadata(
    2258            0 :                 timeline_id,
    2259            0 :                 self.remote_storage.clone(),
    2260            0 :                 None,
    2261            0 :                 cancel.clone(),
    2262            0 :             )
    2263            0 :             .await;
    2264              : 
    2265            0 :         let index_part = match timeline_preload.index_part {
    2266            0 :             Ok(index_part) => {
    2267            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2268            0 :                 index_part
    2269              :             }
    2270              :             Err(DownloadError::NotFound) => {
    2271            0 :                 error!(%timeline_id, "index_part not found on remote");
    2272            0 :                 return Err(TimelineArchivalError::NotFound);
    2273              :             }
    2274            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2275            0 :             Err(e) => {
    2276              :                 // Some (possibly ephemeral) error happened during index_part download.
    2277            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2278            0 :                 return Err(TimelineArchivalError::Other(
    2279            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2280            0 :                 ));
    2281              :             }
    2282              :         };
    2283            0 :         let index_part = match index_part {
    2284            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2285            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2286            0 :                 info!("timeline is deleted according to index_part.json");
    2287            0 :                 return Err(TimelineArchivalError::NotFound);
    2288              :             }
    2289              :         };
    2290            0 :         let remote_metadata = index_part.metadata.clone();
    2291            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2292            0 :         self.load_remote_timeline(
    2293            0 :             timeline_id,
    2294            0 :             index_part,
    2295            0 :             remote_metadata,
    2296            0 :             None,
    2297            0 :             timeline_resources,
    2298            0 :             LoadTimelineCause::Unoffload,
    2299            0 :             &ctx,
    2300            0 :         )
    2301            0 :         .await
    2302            0 :         .with_context(|| {
    2303            0 :             format!(
    2304            0 :                 "failed to load remote timeline {} for tenant {}",
    2305            0 :                 timeline_id, self.tenant_shard_id
    2306              :             )
    2307            0 :         })
    2308            0 :         .map_err(TimelineArchivalError::Other)?;
    2309              : 
    2310            0 :         let timeline = {
    2311            0 :             let timelines = self.timelines.lock().unwrap();
    2312            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2313            0 :                 warn!("timeline not available directly after attach");
    2314              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2315              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2316            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2317            0 :                     "timeline not available directly after attach"
    2318            0 :                 )));
    2319              :             };
    2320            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2321            0 :             match offloaded_timelines.remove(&timeline_id) {
    2322            0 :                 Some(offloaded) => {
    2323            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2324            0 :                 }
    2325            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2326              :             }
    2327              : 
    2328            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2329              : 
    2330            0 :             Arc::clone(timeline)
    2331              :         };
    2332              : 
    2333              :         // Upload new list of offloaded timelines to S3
    2334            0 :         self.maybe_upload_tenant_manifest().await?;
    2335              : 
    2336              :         // Activate the timeline (if it makes sense)
    2337            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2338            0 :             let background_jobs_can_start = None;
    2339            0 :             timeline.activate(
    2340            0 :                 self.clone(),
    2341            0 :                 broker_client.clone(),
    2342            0 :                 background_jobs_can_start,
    2343            0 :                 &ctx.with_scope_timeline(&timeline),
    2344            0 :             );
    2345            0 :         }
    2346              : 
    2347            0 :         info!("timeline unoffloading complete");
    2348            0 :         Ok(timeline)
    2349            0 :     }
    2350              : 
    2351            0 :     pub(crate) async fn apply_timeline_archival_config(
    2352            0 :         self: &Arc<Self>,
    2353            0 :         timeline_id: TimelineId,
    2354            0 :         new_state: TimelineArchivalState,
    2355            0 :         broker_client: storage_broker::BrokerClientChannel,
    2356            0 :         ctx: RequestContext,
    2357            0 :     ) -> Result<(), TimelineArchivalError> {
    2358            0 :         info!("setting timeline archival config");
    2359              :         // First part: figure out what is needed to do, and do validation
    2360            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2361            0 :             let timelines = self.timelines.lock().unwrap();
    2362              : 
    2363            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2364            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2365            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2366            0 :                     return Err(TimelineArchivalError::NotFound);
    2367              :                 };
    2368            0 :                 if new_state == TimelineArchivalState::Archived {
    2369              :                     // It's offloaded already, so nothing to do
    2370            0 :                     return Ok(());
    2371            0 :                 }
    2372            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2373            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2374            0 :                         ancestor_timeline_id,
    2375            0 :                         &timelines,
    2376            0 :                         &offloaded_timelines,
    2377            0 :                     )?;
    2378            0 :                 }
    2379            0 :                 break 'outer None;
    2380              :             };
    2381              : 
    2382              :             // Do some validation. We release the timelines lock below, so there is potential
    2383              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2384              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2385            0 :             match new_state {
    2386              :                 TimelineArchivalState::Unarchived => {
    2387            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2388              :                 }
    2389              :                 TimelineArchivalState::Archived => {
    2390            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2391              :                 }
    2392              :             }
    2393            0 :             Some(Arc::clone(timeline))
    2394              :         };
    2395              : 
    2396              :         // Second part: unoffload timeline (if needed)
    2397            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2398            0 :             timeline
    2399              :         } else {
    2400              :             // Turn offloaded timeline into a non-offloaded one
    2401            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2402            0 :                 .await?
    2403              :         };
    2404              : 
    2405              :         // Third part: upload new timeline archival state and block until it is present in S3
    2406            0 :         let upload_needed = match timeline
    2407            0 :             .remote_client
    2408            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2409              :         {
    2410            0 :             Ok(upload_needed) => upload_needed,
    2411            0 :             Err(e) => {
    2412            0 :                 if timeline.cancel.is_cancelled() {
    2413            0 :                     return Err(TimelineArchivalError::Cancelled);
    2414              :                 } else {
    2415            0 :                     return Err(TimelineArchivalError::Other(e));
    2416              :                 }
    2417              :             }
    2418              :         };
    2419              : 
    2420            0 :         if upload_needed {
    2421            0 :             info!("Uploading new state");
    2422              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2423            0 :             let Ok(v) =
    2424            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2425              :             else {
    2426            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2427            0 :                 return Err(TimelineArchivalError::Timeout);
    2428              :             };
    2429            0 :             v.map_err(|e| match e {
    2430            0 :                 WaitCompletionError::NotInitialized(e) => {
    2431            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2432              :                 }
    2433              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2434            0 :                     TimelineArchivalError::Cancelled
    2435              :                 }
    2436            0 :             })?;
    2437            0 :         }
    2438            0 :         Ok(())
    2439            0 :     }
    2440              : 
    2441            1 :     pub fn get_offloaded_timeline(
    2442            1 :         &self,
    2443            1 :         timeline_id: TimelineId,
    2444            1 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2445            1 :         self.timelines_offloaded
    2446            1 :             .lock()
    2447            1 :             .unwrap()
    2448            1 :             .get(&timeline_id)
    2449            1 :             .map(Arc::clone)
    2450            1 :             .ok_or(GetTimelineError::NotFound {
    2451            1 :                 tenant_id: self.tenant_shard_id,
    2452            1 :                 timeline_id,
    2453            1 :             })
    2454            1 :     }
    2455              : 
    2456            2 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2457            2 :         self.tenant_shard_id
    2458            2 :     }
    2459              : 
    2460              :     /// Get Timeline handle for given Neon timeline ID.
    2461              :     /// This function is idempotent. It doesn't change internal state in any way.
    2462          111 :     pub fn get_timeline(
    2463          111 :         &self,
    2464          111 :         timeline_id: TimelineId,
    2465          111 :         active_only: bool,
    2466          111 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2467          111 :         let timelines_accessor = self.timelines.lock().unwrap();
    2468          111 :         let timeline = timelines_accessor
    2469          111 :             .get(&timeline_id)
    2470          111 :             .ok_or(GetTimelineError::NotFound {
    2471          111 :                 tenant_id: self.tenant_shard_id,
    2472          111 :                 timeline_id,
    2473          111 :             })?;
    2474              : 
    2475          110 :         if active_only && !timeline.is_active() {
    2476            0 :             Err(GetTimelineError::NotActive {
    2477            0 :                 tenant_id: self.tenant_shard_id,
    2478            0 :                 timeline_id,
    2479            0 :                 state: timeline.current_state(),
    2480            0 :             })
    2481              :         } else {
    2482          110 :             Ok(Arc::clone(timeline))
    2483              :         }
    2484          111 :     }
    2485              : 
    2486              :     /// Lists timelines the tenant contains.
    2487              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2488            3 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2489            3 :         self.timelines
    2490            3 :             .lock()
    2491            3 :             .unwrap()
    2492            3 :             .values()
    2493            3 :             .map(Arc::clone)
    2494            3 :             .collect()
    2495            3 :     }
    2496              : 
    2497              :     /// Lists timelines the tenant contains.
    2498              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2499            0 :     pub fn list_importing_timelines(&self) -> Vec<Arc<ImportingTimeline>> {
    2500            0 :         self.timelines_importing
    2501            0 :             .lock()
    2502            0 :             .unwrap()
    2503            0 :             .values()
    2504            0 :             .map(Arc::clone)
    2505            0 :             .collect()
    2506            0 :     }
    2507              : 
    2508              :     /// Lists timelines the tenant manages, including offloaded ones.
    2509              :     ///
    2510              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2511            0 :     pub fn list_timelines_and_offloaded(
    2512            0 :         &self,
    2513            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2514            0 :         let timelines = self
    2515            0 :             .timelines
    2516            0 :             .lock()
    2517            0 :             .unwrap()
    2518            0 :             .values()
    2519            0 :             .map(Arc::clone)
    2520            0 :             .collect();
    2521            0 :         let offloaded = self
    2522            0 :             .timelines_offloaded
    2523            0 :             .lock()
    2524            0 :             .unwrap()
    2525            0 :             .values()
    2526            0 :             .map(Arc::clone)
    2527            0 :             .collect();
    2528            0 :         (timelines, offloaded)
    2529            0 :     }
    2530              : 
    2531            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2532            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2533            0 :     }
    2534              : 
    2535              :     /// This is used by tests & import-from-basebackup.
    2536              :     ///
    2537              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2538              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2539              :     ///
    2540              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2541              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2542              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2543              :     /// to the [`TenantShard::timelines`].
    2544              :     ///
    2545              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2546          115 :     pub(crate) async fn create_empty_timeline(
    2547          115 :         self: &Arc<Self>,
    2548          115 :         new_timeline_id: TimelineId,
    2549          115 :         initdb_lsn: Lsn,
    2550          115 :         pg_version: PgMajorVersion,
    2551          115 :         ctx: &RequestContext,
    2552          115 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2553          115 :         anyhow::ensure!(
    2554          115 :             self.is_active(),
    2555            0 :             "Cannot create empty timelines on inactive tenant"
    2556              :         );
    2557              : 
    2558              :         // Protect against concurrent attempts to use this TimelineId
    2559          115 :         let create_guard = match self
    2560          115 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2561          115 :             .await?
    2562              :         {
    2563          114 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2564              :             StartCreatingTimelineResult::Idempotent(_) => {
    2565            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2566              :             }
    2567              :         };
    2568              : 
    2569          114 :         let new_metadata = TimelineMetadata::new(
    2570              :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2571              :             // make it valid, before calling finish_creation()
    2572          114 :             Lsn(0),
    2573          114 :             None,
    2574          114 :             None,
    2575          114 :             Lsn(0),
    2576          114 :             initdb_lsn,
    2577          114 :             initdb_lsn,
    2578          114 :             pg_version,
    2579              :         );
    2580          114 :         self.prepare_new_timeline(
    2581          114 :             new_timeline_id,
    2582          114 :             &new_metadata,
    2583          114 :             create_guard,
    2584          114 :             initdb_lsn,
    2585          114 :             None,
    2586          114 :             None,
    2587          114 :             ctx,
    2588          114 :         )
    2589          114 :         .await
    2590          115 :     }
    2591              : 
    2592              :     /// Helper for unit tests to create an empty timeline.
    2593              :     ///
    2594              :     /// The timeline is has state value `Active` but its background loops are not running.
    2595              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2596              :     // Our current tests don't need the background loops.
    2597              :     #[cfg(test)]
    2598          110 :     pub async fn create_test_timeline(
    2599          110 :         self: &Arc<Self>,
    2600          110 :         new_timeline_id: TimelineId,
    2601          110 :         initdb_lsn: Lsn,
    2602          110 :         pg_version: PgMajorVersion,
    2603          110 :         ctx: &RequestContext,
    2604          110 :     ) -> anyhow::Result<Arc<Timeline>> {
    2605          110 :         let (uninit_tl, ctx) = self
    2606          110 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2607          110 :             .await?;
    2608          110 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2609          110 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2610              : 
    2611              :         // Setup minimum keys required for the timeline to be usable.
    2612          110 :         let mut modification = tline.begin_modification(initdb_lsn);
    2613          110 :         modification
    2614          110 :             .init_empty_test_timeline()
    2615          110 :             .context("init_empty_test_timeline")?;
    2616          110 :         modification
    2617          110 :             .commit(&ctx)
    2618          110 :             .await
    2619          110 :             .context("commit init_empty_test_timeline modification")?;
    2620              : 
    2621              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2622          110 :         tline.maybe_spawn_flush_loop();
    2623          110 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2624              : 
    2625              :         // Make sure the freeze_and_flush reaches remote storage.
    2626          110 :         tline.remote_client.wait_completion().await.unwrap();
    2627              : 
    2628          110 :         let tl = uninit_tl.finish_creation().await?;
    2629              :         // The non-test code would call tl.activate() here.
    2630          110 :         tl.set_state(TimelineState::Active);
    2631          110 :         Ok(tl)
    2632          110 :     }
    2633              : 
    2634              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2635              :     #[cfg(test)]
    2636              :     #[allow(clippy::too_many_arguments)]
    2637           24 :     pub async fn create_test_timeline_with_layers(
    2638           24 :         self: &Arc<Self>,
    2639           24 :         new_timeline_id: TimelineId,
    2640           24 :         initdb_lsn: Lsn,
    2641           24 :         pg_version: PgMajorVersion,
    2642           24 :         ctx: &RequestContext,
    2643           24 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2644           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2645           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2646           24 :         end_lsn: Lsn,
    2647           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    2648              :         use checks::check_valid_layermap;
    2649              :         use itertools::Itertools;
    2650              : 
    2651           24 :         let tline = self
    2652           24 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2653           24 :             .await?;
    2654           24 :         tline.force_advance_lsn(end_lsn);
    2655           71 :         for deltas in delta_layer_desc {
    2656           47 :             tline
    2657           47 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2658           47 :                 .await?;
    2659              :         }
    2660           58 :         for (lsn, images) in image_layer_desc {
    2661           34 :             tline
    2662           34 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2663           34 :                 .await?;
    2664              :         }
    2665           28 :         for in_memory in in_memory_layer_desc {
    2666            4 :             tline
    2667            4 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2668            4 :                 .await?;
    2669              :         }
    2670           24 :         let layer_names = tline
    2671           24 :             .layers
    2672           24 :             .read(LayerManagerLockHolder::Testing)
    2673           24 :             .await
    2674           24 :             .layer_map()
    2675           24 :             .unwrap()
    2676           24 :             .iter_historic_layers()
    2677          105 :             .map(|layer| layer.layer_name())
    2678           24 :             .collect_vec();
    2679           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2680            0 :             bail!("invalid layermap: {err}");
    2681           24 :         }
    2682           24 :         Ok(tline)
    2683           24 :     }
    2684              : 
    2685              :     /// Create a new timeline.
    2686              :     ///
    2687              :     /// Returns the new timeline ID and reference to its Timeline object.
    2688              :     ///
    2689              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2690              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2691              :     #[allow(clippy::too_many_arguments)]
    2692            0 :     pub(crate) async fn create_timeline(
    2693            0 :         self: &Arc<TenantShard>,
    2694            0 :         params: CreateTimelineParams,
    2695            0 :         broker_client: storage_broker::BrokerClientChannel,
    2696            0 :         ctx: &RequestContext,
    2697            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2698            0 :         if !self.is_active() {
    2699            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2700            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2701              :             } else {
    2702            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2703            0 :                     "Cannot create timelines on inactive tenant"
    2704            0 :                 )));
    2705              :             }
    2706            0 :         }
    2707              : 
    2708            0 :         let _gate = self
    2709            0 :             .gate
    2710            0 :             .enter()
    2711            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2712              : 
    2713            0 :         let result: CreateTimelineResult = match params {
    2714              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2715            0 :                 new_timeline_id,
    2716            0 :                 existing_initdb_timeline_id,
    2717            0 :                 pg_version,
    2718              :             }) => {
    2719            0 :                 self.bootstrap_timeline(
    2720            0 :                     new_timeline_id,
    2721            0 :                     pg_version,
    2722            0 :                     existing_initdb_timeline_id,
    2723            0 :                     ctx,
    2724            0 :                 )
    2725            0 :                 .await?
    2726              :             }
    2727              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2728            0 :                 new_timeline_id,
    2729            0 :                 ancestor_timeline_id,
    2730            0 :                 mut ancestor_start_lsn,
    2731              :             }) => {
    2732            0 :                 let ancestor_timeline = self
    2733            0 :                     .get_timeline(ancestor_timeline_id, false)
    2734            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2735              : 
    2736              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2737              :                 // ready for other purposes either.
    2738            0 :                 if !ancestor_timeline.is_active() {
    2739            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2740            0 :                 }
    2741              : 
    2742            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2743            0 :                     info!("tried to branch archived timeline");
    2744            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2745            0 :                 }
    2746              : 
    2747            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2748            0 :                     *lsn = lsn.align();
    2749              : 
    2750            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2751            0 :                     if ancestor_ancestor_lsn > *lsn {
    2752              :                         // can we safely just branch from the ancestor instead?
    2753            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2754            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2755            0 :                             lsn,
    2756            0 :                             ancestor_timeline_id,
    2757            0 :                             ancestor_ancestor_lsn,
    2758            0 :                         )));
    2759            0 :                     }
    2760              : 
    2761              :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2762              :                     // to the requested branch point. The repository code itself doesn't
    2763              :                     // require it, but if we start to receive WAL on the new timeline,
    2764              :                     // decoding the new WAL might need to look up previous pages, relation
    2765              :                     // sizes etc. and that would get confused if the previous page versions
    2766              :                     // are not in the repository yet.
    2767            0 :                     ancestor_timeline
    2768            0 :                         .wait_lsn(
    2769            0 :                             *lsn,
    2770            0 :                             timeline::WaitLsnWaiter::Tenant,
    2771            0 :                             timeline::WaitLsnTimeout::Default,
    2772            0 :                             ctx,
    2773            0 :                         )
    2774            0 :                         .await
    2775            0 :                         .map_err(|e| match e {
    2776            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2777            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2778              :                             }
    2779            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2780            0 :                         })?;
    2781            0 :                 }
    2782              : 
    2783            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2784            0 :                     .await?
    2785              :             }
    2786            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2787            0 :                 self.create_timeline_import_pgdata(params, ctx).await?
    2788              :             }
    2789              :         };
    2790              : 
    2791              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2792              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2793              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2794              :         //
    2795              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2796              :         // assume that, because they can see the timeline via API, that the creation is done and
    2797              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2798              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2799              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2800              :         //
    2801              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2802              :         // creation API until it returns success. Only then is durability guaranteed.
    2803            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2804            0 :         result
    2805            0 :             .timeline()
    2806            0 :             .remote_client
    2807            0 :             .wait_completion()
    2808            0 :             .await
    2809            0 :             .map_err(|e| match e {
    2810              :                 WaitCompletionError::NotInitialized(
    2811            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2812            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2813              :                 WaitCompletionError::NotInitialized(_) => {
    2814              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2815            0 :                     debug_assert!(false);
    2816            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2817              :                 }
    2818              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2819            0 :                     CreateTimelineError::ShuttingDown
    2820              :                 }
    2821            0 :             })?;
    2822              : 
    2823              :         // The creating task is responsible for activating the timeline.
    2824              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2825              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2826            0 :         let activated_timeline = match result {
    2827            0 :             CreateTimelineResult::Created(timeline) => {
    2828            0 :                 timeline.activate(
    2829            0 :                     self.clone(),
    2830            0 :                     broker_client,
    2831            0 :                     None,
    2832            0 :                     &ctx.with_scope_timeline(&timeline),
    2833              :                 );
    2834            0 :                 timeline
    2835              :             }
    2836            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2837            0 :                 info!(
    2838            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2839              :                 );
    2840            0 :                 timeline
    2841              :             }
    2842            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2843            0 :                 info!(
    2844            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2845              :                 );
    2846            0 :                 timeline
    2847              :             }
    2848              :         };
    2849              : 
    2850            0 :         Ok(activated_timeline)
    2851            0 :     }
    2852              : 
    2853              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2854              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2855              :     /// [`TenantShard::timelines`] map when the import completes.
    2856              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2857              :     /// for the response.
    2858            0 :     async fn create_timeline_import_pgdata(
    2859            0 :         self: &Arc<Self>,
    2860            0 :         params: CreateTimelineParamsImportPgdata,
    2861            0 :         ctx: &RequestContext,
    2862            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2863              :         let CreateTimelineParamsImportPgdata {
    2864            0 :             new_timeline_id,
    2865            0 :             location,
    2866            0 :             idempotency_key,
    2867            0 :         } = params;
    2868              : 
    2869            0 :         let started_at = chrono::Utc::now().naive_utc();
    2870              : 
    2871              :         //
    2872              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2873              :         // is the canonical way we do it.
    2874              :         // - create an empty timeline in-memory
    2875              :         // - use its remote_timeline_client to do the upload
    2876              :         // - dispose of the uninit timeline
    2877              :         // - keep the creation guard alive
    2878              : 
    2879            0 :         let timeline_create_guard = match self
    2880            0 :             .start_creating_timeline(
    2881            0 :                 new_timeline_id,
    2882            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2883            0 :                     idempotency_key: idempotency_key.clone(),
    2884            0 :                 }),
    2885            0 :             )
    2886            0 :             .await?
    2887              :         {
    2888            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2889            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2890            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2891              :             }
    2892              :         };
    2893              : 
    2894            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2895            0 :             let this = &self;
    2896            0 :             let initdb_lsn = Lsn(0);
    2897            0 :             async move {
    2898            0 :                 let new_metadata = TimelineMetadata::new(
    2899              :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2900              :                     // make it valid, before calling finish_creation()
    2901            0 :                     Lsn(0),
    2902            0 :                     None,
    2903            0 :                     None,
    2904            0 :                     Lsn(0),
    2905            0 :                     initdb_lsn,
    2906            0 :                     initdb_lsn,
    2907            0 :                     PgMajorVersion::PG15,
    2908              :                 );
    2909            0 :                 this.prepare_new_timeline(
    2910            0 :                     new_timeline_id,
    2911            0 :                     &new_metadata,
    2912            0 :                     timeline_create_guard,
    2913            0 :                     initdb_lsn,
    2914            0 :                     None,
    2915            0 :                     None,
    2916            0 :                     ctx,
    2917            0 :                 )
    2918            0 :                 .await
    2919            0 :             }
    2920              :         }
    2921            0 :         .await?;
    2922              : 
    2923            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2924            0 :             idempotency_key,
    2925            0 :             location,
    2926            0 :             started_at,
    2927            0 :         };
    2928            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2929            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2930            0 :         );
    2931            0 :         uninit_timeline
    2932            0 :             .raw_timeline()
    2933            0 :             .unwrap()
    2934            0 :             .remote_client
    2935            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2936              : 
    2937              :         // wait_completion happens in caller
    2938              : 
    2939            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2940              : 
    2941            0 :         let import_task_gate = Gate::default();
    2942            0 :         let import_task_guard = import_task_gate.enter().unwrap();
    2943              : 
    2944            0 :         let import_task_handle = tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2945            0 :             timeline.clone(),
    2946            0 :             index_part,
    2947            0 :             timeline_create_guard,
    2948            0 :             import_task_guard,
    2949            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2950              :         ));
    2951              : 
    2952            0 :         let prev = self.timelines_importing.lock().unwrap().insert(
    2953            0 :             timeline.timeline_id,
    2954            0 :             Arc::new(ImportingTimeline {
    2955            0 :                 timeline: timeline.clone(),
    2956            0 :                 import_task_handle,
    2957            0 :                 import_task_gate,
    2958            0 :                 delete_progress: TimelineDeleteProgress::default(),
    2959            0 :             }),
    2960            0 :         );
    2961              : 
    2962              :         // Idempotency is enforced higher up the stack
    2963            0 :         assert!(prev.is_none());
    2964              : 
    2965              :         // NB: the timeline doesn't exist in self.timelines at this point
    2966            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2967            0 :     }
    2968              : 
    2969              :     /// Finalize the import of a timeline on this shard by marking it complete in
    2970              :     /// the index part. If the import task hasn't finished yet, returns an error.
    2971              :     ///
    2972              :     /// This method is idempotent. If the import was finalized once, the next call
    2973              :     /// will be a no-op.
    2974            0 :     pub(crate) async fn finalize_importing_timeline(
    2975            0 :         &self,
    2976            0 :         timeline_id: TimelineId,
    2977            0 :     ) -> Result<(), FinalizeTimelineImportError> {
    2978            0 :         let timeline = {
    2979            0 :             let locked = self.timelines_importing.lock().unwrap();
    2980            0 :             match locked.get(&timeline_id) {
    2981            0 :                 Some(importing_timeline) => {
    2982            0 :                     if !importing_timeline.import_task_handle.is_finished() {
    2983            0 :                         return Err(FinalizeTimelineImportError::ImportTaskStillRunning);
    2984            0 :                     }
    2985              : 
    2986            0 :                     importing_timeline.timeline.clone()
    2987              :                 }
    2988              :                 None => {
    2989            0 :                     return Ok(());
    2990              :                 }
    2991              :             }
    2992              :         };
    2993              : 
    2994            0 :         timeline
    2995            0 :             .remote_client
    2996            0 :             .schedule_index_upload_for_import_pgdata_finalize()
    2997            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    2998            0 :         timeline
    2999            0 :             .remote_client
    3000            0 :             .wait_completion()
    3001            0 :             .await
    3002            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    3003              : 
    3004            0 :         self.timelines_importing
    3005            0 :             .lock()
    3006            0 :             .unwrap()
    3007            0 :             .remove(&timeline_id);
    3008              : 
    3009            0 :         Ok(())
    3010            0 :     }
    3011              : 
    3012              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
    3013              :     async fn create_timeline_import_pgdata_task(
    3014              :         self: Arc<TenantShard>,
    3015              :         timeline: Arc<Timeline>,
    3016              :         index_part: import_pgdata::index_part_format::Root,
    3017              :         timeline_create_guard: TimelineCreateGuard,
    3018              :         _import_task_guard: GateGuard,
    3019              :         ctx: RequestContext,
    3020              :     ) {
    3021              :         debug_assert_current_span_has_tenant_and_timeline_id();
    3022              :         info!("starting");
    3023              :         scopeguard::defer! {info!("exiting")};
    3024              : 
    3025              :         let res = self
    3026              :             .create_timeline_import_pgdata_task_impl(
    3027              :                 timeline,
    3028              :                 index_part,
    3029              :                 timeline_create_guard,
    3030              :                 ctx,
    3031              :             )
    3032              :             .await;
    3033              :         if let Err(err) = &res {
    3034              :             error!(?err, "task failed");
    3035              :             // TODO sleep & retry, sensitive to tenant shutdown
    3036              :             // TODO: allow timeline deletion requests => should cancel the task
    3037              :         }
    3038              :     }
    3039              : 
    3040            0 :     async fn create_timeline_import_pgdata_task_impl(
    3041            0 :         self: Arc<TenantShard>,
    3042            0 :         timeline: Arc<Timeline>,
    3043            0 :         index_part: import_pgdata::index_part_format::Root,
    3044            0 :         _timeline_create_guard: TimelineCreateGuard,
    3045            0 :         ctx: RequestContext,
    3046            0 :     ) -> Result<(), anyhow::Error> {
    3047            0 :         info!("importing pgdata");
    3048            0 :         let ctx = ctx.with_scope_timeline(&timeline);
    3049            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    3050            0 :             .await
    3051            0 :             .context("import")?;
    3052            0 :         info!("import done - waiting for activation");
    3053              : 
    3054            0 :         anyhow::Ok(())
    3055            0 :     }
    3056              : 
    3057            0 :     pub(crate) async fn delete_timeline(
    3058            0 :         self: Arc<Self>,
    3059            0 :         timeline_id: TimelineId,
    3060            0 :     ) -> Result<(), DeleteTimelineError> {
    3061            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    3062              : 
    3063            0 :         Ok(())
    3064            0 :     }
    3065              : 
    3066              :     /// perform one garbage collection iteration, removing old data files from disk.
    3067              :     /// this function is periodically called by gc task.
    3068              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    3069              :     ///
    3070              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    3071              :     ///
    3072              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    3073              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    3074              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    3075              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    3076              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    3077              :     /// requires more history to be retained.
    3078              :     //
    3079          377 :     pub(crate) async fn gc_iteration(
    3080          377 :         &self,
    3081          377 :         target_timeline_id: Option<TimelineId>,
    3082          377 :         horizon: u64,
    3083          377 :         pitr: Duration,
    3084          377 :         cancel: &CancellationToken,
    3085          377 :         ctx: &RequestContext,
    3086          377 :     ) -> Result<GcResult, GcError> {
    3087              :         // Don't start doing work during shutdown
    3088          377 :         if let TenantState::Stopping { .. } = self.current_state() {
    3089            0 :             return Ok(GcResult::default());
    3090          377 :         }
    3091              : 
    3092              :         // there is a global allowed_error for this
    3093          377 :         if !self.is_active() {
    3094            0 :             return Err(GcError::NotActive);
    3095          377 :         }
    3096              : 
    3097              :         {
    3098          377 :             let conf = self.tenant_conf.load();
    3099              : 
    3100              :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    3101              :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    3102              :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    3103              :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    3104          377 :             if !conf.location.may_delete_layers_hint() {
    3105            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    3106            0 :                 return Ok(GcResult::default());
    3107          377 :             }
    3108              : 
    3109          377 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    3110            0 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3111            0 :                 return Ok(GcResult::default());
    3112          377 :             }
    3113              :         }
    3114              : 
    3115          377 :         let _guard = match self.gc_block.start().await {
    3116          377 :             Ok(guard) => guard,
    3117            0 :             Err(reasons) => {
    3118            0 :                 info!("Skipping GC: {reasons}");
    3119            0 :                 return Ok(GcResult::default());
    3120              :             }
    3121              :         };
    3122              : 
    3123          377 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3124          377 :             .await
    3125          377 :     }
    3126              : 
    3127              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3128              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3129              :     /// immediate L0 compaction.
    3130              :     ///
    3131              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3132            0 :     async fn compaction_iteration(
    3133            0 :         self: &Arc<Self>,
    3134            0 :         cancel: &CancellationToken,
    3135            0 :         ctx: &RequestContext,
    3136            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3137              :         // Don't compact inactive tenants.
    3138            0 :         if !self.is_active() {
    3139            0 :             return Ok(CompactionOutcome::Skipped);
    3140            0 :         }
    3141              : 
    3142              :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3143              :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3144            0 :         let location = self.tenant_conf.load().location;
    3145            0 :         if !location.may_upload_layers_hint() {
    3146            0 :             info!("skipping compaction in location state {location:?}");
    3147            0 :             return Ok(CompactionOutcome::Skipped);
    3148            0 :         }
    3149              : 
    3150              :         // Don't compact if the circuit breaker is tripped.
    3151            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3152            0 :             info!("skipping compaction due to previous failures");
    3153            0 :             return Ok(CompactionOutcome::Skipped);
    3154            0 :         }
    3155              : 
    3156              :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3157            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3158            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3159            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3160              : 
    3161              :         {
    3162            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3163            0 :             let timelines = self.timelines.lock().unwrap();
    3164            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3165              :                 // Skip inactive timelines.
    3166            0 :                 if !timeline.is_active() {
    3167            0 :                     continue;
    3168            0 :                 }
    3169              : 
    3170              :                 // Schedule the timeline for compaction.
    3171            0 :                 compact.push(timeline.clone());
    3172              : 
    3173              :                 // Schedule the timeline for offloading if eligible.
    3174            0 :                 let can_offload = offload_enabled
    3175            0 :                     && timeline.can_offload().0
    3176            0 :                     && !timelines
    3177            0 :                         .iter()
    3178            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3179            0 :                 if can_offload {
    3180            0 :                     offload.insert(timeline_id);
    3181            0 :                 }
    3182              :             }
    3183              :         } // release timelines lock
    3184              : 
    3185            0 :         for timeline in &compact {
    3186              :             // Collect L0 counts. Can't await while holding lock above.
    3187            0 :             if let Ok(lm) = timeline
    3188            0 :                 .layers
    3189            0 :                 .read(LayerManagerLockHolder::Compaction)
    3190            0 :                 .await
    3191            0 :                 .layer_map()
    3192            0 :             {
    3193            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3194            0 :             }
    3195              :         }
    3196              : 
    3197              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3198              :         // bound read amplification.
    3199              :         //
    3200              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3201              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3202              :         // splitting L0 and image/GC compaction to separate background jobs.
    3203            0 :         if self.get_compaction_l0_first() {
    3204            0 :             let compaction_threshold = self.get_compaction_threshold();
    3205            0 :             let compact_l0 = compact
    3206            0 :                 .iter()
    3207            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3208            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3209            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3210            0 :                 .rev()
    3211            0 :                 .map(|(tli, _)| tli.clone())
    3212            0 :                 .collect_vec();
    3213              : 
    3214            0 :             let mut has_pending_l0 = false;
    3215            0 :             for timeline in compact_l0 {
    3216            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3217              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3218            0 :                 let outcome = timeline
    3219            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3220            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3221            0 :                     .await
    3222            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3223            0 :                 match outcome {
    3224            0 :                     CompactionOutcome::Done => {}
    3225            0 :                     CompactionOutcome::Skipped => {}
    3226            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3227            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3228              :                 }
    3229              :             }
    3230            0 :             if has_pending_l0 {
    3231            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3232            0 :             }
    3233            0 :         }
    3234              : 
    3235              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3236              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3237              :         // pending L0 compaction on any tenant timeline.
    3238              :         //
    3239              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3240              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3241            0 :         let mut has_pending = false;
    3242            0 :         for timeline in compact {
    3243            0 :             if !timeline.is_active() {
    3244            0 :                 continue;
    3245            0 :             }
    3246            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3247              : 
    3248              :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3249            0 :             let mut flags = EnumSet::default();
    3250            0 :             if self.get_compaction_l0_first() {
    3251            0 :                 flags |= CompactFlags::YieldForL0;
    3252            0 :             }
    3253              : 
    3254            0 :             let mut outcome = timeline
    3255            0 :                 .compact(cancel, flags, ctx)
    3256            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3257            0 :                 .await
    3258            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3259              : 
    3260              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3261            0 :             if outcome == CompactionOutcome::Done {
    3262            0 :                 let queue = {
    3263            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3264            0 :                     guard
    3265            0 :                         .entry(timeline.timeline_id)
    3266            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3267            0 :                         .clone()
    3268              :                 };
    3269            0 :                 let gc_compaction_strategy = self
    3270            0 :                     .feature_resolver
    3271            0 :                     .evaluate_multivariate("gc-comapction-strategy")
    3272            0 :                     .ok();
    3273            0 :                 let span = if let Some(gc_compaction_strategy) = gc_compaction_strategy {
    3274            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id, strategy = %gc_compaction_strategy)
    3275              :                 } else {
    3276            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id)
    3277              :                 };
    3278            0 :                 outcome = queue
    3279            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3280            0 :                     .instrument(span)
    3281            0 :                     .await?;
    3282            0 :             }
    3283              : 
    3284              :             // If we're done compacting, offload the timeline if requested.
    3285            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3286            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3287            0 :                 offload_timeline(self, &timeline)
    3288            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3289            0 :                     .await
    3290            0 :                     .or_else(|err| match err {
    3291              :                         // Ignore this, we likely raced with unarchival.
    3292            0 :                         OffloadError::NotArchived => Ok(()),
    3293            0 :                         OffloadError::AlreadyInProgress => Ok(()),
    3294            0 :                         OffloadError::Cancelled => Err(CompactionError::new_cancelled()),
    3295              :                         // don't break the anyhow chain
    3296            0 :                         OffloadError::Other(err) => Err(CompactionError::Other(err)),
    3297            0 :                     })?;
    3298            0 :             }
    3299              : 
    3300            0 :             match outcome {
    3301            0 :                 CompactionOutcome::Done => {}
    3302            0 :                 CompactionOutcome::Skipped => {}
    3303            0 :                 CompactionOutcome::Pending => has_pending = true,
    3304              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3305              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3306            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3307              :             }
    3308              :         }
    3309              : 
    3310              :         // Success! Untrip the breaker if necessary.
    3311            0 :         self.compaction_circuit_breaker
    3312            0 :             .lock()
    3313            0 :             .unwrap()
    3314            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3315              : 
    3316            0 :         match has_pending {
    3317            0 :             true => Ok(CompactionOutcome::Pending),
    3318            0 :             false => Ok(CompactionOutcome::Done),
    3319              :         }
    3320            0 :     }
    3321              : 
    3322              :     /// Trips the compaction circuit breaker if appropriate.
    3323            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3324            0 :         if err.is_cancel() {
    3325            0 :             return;
    3326            0 :         }
    3327            0 :         self.compaction_circuit_breaker
    3328            0 :             .lock()
    3329            0 :             .unwrap()
    3330            0 :             .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3331            0 :     }
    3332              : 
    3333              :     /// Cancel scheduled compaction tasks
    3334            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3335            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3336            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3337            0 :             q.cancel_scheduled();
    3338            0 :         }
    3339            0 :     }
    3340              : 
    3341            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3342            0 :         &self,
    3343            0 :         timeline_id: TimelineId,
    3344            0 :     ) -> Vec<CompactInfoResponse> {
    3345            0 :         let res = {
    3346            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3347            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3348              :         };
    3349            0 :         let Some((running, remaining)) = res else {
    3350            0 :             return Vec::new();
    3351              :         };
    3352            0 :         let mut result = Vec::new();
    3353            0 :         if let Some((id, running)) = running {
    3354            0 :             result.extend(running.into_compact_info_resp(id, true));
    3355            0 :         }
    3356            0 :         for (id, job) in remaining {
    3357            0 :             result.extend(job.into_compact_info_resp(id, false));
    3358            0 :         }
    3359            0 :         result
    3360            0 :     }
    3361              : 
    3362              :     /// Schedule a compaction task for a timeline.
    3363            0 :     pub(crate) async fn schedule_compaction(
    3364            0 :         &self,
    3365            0 :         timeline_id: TimelineId,
    3366            0 :         options: CompactOptions,
    3367            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3368            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3369            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3370            0 :         let q = guard
    3371            0 :             .entry(timeline_id)
    3372            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3373            0 :         q.schedule_manual_compaction(options, Some(tx));
    3374            0 :         Ok(rx)
    3375            0 :     }
    3376              : 
    3377              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3378            0 :     async fn housekeeping(&self) {
    3379              :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3380              :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3381              :         //
    3382              :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3383              :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3384              :         // layers that won't be compacted down.
    3385            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3386            0 :             let timelines = self
    3387            0 :                 .timelines
    3388            0 :                 .lock()
    3389            0 :                 .unwrap()
    3390            0 :                 .values()
    3391            0 :                 .filter(|tli| tli.is_active())
    3392            0 :                 .cloned()
    3393            0 :                 .collect_vec();
    3394              : 
    3395            0 :             for timeline in timelines {
    3396            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3397              :             }
    3398            0 :         }
    3399              : 
    3400              :         // Shut down walredo if idle.
    3401              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3402            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3403            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3404            0 :         }
    3405              : 
    3406              :         // Update the feature resolver with the latest tenant-spcific data.
    3407            0 :         self.feature_resolver.refresh_properties_and_flags(self);
    3408            0 :     }
    3409              : 
    3410            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3411            0 :         let timelines = self.timelines.lock().unwrap();
    3412            0 :         !timelines
    3413            0 :             .iter()
    3414            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3415            0 :     }
    3416              : 
    3417         1371 :     pub fn current_state(&self) -> TenantState {
    3418         1371 :         self.state.borrow().clone()
    3419         1371 :     }
    3420              : 
    3421          990 :     pub fn is_active(&self) -> bool {
    3422          990 :         self.current_state() == TenantState::Active
    3423          990 :     }
    3424              : 
    3425            0 :     pub fn generation(&self) -> Generation {
    3426            0 :         self.generation
    3427            0 :     }
    3428              : 
    3429            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3430            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3431            0 :     }
    3432              : 
    3433              :     /// Changes tenant status to active, unless shutdown was already requested.
    3434              :     ///
    3435              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3436              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3437            0 :     fn activate(
    3438            0 :         self: &Arc<Self>,
    3439            0 :         broker_client: BrokerClientChannel,
    3440            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3441            0 :         ctx: &RequestContext,
    3442            0 :     ) {
    3443            0 :         span::debug_assert_current_span_has_tenant_id();
    3444              : 
    3445            0 :         let mut activating = false;
    3446            0 :         self.state.send_modify(|current_state| {
    3447              :             use pageserver_api::models::ActivatingFrom;
    3448            0 :             match &*current_state {
    3449              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3450            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {current_state:?}");
    3451              :                 }
    3452            0 :                 TenantState::Attaching => {
    3453            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3454            0 :                 }
    3455              :             }
    3456            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3457            0 :             activating = true;
    3458              :             // Continue outside the closure. We need to grab timelines.lock()
    3459              :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3460            0 :         });
    3461              : 
    3462            0 :         if activating {
    3463            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3464            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3465            0 :             let timelines_to_activate = timelines_accessor
    3466            0 :                 .values()
    3467            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3468              : 
    3469              :             // Spawn gc and compaction loops. The loops will shut themselves
    3470              :             // down when they notice that the tenant is inactive.
    3471            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3472              : 
    3473            0 :             let mut activated_timelines = 0;
    3474              : 
    3475            0 :             for timeline in timelines_to_activate {
    3476            0 :                 timeline.activate(
    3477            0 :                     self.clone(),
    3478            0 :                     broker_client.clone(),
    3479            0 :                     background_jobs_can_start,
    3480            0 :                     &ctx.with_scope_timeline(timeline),
    3481            0 :                 );
    3482            0 :                 activated_timelines += 1;
    3483            0 :             }
    3484              : 
    3485            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3486            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3487            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3488            0 :             TENANT_OFFLOADED_TIMELINES
    3489            0 :                 .with_label_values(&[&tid, &shard_id])
    3490            0 :                 .set(offloaded_timeline_count as u64);
    3491              : 
    3492            0 :             self.state.send_modify(move |current_state| {
    3493            0 :                 assert!(
    3494            0 :                     matches!(current_state, TenantState::Activating(_)),
    3495            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3496              :                 );
    3497            0 :                 *current_state = TenantState::Active;
    3498              : 
    3499            0 :                 let elapsed = self.constructed_at.elapsed();
    3500            0 :                 let total_timelines = timelines_accessor.len();
    3501              : 
    3502              :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3503              :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3504            0 :                 info!(
    3505            0 :                     since_creation_millis = elapsed.as_millis(),
    3506            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3507            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3508              :                     activated_timelines,
    3509              :                     total_timelines,
    3510            0 :                     post_state = <&'static str>::from(&*current_state),
    3511            0 :                     "activation attempt finished"
    3512              :                 );
    3513              : 
    3514            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3515            0 :             });
    3516            0 :         }
    3517            0 :     }
    3518              : 
    3519              :     /// Shutdown the tenant and join all of the spawned tasks.
    3520              :     ///
    3521              :     /// The method caters for all use-cases:
    3522              :     /// - pageserver shutdown (freeze_and_flush == true)
    3523              :     /// - detach + ignore (freeze_and_flush == false)
    3524              :     ///
    3525              :     /// This will attempt to shutdown even if tenant is broken.
    3526              :     ///
    3527              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3528              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3529              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3530              :     /// the ongoing shutdown.
    3531            3 :     async fn shutdown(
    3532            3 :         &self,
    3533            3 :         shutdown_progress: completion::Barrier,
    3534            3 :         shutdown_mode: timeline::ShutdownMode,
    3535            3 :     ) -> Result<(), completion::Barrier> {
    3536            3 :         span::debug_assert_current_span_has_tenant_id();
    3537              : 
    3538              :         // Set tenant (and its timlines) to Stoppping state.
    3539              :         //
    3540              :         // Since we can only transition into Stopping state after activation is complete,
    3541              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3542              :         //
    3543              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3544              :         // 1. Lock out any new requests to the tenants.
    3545              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3546              :         // 3. Signal cancellation for other tenant background loops.
    3547              :         // 4. ???
    3548              :         //
    3549              :         // The waiting for the cancellation is not done uniformly.
    3550              :         // We certainly wait for WAL receivers to shut down.
    3551              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3552              :         // But the tenant background loops are joined-on in our caller.
    3553              :         // It's mesed up.
    3554              :         // we just ignore the failure to stop
    3555              : 
    3556              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3557              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3558              :         // is very slow.
    3559            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3560            0 :             self.cancel.cancel();
    3561              : 
    3562              :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3563              :             // are children of ours, so their flush loops will have shut down already
    3564            0 :             timeline::ShutdownMode::Hard
    3565              :         } else {
    3566            3 :             shutdown_mode
    3567              :         };
    3568              : 
    3569            3 :         match self.set_stopping(shutdown_progress).await {
    3570            3 :             Ok(()) => {}
    3571            0 :             Err(SetStoppingError::Broken) => {
    3572            0 :                 // assume that this is acceptable
    3573            0 :             }
    3574            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3575              :                 // give caller the option to wait for this this shutdown
    3576            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3577            0 :                 return Err(other);
    3578              :             }
    3579              :         };
    3580              : 
    3581            3 :         let mut js = tokio::task::JoinSet::new();
    3582              :         {
    3583            3 :             let timelines = self.timelines.lock().unwrap();
    3584            3 :             timelines.values().for_each(|timeline| {
    3585            3 :                 let timeline = Arc::clone(timeline);
    3586            3 :                 let timeline_id = timeline.timeline_id;
    3587            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3588            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3589            3 :             });
    3590              :         }
    3591              :         {
    3592            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3593            3 :             timelines_offloaded.values().for_each(|timeline| {
    3594            0 :                 timeline.defuse_for_tenant_drop();
    3595            0 :             });
    3596              :         }
    3597              :         {
    3598            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3599            3 :             timelines_importing
    3600            3 :                 .drain()
    3601            3 :                 .for_each(|(timeline_id, importing_timeline)| {
    3602            0 :                     let span = tracing::info_span!("importing_timeline_shutdown", %timeline_id);
    3603            0 :                     js.spawn(async move { importing_timeline.shutdown().instrument(span).await });
    3604            0 :                 });
    3605              :         }
    3606              :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3607            3 :         tracing::info!("Waiting for timelines...");
    3608            6 :         while let Some(res) = js.join_next().await {
    3609            0 :             match res {
    3610            3 :                 Ok(()) => {}
    3611            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3612            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3613            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3614              :             }
    3615              :         }
    3616              : 
    3617            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3618            0 :             tracing::info!("Flushing deletion queue");
    3619            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3620            0 :                 match e {
    3621            0 :                     DeletionQueueError::ShuttingDown => {
    3622            0 :                         // This is the only error we expect for now. In the future, if more error
    3623            0 :                         // variants are added, we should handle them here.
    3624            0 :                     }
    3625              :                 }
    3626            0 :             }
    3627            3 :         }
    3628              : 
    3629              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3630              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3631            3 :         tracing::debug!("Cancelling CancellationToken");
    3632            3 :         self.cancel.cancel();
    3633              : 
    3634              :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3635              :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3636              :         //
    3637              :         // this will additionally shutdown and await all timeline tasks.
    3638            3 :         tracing::debug!("Waiting for tasks...");
    3639            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3640              : 
    3641            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3642            3 :             walredo_mgr.shutdown().await;
    3643            0 :         }
    3644              : 
    3645              :         // Wait for any in-flight operations to complete
    3646            3 :         self.gate.close().await;
    3647              : 
    3648            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3649              : 
    3650            3 :         Ok(())
    3651            3 :     }
    3652              : 
    3653              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3654              :     ///
    3655              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3656              :     ///
    3657              :     /// This function is not cancel-safe!
    3658            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3659            3 :         let mut rx = self.state.subscribe();
    3660              : 
    3661              :         // cannot stop before we're done activating, so wait out until we're done activating
    3662            3 :         rx.wait_for(|state| match state {
    3663              :             TenantState::Activating(_) | TenantState::Attaching => {
    3664            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3665            0 :                 false
    3666              :             }
    3667            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3668            3 :         })
    3669            3 :         .await
    3670            3 :         .expect("cannot drop self.state while on a &self method");
    3671              : 
    3672              :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3673            3 :         let mut err = None;
    3674            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3675              :             TenantState::Activating(_) | TenantState::Attaching => {
    3676            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3677              :             }
    3678              :             TenantState::Active => {
    3679              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3680              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3681              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3682            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3683              :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3684              :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3685            3 :                 true
    3686              :             }
    3687              :             TenantState::Stopping { progress: None } => {
    3688              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3689              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3690            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3691            0 :                 true
    3692              :             }
    3693            0 :             TenantState::Broken { reason, .. } => {
    3694            0 :                 info!(
    3695            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3696              :                 );
    3697            0 :                 err = Some(SetStoppingError::Broken);
    3698            0 :                 false
    3699              :             }
    3700            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3701            0 :                 info!("Tenant is already in Stopping state");
    3702            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3703            0 :                 false
    3704              :             }
    3705            3 :         });
    3706            3 :         match (stopping, err) {
    3707            3 :             (true, None) => {} // continue
    3708            0 :             (false, Some(err)) => return Err(err),
    3709            0 :             (true, Some(_)) => unreachable!(
    3710              :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3711              :             ),
    3712            0 :             (false, None) => unreachable!(
    3713              :                 "send_if_modified closure must return true if transitioning to Stopping"
    3714              :             ),
    3715              :         }
    3716              : 
    3717            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3718            3 :         let not_broken_timelines = timelines_accessor
    3719            3 :             .values()
    3720            3 :             .filter(|timeline| !timeline.is_broken());
    3721            6 :         for timeline in not_broken_timelines {
    3722            3 :             timeline.set_state(TimelineState::Stopping);
    3723            3 :         }
    3724            3 :         Ok(())
    3725            3 :     }
    3726              : 
    3727              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3728              :     /// `remove_tenant_from_memory`
    3729              :     ///
    3730              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3731              :     ///
    3732              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3733            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3734            0 :         let mut rx = self.state.subscribe();
    3735              : 
    3736              :         // The load & attach routines own the tenant state until it has reached `Active`.
    3737              :         // So, wait until it's done.
    3738            0 :         rx.wait_for(|state| match state {
    3739              :             TenantState::Activating(_) | TenantState::Attaching => {
    3740            0 :                 info!(
    3741            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3742            0 :                     <&'static str>::from(state)
    3743              :                 );
    3744            0 :                 false
    3745              :             }
    3746            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3747            0 :         })
    3748            0 :         .await
    3749            0 :         .expect("cannot drop self.state while on a &self method");
    3750              : 
    3751              :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3752            0 :         self.set_broken_no_wait(reason)
    3753            0 :     }
    3754              : 
    3755            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3756            0 :         let reason = reason.to_string();
    3757            0 :         self.state.send_modify(|current_state| {
    3758            0 :             match *current_state {
    3759              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3760            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3761              :                 }
    3762              :                 TenantState::Active => {
    3763            0 :                     if cfg!(feature = "testing") {
    3764            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3765            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3766              :                     } else {
    3767            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3768              :                     }
    3769              :                 }
    3770              :                 TenantState::Broken { .. } => {
    3771            0 :                     warn!("Tenant is already in Broken state");
    3772              :                 }
    3773              :                 // This is the only "expected" path, any other path is a bug.
    3774              :                 TenantState::Stopping { .. } => {
    3775            0 :                     warn!(
    3776            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3777              :                         reason
    3778              :                     );
    3779            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3780              :                 }
    3781              :            }
    3782            0 :         });
    3783            0 :     }
    3784              : 
    3785            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3786            0 :         self.state.subscribe()
    3787            0 :     }
    3788              : 
    3789              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3790              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3791            0 :     pub(crate) fn activate_now(&self) {
    3792            0 :         self.activate_now_sem.add_permits(1);
    3793            0 :     }
    3794              : 
    3795            0 :     pub(crate) async fn wait_to_become_active(
    3796            0 :         &self,
    3797            0 :         timeout: Duration,
    3798            0 :     ) -> Result<(), GetActiveTenantError> {
    3799            0 :         let mut receiver = self.state.subscribe();
    3800              :         loop {
    3801            0 :             let current_state = receiver.borrow_and_update().clone();
    3802            0 :             match current_state {
    3803              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3804              :                     // in these states, there's a chance that we can reach ::Active
    3805            0 :                     self.activate_now();
    3806            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3807            0 :                         Ok(r) => {
    3808            0 :                             r.map_err(
    3809              :                             |_e: tokio::sync::watch::error::RecvError|
    3810              :                                 // Tenant existed but was dropped: report it as non-existent
    3811            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3812            0 :                         )?
    3813              :                         }
    3814              :                         Err(TimeoutCancellableError::Cancelled) => {
    3815            0 :                             return Err(GetActiveTenantError::Cancelled);
    3816              :                         }
    3817              :                         Err(TimeoutCancellableError::Timeout) => {
    3818            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3819            0 :                                 latest_state: Some(self.current_state()),
    3820            0 :                                 wait_time: timeout,
    3821            0 :                             });
    3822              :                         }
    3823              :                     }
    3824              :                 }
    3825              :                 TenantState::Active => {
    3826            0 :                     return Ok(());
    3827              :                 }
    3828            0 :                 TenantState::Broken { reason, .. } => {
    3829              :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3830              :                     // it's logically a 500 to external API users (broken is always a bug).
    3831            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3832              :                 }
    3833              :                 TenantState::Stopping { .. } => {
    3834              :                     // There's no chance the tenant can transition back into ::Active
    3835            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3836              :                 }
    3837              :             }
    3838              :         }
    3839            0 :     }
    3840              : 
    3841            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3842            0 :         self.tenant_conf.load().location.attach_mode
    3843            0 :     }
    3844              : 
    3845              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3846              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3847              :     /// rare external API calls, like a reconciliation at startup.
    3848            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3849            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3850              : 
    3851            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3852            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3853            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3854            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3855              :         };
    3856              : 
    3857            0 :         models::LocationConfig {
    3858            0 :             mode: location_config_mode,
    3859            0 :             generation: self.generation.into(),
    3860            0 :             secondary_conf: None,
    3861            0 :             shard_number: self.shard_identity.number.0,
    3862            0 :             shard_count: self.shard_identity.count.literal(),
    3863            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3864            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3865            0 :         }
    3866            0 :     }
    3867              : 
    3868            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3869            0 :         &self.tenant_shard_id
    3870            0 :     }
    3871              : 
    3872            0 :     pub(crate) fn get_shard_identity(&self) -> ShardIdentity {
    3873            0 :         self.shard_identity
    3874            0 :     }
    3875              : 
    3876          120 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3877          120 :         self.shard_identity.stripe_size
    3878          120 :     }
    3879              : 
    3880            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3881            0 :         self.generation
    3882            0 :     }
    3883              : 
    3884              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3885              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3886              :     /// resetting this tenant to a valid state if we fail.
    3887            0 :     pub(crate) async fn split_prepare(
    3888            0 :         &self,
    3889            0 :         child_shards: &Vec<TenantShardId>,
    3890            0 :     ) -> anyhow::Result<()> {
    3891            0 :         let (timelines, offloaded) = {
    3892            0 :             let timelines = self.timelines.lock().unwrap();
    3893            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3894            0 :             (timelines.clone(), offloaded.clone())
    3895            0 :         };
    3896            0 :         let timelines_iter = timelines
    3897            0 :             .values()
    3898            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3899            0 :             .chain(
    3900            0 :                 offloaded
    3901            0 :                     .values()
    3902            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3903              :             );
    3904            0 :         for timeline in timelines_iter {
    3905              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3906              :             // to ensure that they do not start a split if currently in the process of doing these.
    3907              : 
    3908            0 :             let timeline_id = timeline.timeline_id();
    3909              : 
    3910            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3911              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3912              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3913              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3914            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3915            0 :                 timeline
    3916            0 :                     .remote_client
    3917            0 :                     .schedule_index_upload_for_file_changes()?;
    3918            0 :                 timeline.remote_client.wait_completion().await?;
    3919            0 :             }
    3920              : 
    3921            0 :             let remote_client = match timeline {
    3922            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3923            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3924            0 :                     let remote_client = self
    3925            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3926            0 :                     Arc::new(remote_client)
    3927              :                 }
    3928              :                 TimelineOrOffloadedArcRef::Importing(_) => {
    3929            0 :                     unreachable!("Importing timelines are not included in the iterator")
    3930              :                 }
    3931              :             };
    3932              : 
    3933              :             // Shut down the timeline's remote client: this means that the indices we write
    3934              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3935            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3936            0 :             remote_client.shutdown().await;
    3937              : 
    3938              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3939              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3940              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3941              :             // we use here really is the remotely persistent one).
    3942            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3943            0 :             let result = remote_client
    3944            0 :                 .download_index_file(&self.cancel)
    3945            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))
    3946            0 :                 .await?;
    3947            0 :             let index_part = match result {
    3948              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3949            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3950              :                 }
    3951            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3952              :             };
    3953              : 
    3954              :             // A shard split may not take place while a timeline import is on-going
    3955              :             // for the tenant. Timeline imports run as part of each tenant shard
    3956              :             // and rely on the sharding scheme to split the work among pageservers.
    3957              :             // If we were to split in the middle of this process, we would have to
    3958              :             // either ensure that it's driven to completion on the old shard set
    3959              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3960            0 :             match index_part.import_pgdata {
    3961            0 :                 Some(ref import) if !import.is_done() => {
    3962            0 :                     anyhow::bail!(
    3963            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3964            0 :                         import.idempotency_key()
    3965              :                     );
    3966              :                 }
    3967            0 :                 Some(_) | None => {
    3968            0 :                     // fallthrough
    3969            0 :                 }
    3970              :             }
    3971              : 
    3972            0 :             for child_shard in child_shards {
    3973            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3974            0 :                 upload_index_part(
    3975            0 :                     &self.remote_storage,
    3976            0 :                     child_shard,
    3977            0 :                     &timeline_id,
    3978            0 :                     self.generation,
    3979            0 :                     &index_part,
    3980            0 :                     &self.cancel,
    3981            0 :                 )
    3982            0 :                 .await?;
    3983              :             }
    3984              :         }
    3985              : 
    3986            0 :         let tenant_manifest = self.build_tenant_manifest();
    3987            0 :         for child_shard in child_shards {
    3988            0 :             tracing::info!(
    3989            0 :                 "Uploading tenant manifest for child {}",
    3990            0 :                 child_shard.to_index()
    3991              :             );
    3992            0 :             upload_tenant_manifest(
    3993            0 :                 &self.remote_storage,
    3994            0 :                 child_shard,
    3995            0 :                 self.generation,
    3996            0 :                 &tenant_manifest,
    3997            0 :                 &self.cancel,
    3998            0 :             )
    3999            0 :             .await?;
    4000              :         }
    4001              : 
    4002            0 :         Ok(())
    4003            0 :     }
    4004              : 
    4005            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    4006            0 :         let mut result = TopTenantShardItem {
    4007            0 :             id: self.tenant_shard_id,
    4008            0 :             resident_size: 0,
    4009            0 :             physical_size: 0,
    4010            0 :             max_logical_size: 0,
    4011            0 :             max_logical_size_per_shard: 0,
    4012            0 :         };
    4013              : 
    4014            0 :         for timeline in self.timelines.lock().unwrap().values() {
    4015            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    4016            0 : 
    4017            0 :             result.physical_size += timeline
    4018            0 :                 .remote_client
    4019            0 :                 .metrics
    4020            0 :                 .remote_physical_size_gauge
    4021            0 :                 .get();
    4022            0 :             result.max_logical_size = std::cmp::max(
    4023            0 :                 result.max_logical_size,
    4024            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    4025            0 :             );
    4026            0 :         }
    4027              : 
    4028            0 :         result.max_logical_size_per_shard = result
    4029            0 :             .max_logical_size
    4030            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    4031              : 
    4032            0 :         result
    4033            0 :     }
    4034              : }
    4035              : 
    4036              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    4037              : /// perform a topological sort, so that the parent of each timeline comes
    4038              : /// before the children.
    4039              : /// E extracts the ancestor from T
    4040              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    4041          119 : fn tree_sort_timelines<T, E>(
    4042          119 :     timelines: HashMap<TimelineId, T>,
    4043          119 :     extractor: E,
    4044          119 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    4045          119 : where
    4046          119 :     E: Fn(&T) -> Option<TimelineId>,
    4047              : {
    4048          119 :     let mut result = Vec::with_capacity(timelines.len());
    4049              : 
    4050          119 :     let mut now = Vec::with_capacity(timelines.len());
    4051              :     // (ancestor, children)
    4052          119 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    4053          119 :         HashMap::with_capacity(timelines.len());
    4054              : 
    4055          122 :     for (timeline_id, value) in timelines {
    4056            3 :         if let Some(ancestor_id) = extractor(&value) {
    4057            1 :             let children = later.entry(ancestor_id).or_default();
    4058            1 :             children.push((timeline_id, value));
    4059            2 :         } else {
    4060            2 :             now.push((timeline_id, value));
    4061            2 :         }
    4062              :     }
    4063              : 
    4064          122 :     while let Some((timeline_id, metadata)) = now.pop() {
    4065            3 :         result.push((timeline_id, metadata));
    4066              :         // All children of this can be loaded now
    4067            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    4068            1 :             now.append(&mut children);
    4069            2 :         }
    4070              :     }
    4071              : 
    4072              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    4073          119 :     if !later.is_empty() {
    4074            0 :         for (missing_id, orphan_ids) in later {
    4075            0 :             for (orphan_id, _) in orphan_ids {
    4076            0 :                 error!(
    4077            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    4078              :                 );
    4079              :             }
    4080              :         }
    4081            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    4082          119 :     }
    4083              : 
    4084          119 :     Ok(result)
    4085          119 : }
    4086              : 
    4087              : impl TenantShard {
    4088            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    4089            0 :         self.tenant_conf.load().tenant_conf.clone()
    4090            0 :     }
    4091              : 
    4092            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    4093            0 :         self.tenant_specific_overrides()
    4094            0 :             .merge(self.conf.default_tenant_conf.clone())
    4095            0 :     }
    4096              : 
    4097            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    4098            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4099            0 :         tenant_conf
    4100            0 :             .checkpoint_distance
    4101            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    4102            0 :     }
    4103              : 
    4104            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    4105            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4106            0 :         tenant_conf
    4107            0 :             .checkpoint_timeout
    4108            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    4109            0 :     }
    4110              : 
    4111            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    4112            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4113            0 :         tenant_conf
    4114            0 :             .compaction_target_size
    4115            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    4116            0 :     }
    4117              : 
    4118            0 :     pub fn get_compaction_period(&self) -> Duration {
    4119            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4120            0 :         tenant_conf
    4121            0 :             .compaction_period
    4122            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    4123            0 :     }
    4124              : 
    4125            0 :     pub fn get_compaction_threshold(&self) -> usize {
    4126            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4127            0 :         tenant_conf
    4128            0 :             .compaction_threshold
    4129            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4130            0 :     }
    4131              : 
    4132            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4133            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4134            0 :         tenant_conf
    4135            0 :             .rel_size_v2_enabled
    4136            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4137            0 :     }
    4138              : 
    4139            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4140            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4141            0 :         tenant_conf
    4142            0 :             .compaction_upper_limit
    4143            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4144            0 :     }
    4145              : 
    4146            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4147            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4148            0 :         tenant_conf
    4149            0 :             .compaction_l0_first
    4150            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4151            0 :     }
    4152              : 
    4153          121 :     pub fn get_gc_horizon(&self) -> u64 {
    4154          121 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4155          121 :         tenant_conf
    4156          121 :             .gc_horizon
    4157          121 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4158          121 :     }
    4159              : 
    4160            0 :     pub fn get_gc_period(&self) -> Duration {
    4161            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4162            0 :         tenant_conf
    4163            0 :             .gc_period
    4164            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4165            0 :     }
    4166              : 
    4167            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4168            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4169            0 :         tenant_conf
    4170            0 :             .image_creation_threshold
    4171            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4172            0 :     }
    4173              : 
    4174              :     // HADRON
    4175            0 :     pub fn get_image_creation_timeout(&self) -> Option<Duration> {
    4176            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4177            0 :         tenant_conf.image_layer_force_creation_period.or(self
    4178            0 :             .conf
    4179            0 :             .default_tenant_conf
    4180            0 :             .image_layer_force_creation_period)
    4181            0 :     }
    4182              : 
    4183            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4184            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4185            2 :         tenant_conf
    4186            2 :             .pitr_interval
    4187            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4188            2 :     }
    4189              : 
    4190            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4191            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4192            0 :         tenant_conf
    4193            0 :             .min_resident_size_override
    4194            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4195            0 :     }
    4196              : 
    4197            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4198            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4199            0 :         let heatmap_period = tenant_conf
    4200            0 :             .heatmap_period
    4201            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4202            0 :         if heatmap_period.is_zero() {
    4203            0 :             None
    4204              :         } else {
    4205            0 :             Some(heatmap_period)
    4206              :         }
    4207            0 :     }
    4208              : 
    4209            0 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4210            0 :         Self::get_lsn_lease_length_impl(self.conf, &self.tenant_conf.load().tenant_conf)
    4211            0 :     }
    4212              : 
    4213          119 :     pub fn get_lsn_lease_length_impl(
    4214          119 :         conf: &'static PageServerConf,
    4215          119 :         tenant_conf: &pageserver_api::models::TenantConfig,
    4216          119 :     ) -> Duration {
    4217          119 :         tenant_conf
    4218          119 :             .lsn_lease_length
    4219          119 :             .unwrap_or(conf.default_tenant_conf.lsn_lease_length)
    4220          119 :     }
    4221              : 
    4222            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4223            0 :         if self.conf.timeline_offloading {
    4224            0 :             return true;
    4225            0 :         }
    4226            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4227            0 :         tenant_conf
    4228            0 :             .timeline_offloading
    4229            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4230            0 :     }
    4231              : 
    4232              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4233          120 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4234              :         // Collect the offloaded timelines, and sort them for deterministic output.
    4235          120 :         let offloaded_timelines = self
    4236          120 :             .timelines_offloaded
    4237          120 :             .lock()
    4238          120 :             .unwrap()
    4239          120 :             .values()
    4240          120 :             .map(|tli| tli.manifest())
    4241          120 :             .sorted_by_key(|m| m.timeline_id)
    4242          120 :             .collect_vec();
    4243              : 
    4244          120 :         TenantManifest {
    4245          120 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4246          120 :             stripe_size: Some(self.get_shard_stripe_size()),
    4247          120 :             offloaded_timelines,
    4248          120 :         }
    4249          120 :     }
    4250              : 
    4251            1 :     pub fn update_tenant_config<
    4252            1 :         F: Fn(
    4253            1 :             pageserver_api::models::TenantConfig,
    4254            1 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4255            1 :     >(
    4256            1 :         &self,
    4257            1 :         update: F,
    4258            1 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4259              :         // Use read-copy-update in order to avoid overwriting the location config
    4260              :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4261              :         // this race is not possible if both request types come from the storage
    4262              :         // controller (as they should!) because an exclusive op lock is required
    4263              :         // on the storage controller side.
    4264              : 
    4265            1 :         self.tenant_conf
    4266            1 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4267            1 :                 Ok(Arc::new(AttachedTenantConf {
    4268            1 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4269            1 :                     location: attached_conf.location,
    4270            1 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4271              :                 }))
    4272            1 :             })?;
    4273              : 
    4274            1 :         let updated = self.tenant_conf.load();
    4275              : 
    4276            1 :         self.tenant_conf_updated(&updated.tenant_conf);
    4277              :         // Don't hold self.timelines.lock() during the notifies.
    4278              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4279              :         // mutexes in struct Timeline in the future.
    4280            1 :         let timelines = self.list_timelines();
    4281            1 :         for timeline in timelines {
    4282            0 :             timeline.tenant_conf_updated(&updated);
    4283            0 :         }
    4284              : 
    4285            1 :         Ok(updated.tenant_conf.clone())
    4286            1 :     }
    4287              : 
    4288            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4289            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4290              : 
    4291            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4292              : 
    4293            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4294              :         // Don't hold self.timelines.lock() during the notifies.
    4295              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4296              :         // mutexes in struct Timeline in the future.
    4297            0 :         let timelines = self.list_timelines();
    4298            0 :         for timeline in timelines {
    4299            0 :             timeline.tenant_conf_updated(&new_conf);
    4300            0 :         }
    4301            0 :     }
    4302              : 
    4303          120 :     fn get_pagestream_throttle_config(
    4304          120 :         psconf: &'static PageServerConf,
    4305          120 :         overrides: &pageserver_api::models::TenantConfig,
    4306          120 :     ) -> throttle::Config {
    4307          120 :         overrides
    4308          120 :             .timeline_get_throttle
    4309          120 :             .clone()
    4310          120 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4311          120 :     }
    4312              : 
    4313            1 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4314            1 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4315            1 :         self.pagestream_throttle.reconfigure(conf)
    4316            1 :     }
    4317              : 
    4318              :     /// Helper function to create a new Timeline struct.
    4319              :     ///
    4320              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4321              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4322              :     /// map.
    4323              :     ///
    4324              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4325              :     /// and we might not have the ancestor present anymore which is fine for to be
    4326              :     /// deleted timelines.
    4327              :     #[allow(clippy::too_many_arguments)]
    4328          235 :     fn create_timeline_struct(
    4329          235 :         &self,
    4330          235 :         new_timeline_id: TimelineId,
    4331          235 :         new_metadata: &TimelineMetadata,
    4332          235 :         previous_heatmap: Option<PreviousHeatmap>,
    4333          235 :         ancestor: Option<Arc<Timeline>>,
    4334          235 :         resources: TimelineResources,
    4335          235 :         cause: CreateTimelineCause,
    4336          235 :         create_idempotency: CreateTimelineIdempotency,
    4337          235 :         gc_compaction_state: Option<GcCompactionState>,
    4338          235 :         rel_size_v2_status: Option<RelSizeMigration>,
    4339          235 :         ctx: &RequestContext,
    4340          235 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4341          235 :         let state = match cause {
    4342              :             CreateTimelineCause::Load => {
    4343          235 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4344          235 :                 anyhow::ensure!(
    4345          235 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4346            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4347              :                 );
    4348          235 :                 TimelineState::Loading
    4349              :             }
    4350            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4351              :         };
    4352              : 
    4353          235 :         let pg_version = new_metadata.pg_version();
    4354              : 
    4355          235 :         let timeline = Timeline::new(
    4356          235 :             self.conf,
    4357          235 :             Arc::clone(&self.tenant_conf),
    4358          235 :             new_metadata,
    4359          235 :             previous_heatmap,
    4360          235 :             ancestor,
    4361          235 :             new_timeline_id,
    4362          235 :             self.tenant_shard_id,
    4363          235 :             self.generation,
    4364          235 :             self.shard_identity,
    4365          235 :             self.walredo_mgr.clone(),
    4366          235 :             resources,
    4367          235 :             pg_version,
    4368          235 :             state,
    4369          235 :             self.attach_wal_lag_cooldown.clone(),
    4370          235 :             create_idempotency,
    4371          235 :             gc_compaction_state,
    4372          235 :             rel_size_v2_status,
    4373          235 :             self.cancel.child_token(),
    4374              :         );
    4375              : 
    4376          235 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4377          235 :             .scope(context::Scope::new_timeline(&timeline))
    4378          235 :             .detached_child();
    4379              : 
    4380          235 :         Ok((timeline, timeline_ctx))
    4381          235 :     }
    4382              : 
    4383              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4384              :     /// to ensure proper cleanup of background tasks and metrics.
    4385              :     //
    4386              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4387              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4388              :     #[allow(clippy::too_many_arguments)]
    4389          119 :     fn new(
    4390          119 :         state: TenantState,
    4391          119 :         conf: &'static PageServerConf,
    4392          119 :         attached_conf: AttachedTenantConf,
    4393          119 :         shard_identity: ShardIdentity,
    4394          119 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4395          119 :         tenant_shard_id: TenantShardId,
    4396          119 :         remote_storage: GenericRemoteStorage,
    4397          119 :         deletion_queue_client: DeletionQueueClient,
    4398          119 :         l0_flush_global_state: L0FlushGlobalState,
    4399          119 :         basebackup_cache: Arc<BasebackupCache>,
    4400          119 :         feature_resolver: FeatureResolver,
    4401          119 :     ) -> TenantShard {
    4402          119 :         assert!(!attached_conf.location.generation.is_none());
    4403              : 
    4404          119 :         let (state, mut rx) = watch::channel(state);
    4405              : 
    4406          119 :         tokio::spawn(async move {
    4407              :             // reflect tenant state in metrics:
    4408              :             // - global per tenant state: TENANT_STATE_METRIC
    4409              :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4410              :             //
    4411              :             // set of broken tenants should not have zero counts so that it remains accessible for
    4412              :             // alerting.
    4413              : 
    4414          119 :             let tid = tenant_shard_id.to_string();
    4415          119 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4416          119 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4417              : 
    4418          237 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4419          237 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4420          237 :             }
    4421              : 
    4422          119 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4423              : 
    4424          119 :             let is_broken = tuple.1;
    4425          119 :             let mut counted_broken = if is_broken {
    4426              :                 // add the id to the set right away, there should not be any updates on the channel
    4427              :                 // after before tenant is removed, if ever
    4428            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4429            0 :                 true
    4430              :             } else {
    4431          119 :                 false
    4432              :             };
    4433              : 
    4434              :             loop {
    4435          237 :                 let labels = &tuple.0;
    4436          237 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4437          237 :                 current.inc();
    4438              : 
    4439          237 :                 if rx.changed().await.is_err() {
    4440              :                     // tenant has been dropped
    4441            7 :                     current.dec();
    4442            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4443            7 :                     break;
    4444          118 :                 }
    4445              : 
    4446          118 :                 current.dec();
    4447          118 :                 tuple = inspect_state(&rx.borrow_and_update());
    4448              : 
    4449          118 :                 let is_broken = tuple.1;
    4450          118 :                 if is_broken && !counted_broken {
    4451            0 :                     counted_broken = true;
    4452            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4453            0 :                     // access
    4454            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4455          118 :                 }
    4456              :             }
    4457            7 :         });
    4458              : 
    4459          119 :         TenantShard {
    4460          119 :             tenant_shard_id,
    4461          119 :             shard_identity,
    4462          119 :             generation: attached_conf.location.generation,
    4463          119 :             conf,
    4464          119 :             // using now here is good enough approximation to catch tenants with really long
    4465          119 :             // activation times.
    4466          119 :             constructed_at: Instant::now(),
    4467          119 :             timelines: Mutex::new(HashMap::new()),
    4468          119 :             timelines_creating: Mutex::new(HashSet::new()),
    4469          119 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4470          119 :             timelines_importing: Mutex::new(HashMap::new()),
    4471          119 :             remote_tenant_manifest: Default::default(),
    4472          119 :             gc_cs: tokio::sync::Mutex::new(()),
    4473          119 :             walredo_mgr,
    4474          119 :             remote_storage,
    4475          119 :             deletion_queue_client,
    4476          119 :             state,
    4477          119 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4478          119 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4479          119 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4480          119 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4481          119 :                 format!("compaction-{tenant_shard_id}"),
    4482          119 :                 5,
    4483          119 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4484          119 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4485          119 :                 // use an extremely long backoff.
    4486          119 :                 Some(Duration::from_secs(3600 * 24)),
    4487          119 :             )),
    4488          119 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4489          119 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4490          119 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4491          119 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4492          119 :             cancel: CancellationToken::default(),
    4493          119 :             gate: Gate::default(),
    4494          119 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4495          119 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4496          119 :             )),
    4497          119 :             pagestream_throttle_metrics: Arc::new(
    4498          119 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4499          119 :             ),
    4500          119 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4501          119 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4502          119 :             gc_block: Default::default(),
    4503          119 :             l0_flush_global_state,
    4504          119 :             basebackup_cache,
    4505          119 :             feature_resolver: Arc::new(TenantFeatureResolver::new(
    4506          119 :                 feature_resolver,
    4507          119 :                 tenant_shard_id.tenant_id,
    4508          119 :             )),
    4509          119 :         }
    4510          119 :     }
    4511              : 
    4512              :     /// Locate and load config
    4513            0 :     pub(super) fn load_tenant_config(
    4514            0 :         conf: &'static PageServerConf,
    4515            0 :         tenant_shard_id: &TenantShardId,
    4516            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4517            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4518              : 
    4519            0 :         info!("loading tenant configuration from {config_path}");
    4520              : 
    4521              :         // load and parse file
    4522            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4523            0 :             match e.kind() {
    4524              :                 std::io::ErrorKind::NotFound => {
    4525              :                     // The config should almost always exist for a tenant directory:
    4526              :                     //  - When attaching a tenant, the config is the first thing we write
    4527              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4528              :                     //    before deleting contents.
    4529              :                     //
    4530              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4531              :                     // between creating directory and writing config.  Callers should handle that as if the
    4532              :                     // directory didn't exist.
    4533              : 
    4534            0 :                     LoadConfigError::NotFound(config_path)
    4535              :                 }
    4536              :                 _ => {
    4537              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4538              :                     // that we cannot cleanly recover
    4539            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4540              :                 }
    4541              :             }
    4542            0 :         })?;
    4543              : 
    4544            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4545            0 :     }
    4546              : 
    4547              :     /// Stores a tenant location config to disk.
    4548              :     ///
    4549              :     /// NB: make sure to call `ShardIdentity::assert_equal` before persisting a new config, to avoid
    4550              :     /// changes to shard parameters that may result in data corruption.
    4551              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4552              :     pub(super) async fn persist_tenant_config(
    4553              :         conf: &'static PageServerConf,
    4554              :         tenant_shard_id: &TenantShardId,
    4555              :         location_conf: &LocationConf,
    4556              :     ) -> std::io::Result<()> {
    4557              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4558              : 
    4559              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4560              :     }
    4561              : 
    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_at(
    4564              :         tenant_shard_id: &TenantShardId,
    4565              :         config_path: &Utf8Path,
    4566              :         location_conf: &LocationConf,
    4567              :     ) -> std::io::Result<()> {
    4568              :         debug!("persisting tenantconf to {config_path}");
    4569              : 
    4570              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4571              : #  It is read in case of pageserver restart.
    4572              : "#
    4573              :         .to_string();
    4574              : 
    4575            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4576            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4577            0 :         });
    4578              : 
    4579              :         // Convert the config to a toml file.
    4580              :         conf_content +=
    4581              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4582              : 
    4583              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4584              : 
    4585              :         let conf_content = conf_content.into_bytes();
    4586              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4587              :     }
    4588              : 
    4589              :     //
    4590              :     // How garbage collection works:
    4591              :     //
    4592              :     //                    +--bar------------->
    4593              :     //                   /
    4594              :     //             +----+-----foo---------------->
    4595              :     //            /
    4596              :     // ----main--+-------------------------->
    4597              :     //                \
    4598              :     //                 +-----baz-------->
    4599              :     //
    4600              :     //
    4601              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4602              :     //    `gc_infos` are being refreshed
    4603              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4604              :     //    all the points where other timelines have been branched off.
    4605              :     //    We will refrain from removing page versions at those LSNs.
    4606              :     // 3. For each timeline, scan all layer files on the timeline.
    4607              :     //    Remove all files for which a newer file exists and which
    4608              :     //    don't cover any branch point LSNs.
    4609              :     //
    4610              :     // TODO:
    4611              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4612              :     //   don't need to keep that in the parent anymore. But currently
    4613              :     //   we do.
    4614          377 :     async fn gc_iteration_internal(
    4615          377 :         &self,
    4616          377 :         target_timeline_id: Option<TimelineId>,
    4617          377 :         horizon: u64,
    4618          377 :         pitr: Duration,
    4619          377 :         cancel: &CancellationToken,
    4620          377 :         ctx: &RequestContext,
    4621          377 :     ) -> Result<GcResult, GcError> {
    4622          377 :         let mut totals: GcResult = Default::default();
    4623          377 :         let now = Instant::now();
    4624              : 
    4625          377 :         let gc_timelines = self
    4626          377 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4627          377 :             .await?;
    4628              : 
    4629          377 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4630              : 
    4631              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4632          377 :         if !gc_timelines.is_empty() {
    4633          377 :             info!("{} timelines need GC", gc_timelines.len());
    4634              :         } else {
    4635            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4636              :         }
    4637              : 
    4638              :         // Perform GC for each timeline.
    4639              :         //
    4640              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4641              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4642              :         // with branch creation.
    4643              :         //
    4644              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4645              :         // creation task can run concurrently with timeline's GC iteration.
    4646          754 :         for timeline in gc_timelines {
    4647          377 :             if cancel.is_cancelled() {
    4648              :                 // We were requested to shut down. Stop and return with the progress we
    4649              :                 // made.
    4650            0 :                 break;
    4651          377 :             }
    4652          377 :             let result = match timeline.gc().await {
    4653              :                 Err(GcError::TimelineCancelled) => {
    4654            0 :                     if target_timeline_id.is_some() {
    4655              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4656            0 :                         return Err(GcError::TimelineCancelled);
    4657              :                     } else {
    4658              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4659              :                         // skip past this and proceed to try GC on other timelines.
    4660            0 :                         continue;
    4661              :                     }
    4662              :                 }
    4663          377 :                 r => r?,
    4664              :             };
    4665          377 :             totals += result;
    4666              :         }
    4667              : 
    4668          377 :         totals.elapsed = now.elapsed();
    4669          377 :         Ok(totals)
    4670          377 :     }
    4671              : 
    4672              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4673              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4674              :     /// [`TenantShard::get_gc_horizon`].
    4675              :     ///
    4676              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4677            2 :     pub(crate) async fn refresh_gc_info(
    4678            2 :         &self,
    4679            2 :         cancel: &CancellationToken,
    4680            2 :         ctx: &RequestContext,
    4681            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4682              :         // since this method can now be called at different rates than the configured gc loop, it
    4683              :         // might be that these configuration values get applied faster than what it was previously,
    4684              :         // since these were only read from the gc task.
    4685            2 :         let horizon = self.get_gc_horizon();
    4686            2 :         let pitr = self.get_pitr_interval();
    4687              : 
    4688              :         // refresh all timelines
    4689            2 :         let target_timeline_id = None;
    4690              : 
    4691            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4692            2 :             .await
    4693            2 :     }
    4694              : 
    4695              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4696              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4697              :     ///
    4698              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4699          119 :     fn initialize_gc_info(
    4700          119 :         &self,
    4701          119 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4702          119 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4703          119 :         restrict_to_timeline: Option<TimelineId>,
    4704          119 :     ) {
    4705          119 :         if restrict_to_timeline.is_none() {
    4706              :             // This function must be called before activation: after activation timeline create/delete operations
    4707              :             // might happen, and this function is not safe to run concurrently with those.
    4708          119 :             assert!(!self.is_active());
    4709            0 :         }
    4710              : 
    4711              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4712              :         // the branch point where it was created.
    4713          119 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4714          119 :             BTreeMap::new();
    4715          119 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4716            3 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4717            1 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4718            1 :                 ancestor_children.push((
    4719            1 :                     timeline_entry.get_ancestor_lsn(),
    4720            1 :                     *timeline_id,
    4721            1 :                     MaybeOffloaded::No,
    4722            1 :                 ));
    4723            2 :             }
    4724            3 :         });
    4725          119 :         timelines_offloaded
    4726          119 :             .iter()
    4727          119 :             .for_each(|(timeline_id, timeline_entry)| {
    4728            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4729            0 :                     return;
    4730              :                 };
    4731            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4732            0 :                     return;
    4733              :                 };
    4734            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4735            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4736            0 :             });
    4737              : 
    4738              :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4739          119 :         let horizon = self.get_gc_horizon();
    4740              : 
    4741              :         // Populate each timeline's GcInfo with information about its child branches
    4742          119 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4743            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4744              :         } else {
    4745          119 :             itertools::Either::Right(timelines.values())
    4746              :         };
    4747          122 :         for timeline in timelines_to_write {
    4748            3 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4749            3 :                 .remove(&timeline.timeline_id)
    4750            3 :                 .unwrap_or_default();
    4751              : 
    4752            3 :             branchpoints.sort_by_key(|b| b.0);
    4753              : 
    4754            3 :             let mut target = timeline.gc_info.write().unwrap();
    4755              : 
    4756            3 :             target.retain_lsns = branchpoints;
    4757              : 
    4758            3 :             let space_cutoff = timeline
    4759            3 :                 .get_last_record_lsn()
    4760            3 :                 .checked_sub(horizon)
    4761            3 :                 .unwrap_or(Lsn(0));
    4762              : 
    4763            3 :             target.cutoffs = GcCutoffs {
    4764            3 :                 space: space_cutoff,
    4765            3 :                 time: None,
    4766            3 :             };
    4767              :         }
    4768          119 :     }
    4769              : 
    4770          379 :     async fn refresh_gc_info_internal(
    4771          379 :         &self,
    4772          379 :         target_timeline_id: Option<TimelineId>,
    4773          379 :         horizon: u64,
    4774          379 :         pitr: Duration,
    4775          379 :         cancel: &CancellationToken,
    4776          379 :         ctx: &RequestContext,
    4777          379 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4778              :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4779              :         // currently visible timelines.
    4780          379 :         let timelines = self
    4781          379 :             .timelines
    4782          379 :             .lock()
    4783          379 :             .unwrap()
    4784          379 :             .values()
    4785         1663 :             .filter(|tl| match target_timeline_id.as_ref() {
    4786         1655 :                 Some(target) => &tl.timeline_id == target,
    4787            8 :                 None => true,
    4788         1663 :             })
    4789          379 :             .cloned()
    4790          379 :             .collect::<Vec<_>>();
    4791              : 
    4792          379 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4793              :             // We were to act on a particular timeline and it wasn't found
    4794            0 :             return Err(GcError::TimelineNotFound);
    4795          379 :         }
    4796              : 
    4797          379 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4798          379 :             HashMap::with_capacity(timelines.len());
    4799              : 
    4800              :         // Ensures all timelines use the same start time when computing the time cutoff.
    4801          379 :         let now_ts_for_pitr_calc = SystemTime::now();
    4802          385 :         for timeline in timelines.iter() {
    4803          385 :             let ctx = &ctx.with_scope_timeline(timeline);
    4804          385 :             let cutoff = timeline
    4805          385 :                 .get_last_record_lsn()
    4806          385 :                 .checked_sub(horizon)
    4807          385 :                 .unwrap_or(Lsn(0));
    4808              : 
    4809          385 :             let cutoffs = timeline
    4810          385 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4811          385 :                 .await?;
    4812          385 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4813          385 :             assert!(old.is_none());
    4814              :         }
    4815              : 
    4816          379 :         if !self.is_active() || self.cancel.is_cancelled() {
    4817            0 :             return Err(GcError::TenantCancelled);
    4818          379 :         }
    4819              : 
    4820              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4821              :         // because that will stall branch creation.
    4822          379 :         let gc_cs = self.gc_cs.lock().await;
    4823              : 
    4824              :         // Ok, we now know all the branch points.
    4825              :         // Update the GC information for each timeline.
    4826          379 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4827          764 :         for timeline in timelines {
    4828              :             // We filtered the timeline list above
    4829          385 :             if let Some(target_timeline_id) = target_timeline_id {
    4830          377 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4831            8 :             }
    4832              : 
    4833              :             {
    4834          385 :                 let mut target = timeline.gc_info.write().unwrap();
    4835              : 
    4836              :                 // Cull any expired leases
    4837          385 :                 let now = SystemTime::now();
    4838          385 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4839              : 
    4840          385 :                 timeline
    4841          385 :                     .metrics
    4842          385 :                     .valid_lsn_lease_count_gauge
    4843          385 :                     .set(target.leases.len() as u64);
    4844              : 
    4845              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4846          385 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4847           56 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4848            6 :                         target.within_ancestor_pitr =
    4849            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4850           50 :                     }
    4851          329 :                 }
    4852              : 
    4853              :                 // Update metrics that depend on GC state
    4854          385 :                 timeline
    4855          385 :                     .metrics
    4856          385 :                     .archival_size
    4857          385 :                     .set(if target.within_ancestor_pitr {
    4858            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4859              :                     } else {
    4860          385 :                         0
    4861              :                     });
    4862          385 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4863          319 :                     timeline.metrics.pitr_history_size.set(
    4864          319 :                         timeline
    4865          319 :                             .get_last_record_lsn()
    4866          319 :                             .checked_sub(time_cutoff)
    4867          319 :                             .unwrap_or_default()
    4868          319 :                             .0,
    4869          319 :                     );
    4870          319 :                 }
    4871              : 
    4872              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4873              :                 // - this timeline was created while we were finding cutoffs
    4874              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4875          385 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4876          385 :                     let original_cutoffs = target.cutoffs.clone();
    4877              :                     // GC cutoffs should never go back
    4878          385 :                     target.cutoffs = GcCutoffs {
    4879          385 :                         space: cutoffs.space.max(original_cutoffs.space),
    4880          385 :                         time: cutoffs.time.max(original_cutoffs.time),
    4881          385 :                     }
    4882            0 :                 }
    4883              :             }
    4884              : 
    4885          385 :             gc_timelines.push(timeline);
    4886              :         }
    4887          379 :         drop(gc_cs);
    4888          379 :         Ok(gc_timelines)
    4889          379 :     }
    4890              : 
    4891              :     /// A substitute for `branch_timeline` for use in unit tests.
    4892              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4893              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4894              :     /// timeline background tasks are launched, except the flush loop.
    4895              :     #[cfg(test)]
    4896          119 :     async fn branch_timeline_test(
    4897          119 :         self: &Arc<Self>,
    4898          119 :         src_timeline: &Arc<Timeline>,
    4899          119 :         dst_id: TimelineId,
    4900          119 :         ancestor_lsn: Option<Lsn>,
    4901          119 :         ctx: &RequestContext,
    4902          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4903          119 :         let tl = self
    4904          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4905          119 :             .await?
    4906          117 :             .into_timeline_for_test();
    4907          117 :         tl.set_state(TimelineState::Active);
    4908          117 :         Ok(tl)
    4909          119 :     }
    4910              : 
    4911              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4912              :     #[cfg(test)]
    4913              :     #[allow(clippy::too_many_arguments)]
    4914            6 :     pub async fn branch_timeline_test_with_layers(
    4915            6 :         self: &Arc<Self>,
    4916            6 :         src_timeline: &Arc<Timeline>,
    4917            6 :         dst_id: TimelineId,
    4918            6 :         ancestor_lsn: Option<Lsn>,
    4919            6 :         ctx: &RequestContext,
    4920            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4921            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4922            6 :         end_lsn: Lsn,
    4923            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4924              :         use checks::check_valid_layermap;
    4925              :         use itertools::Itertools;
    4926              : 
    4927            6 :         let tline = self
    4928            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4929            6 :             .await?;
    4930            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4931            6 :             ancestor_lsn
    4932              :         } else {
    4933            0 :             tline.get_last_record_lsn()
    4934              :         };
    4935            6 :         assert!(end_lsn >= ancestor_lsn);
    4936            6 :         tline.force_advance_lsn(end_lsn);
    4937            9 :         for deltas in delta_layer_desc {
    4938            3 :             tline
    4939            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4940            3 :                 .await?;
    4941              :         }
    4942            8 :         for (lsn, images) in image_layer_desc {
    4943            2 :             tline
    4944            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4945            2 :                 .await?;
    4946              :         }
    4947            6 :         let layer_names = tline
    4948            6 :             .layers
    4949            6 :             .read(LayerManagerLockHolder::Testing)
    4950            6 :             .await
    4951            6 :             .layer_map()
    4952            6 :             .unwrap()
    4953            6 :             .iter_historic_layers()
    4954            6 :             .map(|layer| layer.layer_name())
    4955            6 :             .collect_vec();
    4956            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4957            0 :             bail!("invalid layermap: {err}");
    4958            6 :         }
    4959            6 :         Ok(tline)
    4960            6 :     }
    4961              : 
    4962              :     /// Branch an existing timeline.
    4963            0 :     async fn branch_timeline(
    4964            0 :         self: &Arc<Self>,
    4965            0 :         src_timeline: &Arc<Timeline>,
    4966            0 :         dst_id: TimelineId,
    4967            0 :         start_lsn: Option<Lsn>,
    4968            0 :         ctx: &RequestContext,
    4969            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4970            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4971            0 :             .await
    4972            0 :     }
    4973              : 
    4974          119 :     async fn branch_timeline_impl(
    4975          119 :         self: &Arc<Self>,
    4976          119 :         src_timeline: &Arc<Timeline>,
    4977          119 :         dst_id: TimelineId,
    4978          119 :         start_lsn: Option<Lsn>,
    4979          119 :         ctx: &RequestContext,
    4980          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4981          119 :         let src_id = src_timeline.timeline_id;
    4982              : 
    4983              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4984              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4985              :         // valid while we are creating the branch.
    4986          119 :         let _gc_cs = self.gc_cs.lock().await;
    4987              : 
    4988              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4989          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4990            1 :             let lsn = src_timeline.get_last_record_lsn();
    4991            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4992            1 :             lsn
    4993            1 :         });
    4994              : 
    4995              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4996          119 :         let timeline_create_guard = match self
    4997          119 :             .start_creating_timeline(
    4998          119 :                 dst_id,
    4999          119 :                 CreateTimelineIdempotency::Branch {
    5000          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    5001          119 :                     ancestor_start_lsn: start_lsn,
    5002          119 :                 },
    5003          119 :             )
    5004          119 :             .await?
    5005              :         {
    5006          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5007            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5008            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5009              :             }
    5010              :         };
    5011              : 
    5012              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    5013              :         // horizon on the source timeline
    5014              :         //
    5015              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    5016              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    5017              :         // planned GC cutoff in 'gc_info' is normally larger than
    5018              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    5019              :         // changed the GC settings for the tenant to make the PITR window
    5020              :         // larger, but some of the data was already removed by an earlier GC
    5021              :         // iteration.
    5022              : 
    5023              :         // check against last actual 'latest_gc_cutoff' first
    5024          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    5025              :         {
    5026          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    5027          119 :             let planned_cutoff = gc_info.min_cutoff();
    5028          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    5029            0 :                 tracing::info!(
    5030            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    5031            0 :                     *applied_gc_cutoff_lsn
    5032              :                 );
    5033              :             } else {
    5034          119 :                 src_timeline
    5035          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    5036          119 :                     .context(format!(
    5037          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    5038          119 :                         *applied_gc_cutoff_lsn,
    5039              :                     ))
    5040          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    5041              : 
    5042              :                 // and then the planned GC cutoff
    5043          117 :                 if start_lsn < planned_cutoff {
    5044            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    5045            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    5046            0 :                     )));
    5047          117 :                 }
    5048              :             }
    5049              :         }
    5050              : 
    5051              :         //
    5052              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    5053              :         // so that GC cannot advance the GC cutoff until we are finished.
    5054              :         // Proceed with the branch creation.
    5055              :         //
    5056              : 
    5057              :         // Determine prev-LSN for the new timeline. We can only determine it if
    5058              :         // the timeline was branched at the current end of the source timeline.
    5059              :         let RecordLsn {
    5060          117 :             last: src_last,
    5061          117 :             prev: src_prev,
    5062          117 :         } = src_timeline.get_last_record_rlsn();
    5063          117 :         let dst_prev = if src_last == start_lsn {
    5064          108 :             Some(src_prev)
    5065              :         } else {
    5066            9 :             None
    5067              :         };
    5068              : 
    5069              :         // Create the metadata file, noting the ancestor of the new timeline.
    5070              :         // There is initially no data in it, but all the read-calls know to look
    5071              :         // into the ancestor.
    5072          117 :         let metadata = TimelineMetadata::new(
    5073          117 :             start_lsn,
    5074          117 :             dst_prev,
    5075          117 :             Some(src_id),
    5076          117 :             start_lsn,
    5077          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    5078          117 :             src_timeline.initdb_lsn,
    5079          117 :             src_timeline.pg_version,
    5080              :         );
    5081              : 
    5082          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    5083          117 :             .prepare_new_timeline(
    5084          117 :                 dst_id,
    5085          117 :                 &metadata,
    5086          117 :                 timeline_create_guard,
    5087          117 :                 start_lsn + 1,
    5088          117 :                 Some(Arc::clone(src_timeline)),
    5089          117 :                 Some(src_timeline.get_rel_size_v2_status()),
    5090          117 :                 ctx,
    5091          117 :             )
    5092          117 :             .await?;
    5093              : 
    5094          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    5095              : 
    5096              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    5097              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    5098              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    5099              :         // could get incorrect information and remove more layers, than needed.
    5100              :         // See also https://github.com/neondatabase/neon/issues/3865
    5101          117 :         new_timeline
    5102          117 :             .remote_client
    5103          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    5104          117 :             .context("branch initial metadata upload")?;
    5105              : 
    5106              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5107              : 
    5108          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    5109          119 :     }
    5110              : 
    5111              :     /// For unit tests, make this visible so that other modules can directly create timelines
    5112              :     #[cfg(test)]
    5113              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    5114              :     pub(crate) async fn bootstrap_timeline_test(
    5115              :         self: &Arc<Self>,
    5116              :         timeline_id: TimelineId,
    5117              :         pg_version: PgMajorVersion,
    5118              :         load_existing_initdb: Option<TimelineId>,
    5119              :         ctx: &RequestContext,
    5120              :     ) -> anyhow::Result<Arc<Timeline>> {
    5121              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    5122              :             .await
    5123              :             .map_err(anyhow::Error::new)
    5124            1 :             .map(|r| r.into_timeline_for_test())
    5125              :     }
    5126              : 
    5127              :     /// Get exclusive access to the timeline ID for creation.
    5128              :     ///
    5129              :     /// Timeline-creating code paths must use this function before making changes
    5130              :     /// to in-memory or persistent state.
    5131              :     ///
    5132              :     /// The `state` parameter is a description of the timeline creation operation
    5133              :     /// we intend to perform.
    5134              :     /// If the timeline was already created in the meantime, we check whether this
    5135              :     /// request conflicts or is idempotent , based on `state`.
    5136          235 :     async fn start_creating_timeline(
    5137          235 :         self: &Arc<Self>,
    5138          235 :         new_timeline_id: TimelineId,
    5139          235 :         idempotency: CreateTimelineIdempotency,
    5140          235 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    5141          235 :         let allow_offloaded = false;
    5142          235 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    5143          234 :             Ok(create_guard) => {
    5144          234 :                 pausable_failpoint!("timeline-creation-after-uninit");
    5145          234 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    5146              :             }
    5147            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    5148              :             Err(TimelineExclusionError::AlreadyCreating) => {
    5149              :                 // Creation is in progress, we cannot create it again, and we cannot
    5150              :                 // check if this request matches the existing one, so caller must try
    5151              :                 // again later.
    5152            0 :                 Err(CreateTimelineError::AlreadyCreating)
    5153              :             }
    5154            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    5155              :             Err(TimelineExclusionError::AlreadyExists {
    5156            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5157              :                 ..
    5158              :             }) => {
    5159            0 :                 info!("timeline already exists but is offloaded");
    5160            0 :                 Err(CreateTimelineError::Conflict)
    5161              :             }
    5162              :             Err(TimelineExclusionError::AlreadyExists {
    5163            0 :                 existing: TimelineOrOffloaded::Importing(_existing),
    5164              :                 ..
    5165              :             }) => {
    5166              :                 // If there's a timeline already importing, then we would hit
    5167              :                 // the [`TimelineExclusionError::AlreadyCreating`] branch above.
    5168            0 :                 unreachable!("Importing timelines hold the creation guard")
    5169              :             }
    5170              :             Err(TimelineExclusionError::AlreadyExists {
    5171            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5172            1 :                 arg,
    5173              :             }) => {
    5174              :                 {
    5175            1 :                     let existing = &existing.create_idempotency;
    5176            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5177            1 :                     debug!("timeline already exists");
    5178              : 
    5179            1 :                     match (existing, &arg) {
    5180              :                         // FailWithConflict => no idempotency check
    5181              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5182              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5183            1 :                             warn!("timeline already exists, failing request");
    5184            1 :                             return Err(CreateTimelineError::Conflict);
    5185              :                         }
    5186              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5187            0 :                         (x, y) if x == y => {
    5188            0 :                             info!(
    5189            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5190              :                             );
    5191              :                             // fallthrough
    5192              :                         }
    5193              :                         (_, _) => {
    5194            0 :                             warn!("idempotency conflict, failing request");
    5195            0 :                             return Err(CreateTimelineError::Conflict);
    5196              :                         }
    5197              :                     }
    5198              :                 }
    5199              : 
    5200            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5201              :             }
    5202              :         }
    5203          235 :     }
    5204              : 
    5205            0 :     async fn upload_initdb(
    5206            0 :         &self,
    5207            0 :         timelines_path: &Utf8PathBuf,
    5208            0 :         pgdata_path: &Utf8PathBuf,
    5209            0 :         timeline_id: &TimelineId,
    5210            0 :     ) -> anyhow::Result<()> {
    5211            0 :         let temp_path = timelines_path.join(format!(
    5212            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5213            0 :         ));
    5214              : 
    5215            0 :         scopeguard::defer! {
    5216              :             if let Err(e) = fs::remove_file(&temp_path) {
    5217              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5218              :             }
    5219              :         }
    5220              : 
    5221            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5222              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5223            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5224            0 :             warn!(
    5225            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5226              :             );
    5227            0 :         }
    5228              : 
    5229            0 :         pausable_failpoint!("before-initdb-upload");
    5230              : 
    5231            0 :         backoff::retry(
    5232            0 :             || async {
    5233            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5234            0 :                     &self.remote_storage,
    5235            0 :                     &self.tenant_shard_id.tenant_id,
    5236            0 :                     timeline_id,
    5237            0 :                     pgdata_zstd.try_clone().await?,
    5238            0 :                     tar_zst_size,
    5239            0 :                     &self.cancel,
    5240              :                 )
    5241            0 :                 .await
    5242            0 :             },
    5243              :             |_| false,
    5244              :             3,
    5245              :             u32::MAX,
    5246            0 :             "persist_initdb_tar_zst",
    5247            0 :             &self.cancel,
    5248              :         )
    5249            0 :         .await
    5250            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5251            0 :         .and_then(|x| x)
    5252            0 :     }
    5253              : 
    5254              :     /// - run initdb to init temporary instance and get bootstrap data
    5255              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5256            1 :     async fn bootstrap_timeline(
    5257            1 :         self: &Arc<Self>,
    5258            1 :         timeline_id: TimelineId,
    5259            1 :         pg_version: PgMajorVersion,
    5260            1 :         load_existing_initdb: Option<TimelineId>,
    5261            1 :         ctx: &RequestContext,
    5262            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5263            1 :         let timeline_create_guard = match self
    5264            1 :             .start_creating_timeline(
    5265            1 :                 timeline_id,
    5266            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5267            1 :             )
    5268            1 :             .await?
    5269              :         {
    5270            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5271            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5272            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5273              :             }
    5274              :         };
    5275              : 
    5276              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5277              :         // temporary directory for basebackup files for the given timeline.
    5278              : 
    5279            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5280            1 :         let pgdata_path = path_with_suffix_extension(
    5281            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5282            1 :             TEMP_FILE_SUFFIX,
    5283              :         );
    5284              : 
    5285              :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5286              :         // we won't race with other creations or existent timelines with the same path.
    5287            1 :         if pgdata_path.exists() {
    5288            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5289            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5290            0 :             })?;
    5291            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5292            1 :         }
    5293              : 
    5294              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5295            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5296            1 :         scopeguard::defer! {
    5297              :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5298              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5299              :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5300              :             } else {
    5301              :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5302              :             }
    5303              :         }
    5304            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5305            1 :             if existing_initdb_timeline_id != timeline_id {
    5306            0 :                 let source_path = &remote_initdb_archive_path(
    5307            0 :                     &self.tenant_shard_id.tenant_id,
    5308            0 :                     &existing_initdb_timeline_id,
    5309            0 :                 );
    5310            0 :                 let dest_path =
    5311            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5312              : 
    5313              :                 // if this fails, it will get retried by retried control plane requests
    5314            0 :                 self.remote_storage
    5315            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5316            0 :                     .await
    5317            0 :                     .context("copy initdb tar")?;
    5318            1 :             }
    5319            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5320            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5321            1 :                     self.conf,
    5322            1 :                     &self.remote_storage,
    5323            1 :                     &self.tenant_shard_id,
    5324            1 :                     &existing_initdb_timeline_id,
    5325            1 :                     &self.cancel,
    5326            1 :                 )
    5327            1 :                 .await
    5328            1 :                 .context("download initdb tar")?;
    5329              : 
    5330            1 :             scopeguard::defer! {
    5331              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5332              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5333              :                 }
    5334              :             }
    5335              : 
    5336            1 :             let buf_read =
    5337            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5338            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5339            1 :                 .await
    5340            1 :                 .context("extract initdb tar")?;
    5341              :         } else {
    5342              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5343            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5344            0 :                 .await
    5345            0 :                 .context("run initdb")?;
    5346              : 
    5347              :             // Upload the created data dir to S3
    5348            0 :             if self.tenant_shard_id().is_shard_zero() {
    5349            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5350            0 :                     .await?;
    5351            0 :             }
    5352              :         }
    5353            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5354              : 
    5355              :         // Import the contents of the data directory at the initial checkpoint
    5356              :         // LSN, and any WAL after that.
    5357              :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5358              :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5359            1 :         let new_metadata = TimelineMetadata::new(
    5360            1 :             Lsn(0),
    5361            1 :             None,
    5362            1 :             None,
    5363            1 :             Lsn(0),
    5364            1 :             pgdata_lsn,
    5365            1 :             pgdata_lsn,
    5366            1 :             pg_version,
    5367              :         );
    5368            1 :         let (mut raw_timeline, timeline_ctx) = self
    5369            1 :             .prepare_new_timeline(
    5370            1 :                 timeline_id,
    5371            1 :                 &new_metadata,
    5372            1 :                 timeline_create_guard,
    5373            1 :                 pgdata_lsn,
    5374            1 :                 None,
    5375            1 :                 None,
    5376            1 :                 ctx,
    5377            1 :             )
    5378            1 :             .await?;
    5379              : 
    5380            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5381            1 :         raw_timeline
    5382            1 :             .write(|unfinished_timeline| async move {
    5383            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5384            1 :                     &unfinished_timeline,
    5385            1 :                     &pgdata_path,
    5386            1 :                     pgdata_lsn,
    5387            1 :                     &timeline_ctx,
    5388            1 :                 )
    5389            1 :                 .await
    5390            1 :                 .with_context(|| {
    5391            0 :                     format!(
    5392            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5393              :                     )
    5394            0 :                 })?;
    5395              : 
    5396            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5397            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5398            0 :                         "failpoint before-checkpoint-new-timeline"
    5399            0 :                     )))
    5400            0 :                 });
    5401              : 
    5402            1 :                 Ok(())
    5403            2 :             })
    5404            1 :             .await?;
    5405              : 
    5406              :         // All done!
    5407            1 :         let timeline = raw_timeline.finish_creation().await?;
    5408              : 
    5409              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5410              : 
    5411            1 :         Ok(CreateTimelineResult::Created(timeline))
    5412            1 :     }
    5413              : 
    5414          232 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5415          232 :         RemoteTimelineClient::new(
    5416          232 :             self.remote_storage.clone(),
    5417          232 :             self.deletion_queue_client.clone(),
    5418          232 :             self.conf,
    5419          232 :             self.tenant_shard_id,
    5420          232 :             timeline_id,
    5421          232 :             self.generation,
    5422          232 :             &self.tenant_conf.load().location,
    5423              :         )
    5424          232 :     }
    5425              : 
    5426              :     /// Builds required resources for a new timeline.
    5427          232 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5428          232 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5429          232 :         self.get_timeline_resources_for(remote_client)
    5430          232 :     }
    5431              : 
    5432              :     /// Builds timeline resources for the given remote client.
    5433          235 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5434          235 :         TimelineResources {
    5435          235 :             remote_client,
    5436          235 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5437          235 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5438          235 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5439          235 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5440          235 :             basebackup_cache: self.basebackup_cache.clone(),
    5441          235 :             feature_resolver: self.feature_resolver.clone(),
    5442          235 :         }
    5443          235 :     }
    5444              : 
    5445              :     /// Creates intermediate timeline structure and its files.
    5446              :     ///
    5447              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5448              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5449              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5450              :     #[allow(clippy::too_many_arguments)]
    5451          232 :     async fn prepare_new_timeline<'a>(
    5452          232 :         &'a self,
    5453          232 :         new_timeline_id: TimelineId,
    5454          232 :         new_metadata: &TimelineMetadata,
    5455          232 :         create_guard: TimelineCreateGuard,
    5456          232 :         start_lsn: Lsn,
    5457          232 :         ancestor: Option<Arc<Timeline>>,
    5458          232 :         rel_size_v2_status: Option<RelSizeMigration>,
    5459          232 :         ctx: &RequestContext,
    5460          232 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5461          232 :         let tenant_shard_id = self.tenant_shard_id;
    5462              : 
    5463          232 :         let resources = self.build_timeline_resources(new_timeline_id);
    5464          232 :         resources
    5465          232 :             .remote_client
    5466          232 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5467              : 
    5468          232 :         let (timeline_struct, timeline_ctx) = self
    5469          232 :             .create_timeline_struct(
    5470          232 :                 new_timeline_id,
    5471          232 :                 new_metadata,
    5472          232 :                 None,
    5473          232 :                 ancestor,
    5474          232 :                 resources,
    5475          232 :                 CreateTimelineCause::Load,
    5476          232 :                 create_guard.idempotency.clone(),
    5477          232 :                 None,
    5478          232 :                 rel_size_v2_status,
    5479          232 :                 ctx,
    5480              :             )
    5481          232 :             .context("Failed to create timeline data structure")?;
    5482              : 
    5483          232 :         timeline_struct.init_empty_layer_map(start_lsn);
    5484              : 
    5485          232 :         if let Err(e) = self
    5486          232 :             .create_timeline_files(&create_guard.timeline_path)
    5487          232 :             .await
    5488              :         {
    5489            0 :             error!(
    5490            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5491              :             );
    5492            0 :             cleanup_timeline_directory(create_guard);
    5493            0 :             return Err(e);
    5494          232 :         }
    5495              : 
    5496          232 :         debug!(
    5497            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5498              :         );
    5499              : 
    5500          232 :         Ok((
    5501          232 :             UninitializedTimeline::new(
    5502          232 :                 self,
    5503          232 :                 new_timeline_id,
    5504          232 :                 Some((timeline_struct, create_guard)),
    5505          232 :             ),
    5506          232 :             timeline_ctx,
    5507          232 :         ))
    5508          232 :     }
    5509              : 
    5510          232 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5511          232 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5512              : 
    5513          232 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5514            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5515            0 :         });
    5516              : 
    5517          232 :         Ok(())
    5518          232 :     }
    5519              : 
    5520              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5521              :     /// concurrent attempts to create the same timeline.
    5522              :     ///
    5523              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5524              :     /// offloaded timelines or not.
    5525          235 :     fn create_timeline_create_guard(
    5526          235 :         self: &Arc<Self>,
    5527          235 :         timeline_id: TimelineId,
    5528          235 :         idempotency: CreateTimelineIdempotency,
    5529          235 :         allow_offloaded: bool,
    5530          235 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5531          235 :         let tenant_shard_id = self.tenant_shard_id;
    5532              : 
    5533          235 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5534              : 
    5535          235 :         let create_guard = TimelineCreateGuard::new(
    5536          235 :             self,
    5537          235 :             timeline_id,
    5538          235 :             timeline_path.clone(),
    5539          235 :             idempotency,
    5540          235 :             allow_offloaded,
    5541            1 :         )?;
    5542              : 
    5543              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5544              :         // for creation.
    5545              :         // A timeline directory should never exist on disk already:
    5546              :         // - a previous failed creation would have cleaned up after itself
    5547              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5548              :         //
    5549              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5550              :         // this error may indicate a bug in cleanup on failed creations.
    5551          234 :         if timeline_path.exists() {
    5552            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5553            0 :                 "Timeline directory already exists! This is a bug."
    5554            0 :             )));
    5555          234 :         }
    5556              : 
    5557          234 :         Ok(create_guard)
    5558          235 :     }
    5559              : 
    5560              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5561              :     ///
    5562              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5563              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5564              :     pub async fn gather_size_inputs(
    5565              :         &self,
    5566              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5567              :         // (only if it is shorter than the real cutoff).
    5568              :         max_retention_period: Option<u64>,
    5569              :         cause: LogicalSizeCalculationCause,
    5570              :         cancel: &CancellationToken,
    5571              :         ctx: &RequestContext,
    5572              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5573              :         let logical_sizes_at_once = self
    5574              :             .conf
    5575              :             .concurrent_tenant_size_logical_size_queries
    5576              :             .inner();
    5577              : 
    5578              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5579              :         //
    5580              :         // But the only case where we need to run multiple of these at once is when we
    5581              :         // request a size for a tenant manually via API, while another background calculation
    5582              :         // is in progress (which is not a common case).
    5583              :         //
    5584              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5585              :         let mut shared_cache = tokio::select! {
    5586              :             locked = self.cached_logical_sizes.lock() => locked,
    5587              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5588              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5589              :         };
    5590              : 
    5591              :         size::gather_inputs(
    5592              :             self,
    5593              :             logical_sizes_at_once,
    5594              :             max_retention_period,
    5595              :             &mut shared_cache,
    5596              :             cause,
    5597              :             cancel,
    5598              :             ctx,
    5599              :         )
    5600              :         .await
    5601              :     }
    5602              : 
    5603              :     /// Calculate synthetic tenant size and cache the result.
    5604              :     /// This is periodically called by background worker.
    5605              :     /// result is cached in tenant struct
    5606              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5607              :     pub async fn calculate_synthetic_size(
    5608              :         &self,
    5609              :         cause: LogicalSizeCalculationCause,
    5610              :         cancel: &CancellationToken,
    5611              :         ctx: &RequestContext,
    5612              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5613              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5614              : 
    5615              :         let size = inputs.calculate();
    5616              : 
    5617              :         self.set_cached_synthetic_size(size);
    5618              : 
    5619              :         Ok(size)
    5620              :     }
    5621              : 
    5622              :     /// Cache given synthetic size and update the metric value
    5623            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5624            0 :         self.cached_synthetic_tenant_size
    5625            0 :             .store(size, Ordering::Relaxed);
    5626              : 
    5627              :         // Only shard zero should be calculating synthetic sizes
    5628            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5629              : 
    5630            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5631            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5632            0 :             .unwrap()
    5633            0 :             .set(size);
    5634            0 :     }
    5635              : 
    5636            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5637            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5638            0 :     }
    5639              : 
    5640              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5641              :     ///
    5642              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5643              :     /// from an external API handler.
    5644              :     ///
    5645              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5646              :     /// still bounded by tenant/timeline shutdown.
    5647              :     #[tracing::instrument(skip_all)]
    5648              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5649              :         let timelines = self.timelines.lock().unwrap().clone();
    5650              : 
    5651            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5652            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5653            0 :             timeline.freeze_and_flush().await?;
    5654            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5655            0 :             timeline.remote_client.wait_completion().await?;
    5656              : 
    5657            0 :             Ok(())
    5658            0 :         }
    5659              : 
    5660              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5661              :         // aborted when this function's future is cancelled: they should stay alive
    5662              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5663              :         // before Timeline shutdown completes.
    5664              :         let mut results = FuturesUnordered::new();
    5665              : 
    5666              :         for (_timeline_id, timeline) in timelines {
    5667              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5668              :             // means that if this function's future is cancelled, the Timeline shutdown
    5669              :             // will still wait for any I/O in here to complete.
    5670              :             let Ok(gate) = timeline.gate.enter() else {
    5671              :                 continue;
    5672              :             };
    5673            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5674              :             results.push(jh);
    5675              :         }
    5676              : 
    5677              :         while let Some(r) = results.next().await {
    5678              :             if let Err(e) = r {
    5679              :                 if !e.is_cancelled() && !e.is_panic() {
    5680              :                     tracing::error!("unexpected join error: {e:?}");
    5681              :                 }
    5682              :             }
    5683              :         }
    5684              : 
    5685              :         // The flushes we did above were just writes, but the TenantShard might have had
    5686              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5687              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5688              :         // because it's typically a no-op.
    5689              :         match self.deletion_queue_client.flush_execute().await {
    5690              :             Ok(_) => {}
    5691              :             Err(DeletionQueueError::ShuttingDown) => {}
    5692              :         }
    5693              : 
    5694              :         Ok(())
    5695              :     }
    5696              : 
    5697            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5698            0 :         self.tenant_conf.load().tenant_conf.clone()
    5699            0 :     }
    5700              : 
    5701              :     /// How much local storage would this tenant like to have?  It can cope with
    5702              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5703              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5704              :     /// by keeping important things on local disk.
    5705              :     ///
    5706              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5707              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5708              :     /// actually use more than they report here.
    5709            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5710            0 :         let timelines = self.timelines.lock().unwrap();
    5711              : 
    5712              :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5713              :         // reflects the observation that on tenants with multiple large branches, typically only one
    5714              :         // of them is used actively enough to occupy space on disk.
    5715            0 :         timelines
    5716            0 :             .values()
    5717            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5718            0 :             .max()
    5719            0 :             .unwrap_or(0)
    5720            0 :     }
    5721              : 
    5722              :     /// HADRON
    5723              :     /// Return the visible size of all timelines in this tenant.
    5724            0 :     pub(crate) fn get_visible_size(&self) -> u64 {
    5725            0 :         let timelines = self.timelines.lock().unwrap();
    5726            0 :         timelines
    5727            0 :             .values()
    5728            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5729            0 :             .sum()
    5730            0 :     }
    5731              : 
    5732              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5733              :     /// manifest in `Self::remote_tenant_manifest`.
    5734              :     ///
    5735              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5736              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5737              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5738              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5739          120 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5740              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5741              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5742              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5743              :         // simple coalescing mechanism.
    5744          120 :         let mut guard = tokio::select! {
    5745          120 :             guard = self.remote_tenant_manifest.lock() => guard,
    5746          120 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5747              :         };
    5748              : 
    5749              :         // Build a new manifest.
    5750          120 :         let manifest = self.build_tenant_manifest();
    5751              : 
    5752              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5753              :         // uploading every manifest on version number bumps.
    5754          120 :         if let Some(old) = guard.as_ref() {
    5755            4 :             if manifest.eq_ignoring_version(old) {
    5756            3 :                 return Ok(());
    5757            1 :             }
    5758          116 :         }
    5759              : 
    5760              :         // Update metrics
    5761          117 :         let tid = self.tenant_shard_id.to_string();
    5762          117 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5763          117 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5764          117 :         TENANT_OFFLOADED_TIMELINES
    5765          117 :             .with_label_values(set_key)
    5766          117 :             .set(manifest.offloaded_timelines.len() as u64);
    5767              : 
    5768              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5769          117 :         match backoff::retry(
    5770          117 :             || async {
    5771          117 :                 upload_tenant_manifest(
    5772          117 :                     &self.remote_storage,
    5773          117 :                     &self.tenant_shard_id,
    5774          117 :                     self.generation,
    5775          117 :                     &manifest,
    5776          117 :                     &self.cancel,
    5777          117 :                 )
    5778          117 :                 .await
    5779          234 :             },
    5780            0 :             |_| self.cancel.is_cancelled(),
    5781              :             FAILED_UPLOAD_WARN_THRESHOLD,
    5782              :             FAILED_REMOTE_OP_RETRIES,
    5783          117 :             "uploading tenant manifest",
    5784          117 :             &self.cancel,
    5785              :         )
    5786          117 :         .await
    5787              :         {
    5788            0 :             None => Err(TenantManifestError::Cancelled),
    5789            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5790            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5791              :             Some(Ok(_)) => {
    5792              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5793              :                 // re-uploading the same thing.
    5794          117 :                 *guard = Some(manifest);
    5795              : 
    5796          117 :                 Ok(())
    5797              :             }
    5798              :         }
    5799          120 :     }
    5800              : }
    5801              : 
    5802              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5803              : /// to get bootstrap data for timeline initialization.
    5804            0 : async fn run_initdb(
    5805            0 :     conf: &'static PageServerConf,
    5806            0 :     initdb_target_dir: &Utf8Path,
    5807            0 :     pg_version: PgMajorVersion,
    5808            0 :     cancel: &CancellationToken,
    5809            0 : ) -> Result<(), InitdbError> {
    5810            0 :     let initdb_bin_path = conf
    5811            0 :         .pg_bin_dir(pg_version)
    5812            0 :         .map_err(InitdbError::Other)?
    5813            0 :         .join("initdb");
    5814            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5815            0 :     info!(
    5816            0 :         "running {} in {}, libdir: {}",
    5817              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5818              :     );
    5819              : 
    5820            0 :     let _permit = {
    5821            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5822            0 :         INIT_DB_SEMAPHORE.acquire().await
    5823              :     };
    5824              : 
    5825            0 :     CONCURRENT_INITDBS.inc();
    5826            0 :     scopeguard::defer! {
    5827              :         CONCURRENT_INITDBS.dec();
    5828              :     }
    5829              : 
    5830            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5831            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5832            0 :         superuser: &conf.superuser,
    5833            0 :         locale: &conf.locale,
    5834            0 :         initdb_bin: &initdb_bin_path,
    5835            0 :         pg_version,
    5836            0 :         library_search_path: &initdb_lib_dir,
    5837            0 :         pgdata: initdb_target_dir,
    5838            0 :     })
    5839            0 :     .await
    5840            0 :     .map_err(InitdbError::Inner);
    5841              : 
    5842              :     // This isn't true cancellation support, see above. Still return an error to
    5843              :     // excercise the cancellation code path.
    5844            0 :     if cancel.is_cancelled() {
    5845            0 :         return Err(InitdbError::Cancelled);
    5846            0 :     }
    5847              : 
    5848            0 :     res
    5849            0 : }
    5850              : 
    5851              : /// Dump contents of a layer file to stdout.
    5852            0 : pub async fn dump_layerfile_from_path(
    5853            0 :     path: &Utf8Path,
    5854            0 :     verbose: bool,
    5855            0 :     ctx: &RequestContext,
    5856            0 : ) -> anyhow::Result<()> {
    5857              :     use std::os::unix::fs::FileExt;
    5858              : 
    5859              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5860              :     // file.
    5861            0 :     let file = File::open(path)?;
    5862            0 :     let mut header_buf = [0u8; 2];
    5863            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5864              : 
    5865            0 :     match u16::from_be_bytes(header_buf) {
    5866              :         crate::IMAGE_FILE_MAGIC => {
    5867            0 :             ImageLayer::new_for_path(path, file)?
    5868            0 :                 .dump(verbose, ctx)
    5869            0 :                 .await?
    5870              :         }
    5871              :         crate::DELTA_FILE_MAGIC => {
    5872            0 :             DeltaLayer::new_for_path(path, file)?
    5873            0 :                 .dump(verbose, ctx)
    5874            0 :                 .await?
    5875              :         }
    5876            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5877              :     }
    5878              : 
    5879            0 :     Ok(())
    5880            0 : }
    5881              : 
    5882              : #[cfg(test)]
    5883              : pub(crate) mod harness {
    5884              :     use bytes::{Bytes, BytesMut};
    5885              :     use hex_literal::hex;
    5886              :     use once_cell::sync::OnceCell;
    5887              :     use pageserver_api::key::Key;
    5888              :     use pageserver_api::models::ShardParameters;
    5889              :     use pageserver_api::shard::ShardIndex;
    5890              :     use utils::id::TenantId;
    5891              :     use utils::logging;
    5892              :     use wal_decoder::models::record::NeonWalRecord;
    5893              : 
    5894              :     use super::*;
    5895              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5896              :     use crate::l0_flush::L0FlushConfig;
    5897              :     use crate::walredo::apply_neon;
    5898              : 
    5899              :     pub const TIMELINE_ID: TimelineId =
    5900              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5901              :     pub const NEW_TIMELINE_ID: TimelineId =
    5902              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5903              : 
    5904              :     /// Convenience function to create a page image with given string as the only content
    5905      2514427 :     pub fn test_img(s: &str) -> Bytes {
    5906      2514427 :         let mut buf = BytesMut::new();
    5907      2514427 :         buf.extend_from_slice(s.as_bytes());
    5908      2514427 :         buf.resize(64, 0);
    5909              : 
    5910      2514427 :         buf.freeze()
    5911      2514427 :     }
    5912              : 
    5913              :     pub struct TenantHarness {
    5914              :         pub conf: &'static PageServerConf,
    5915              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5916              :         pub tenant_shard_id: TenantShardId,
    5917              :         pub shard_identity: ShardIdentity,
    5918              :         pub generation: Generation,
    5919              :         pub shard: ShardIndex,
    5920              :         pub remote_storage: GenericRemoteStorage,
    5921              :         pub remote_fs_dir: Utf8PathBuf,
    5922              :         pub deletion_queue: MockDeletionQueue,
    5923              :     }
    5924              : 
    5925              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5926              : 
    5927          131 :     pub(crate) fn setup_logging() {
    5928          131 :         LOG_HANDLE.get_or_init(|| {
    5929          125 :             logging::init(
    5930          125 :                 logging::LogFormat::Test,
    5931              :                 // enable it in case the tests exercise code paths that use
    5932              :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5933          125 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5934          125 :                 logging::Output::Stdout,
    5935              :             )
    5936          125 :             .expect("Failed to init test logging");
    5937          125 :         });
    5938          131 :     }
    5939              : 
    5940              :     impl TenantHarness {
    5941          119 :         pub async fn create_custom(
    5942          119 :             test_name: &'static str,
    5943          119 :             tenant_conf: pageserver_api::models::TenantConfig,
    5944          119 :             tenant_id: TenantId,
    5945          119 :             shard_identity: ShardIdentity,
    5946          119 :             generation: Generation,
    5947          119 :         ) -> anyhow::Result<Self> {
    5948          119 :             setup_logging();
    5949              : 
    5950          119 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5951          119 :             let _ = fs::remove_dir_all(&repo_dir);
    5952          119 :             fs::create_dir_all(&repo_dir)?;
    5953              : 
    5954          119 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5955              :             // Make a static copy of the config. This can never be free'd, but that's
    5956              :             // OK in a test.
    5957          119 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5958              : 
    5959          119 :             let shard = shard_identity.shard_index();
    5960          119 :             let tenant_shard_id = TenantShardId {
    5961          119 :                 tenant_id,
    5962          119 :                 shard_number: shard.shard_number,
    5963          119 :                 shard_count: shard.shard_count,
    5964          119 :             };
    5965          119 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5966          119 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5967              : 
    5968              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5969          119 :             let remote_fs_dir = conf.workdir.join("localfs");
    5970          119 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5971          119 :             let config = RemoteStorageConfig {
    5972          119 :                 storage: RemoteStorageKind::LocalFs {
    5973          119 :                     local_path: remote_fs_dir.clone(),
    5974          119 :                 },
    5975          119 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5976          119 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5977          119 :             };
    5978          119 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5979          119 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5980              : 
    5981          119 :             Ok(Self {
    5982          119 :                 conf,
    5983          119 :                 tenant_conf,
    5984          119 :                 tenant_shard_id,
    5985          119 :                 shard_identity,
    5986          119 :                 generation,
    5987          119 :                 shard,
    5988          119 :                 remote_storage,
    5989          119 :                 remote_fs_dir,
    5990          119 :                 deletion_queue,
    5991          119 :             })
    5992          119 :         }
    5993              : 
    5994          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5995              :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5996              :             // The tests perform them manually if needed.
    5997          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5998          110 :                 gc_period: Some(Duration::ZERO),
    5999          110 :                 compaction_period: Some(Duration::ZERO),
    6000          110 :                 ..Default::default()
    6001          110 :             };
    6002          110 :             let tenant_id = TenantId::generate();
    6003          110 :             let shard = ShardIdentity::unsharded();
    6004          110 :             Self::create_custom(
    6005          110 :                 test_name,
    6006          110 :                 tenant_conf,
    6007          110 :                 tenant_id,
    6008          110 :                 shard,
    6009          110 :                 Generation::new(0xdeadbeef),
    6010          110 :             )
    6011          110 :             .await
    6012          110 :         }
    6013              : 
    6014           10 :         pub fn span(&self) -> tracing::Span {
    6015           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    6016           10 :         }
    6017              : 
    6018          119 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    6019          119 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    6020          119 :                 .with_scope_unit_test();
    6021              :             (
    6022          119 :                 self.do_try_load(&ctx)
    6023          119 :                     .await
    6024          119 :                     .expect("failed to load test tenant"),
    6025          119 :                 ctx,
    6026              :             )
    6027          119 :         }
    6028              : 
    6029              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    6030              :         pub(crate) async fn do_try_load_with_redo(
    6031              :             &self,
    6032              :             walredo_mgr: Arc<WalRedoManager>,
    6033              :             ctx: &RequestContext,
    6034              :         ) -> anyhow::Result<Arc<TenantShard>> {
    6035              :             let (basebackup_cache, _) = BasebackupCache::new(Utf8PathBuf::new(), None);
    6036              : 
    6037              :             let tenant = Arc::new(TenantShard::new(
    6038              :                 TenantState::Attaching,
    6039              :                 self.conf,
    6040              :                 AttachedTenantConf::try_from(
    6041              :                     self.conf,
    6042              :                     LocationConf::attached_single(
    6043              :                         self.tenant_conf.clone(),
    6044              :                         self.generation,
    6045              :                         ShardParameters::default(),
    6046              :                     ),
    6047              :                 )
    6048              :                 .unwrap(),
    6049              :                 self.shard_identity,
    6050              :                 Some(walredo_mgr),
    6051              :                 self.tenant_shard_id,
    6052              :                 self.remote_storage.clone(),
    6053              :                 self.deletion_queue.new_client(),
    6054              :                 // TODO: ideally we should run all unit tests with both configs
    6055              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    6056              :                 basebackup_cache,
    6057              :                 FeatureResolver::new_disabled(),
    6058              :             ));
    6059              : 
    6060              :             let preload = tenant
    6061              :                 .preload(&self.remote_storage, CancellationToken::new())
    6062              :                 .await?;
    6063              :             tenant.attach(Some(preload), ctx).await?;
    6064              : 
    6065              :             tenant.state.send_replace(TenantState::Active);
    6066              :             for timeline in tenant.timelines.lock().unwrap().values() {
    6067              :                 timeline.set_state(TimelineState::Active);
    6068              :             }
    6069              :             Ok(tenant)
    6070              :         }
    6071              : 
    6072          119 :         pub(crate) async fn do_try_load(
    6073          119 :             &self,
    6074          119 :             ctx: &RequestContext,
    6075          119 :         ) -> anyhow::Result<Arc<TenantShard>> {
    6076          119 :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    6077          119 :             self.do_try_load_with_redo(walredo_mgr, ctx).await
    6078          119 :         }
    6079              : 
    6080            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    6081            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    6082            1 :         }
    6083              :     }
    6084              : 
    6085              :     // Mock WAL redo manager that doesn't do much
    6086              :     pub(crate) struct TestRedoManager;
    6087              : 
    6088              :     impl TestRedoManager {
    6089              :         /// # Cancel-Safety
    6090              :         ///
    6091              :         /// This method is cancellation-safe.
    6092        26774 :         pub async fn request_redo(
    6093        26774 :             &self,
    6094        26774 :             key: Key,
    6095        26774 :             lsn: Lsn,
    6096        26774 :             base_img: Option<(Lsn, Bytes)>,
    6097        26774 :             records: Vec<(Lsn, NeonWalRecord)>,
    6098        26774 :             _pg_version: PgMajorVersion,
    6099        26774 :             _redo_attempt_type: RedoAttemptType,
    6100        26774 :         ) -> Result<Bytes, walredo::Error> {
    6101      1403510 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    6102        26774 :             if records_neon {
    6103              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    6104        26774 :                 let mut page = match (base_img, records.first()) {
    6105        13029 :                     (Some((_lsn, img)), _) => {
    6106        13029 :                         let mut page = BytesMut::new();
    6107        13029 :                         page.extend_from_slice(&img);
    6108        13029 :                         page
    6109              :                     }
    6110        13745 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    6111              :                     _ => {
    6112            0 :                         panic!("Neon WAL redo requires base image or will init record");
    6113              :                     }
    6114              :                 };
    6115              : 
    6116      1430283 :                 for (record_lsn, record) in records {
    6117      1403510 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    6118              :                 }
    6119        26773 :                 Ok(page.freeze())
    6120              :             } else {
    6121              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    6122            0 :                 let s = format!(
    6123            0 :                     "redo for {} to get to {}, with {} and {} records",
    6124              :                     key,
    6125              :                     lsn,
    6126            0 :                     if base_img.is_some() {
    6127            0 :                         "base image"
    6128              :                     } else {
    6129            0 :                         "no base image"
    6130              :                     },
    6131            0 :                     records.len()
    6132              :                 );
    6133            0 :                 println!("{s}");
    6134              : 
    6135            0 :                 Ok(test_img(&s))
    6136              :             }
    6137        26774 :         }
    6138              :     }
    6139              : }
    6140              : 
    6141              : #[cfg(test)]
    6142              : mod tests {
    6143              :     use std::collections::{BTreeMap, BTreeSet};
    6144              : 
    6145              :     use bytes::{Bytes, BytesMut};
    6146              :     use hex_literal::hex;
    6147              :     use itertools::Itertools;
    6148              :     #[cfg(feature = "testing")]
    6149              :     use models::CompactLsnRange;
    6150              :     use pageserver_api::key::{
    6151              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    6152              :     };
    6153              :     use pageserver_api::keyspace::KeySpace;
    6154              :     #[cfg(feature = "testing")]
    6155              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    6156              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings, LsnLease};
    6157              :     use pageserver_compaction::helpers::overlaps_with;
    6158              :     #[cfg(feature = "testing")]
    6159              :     use rand::SeedableRng;
    6160              :     #[cfg(feature = "testing")]
    6161              :     use rand::rngs::StdRng;
    6162              :     use rand::{Rng, thread_rng};
    6163              :     #[cfg(feature = "testing")]
    6164              :     use std::ops::Range;
    6165              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    6166              :     use tests::storage_layer::ValuesReconstructState;
    6167              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    6168              :     #[cfg(feature = "testing")]
    6169              :     use timeline::GcInfo;
    6170              :     #[cfg(feature = "testing")]
    6171              :     use timeline::InMemoryLayerTestDesc;
    6172              :     #[cfg(feature = "testing")]
    6173              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    6174              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    6175              :     use utils::id::TenantId;
    6176              :     use utils::shard::{ShardCount, ShardNumber};
    6177              :     #[cfg(feature = "testing")]
    6178              :     use wal_decoder::models::record::NeonWalRecord;
    6179              :     use wal_decoder::models::value::Value;
    6180              : 
    6181              :     use super::*;
    6182              :     use crate::DEFAULT_PG_VERSION;
    6183              :     use crate::keyspace::KeySpaceAccum;
    6184              :     use crate::tenant::harness::*;
    6185              :     use crate::tenant::timeline::CompactFlags;
    6186              : 
    6187              :     static TEST_KEY: Lazy<Key> =
    6188           10 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    6189              : 
    6190              :     #[cfg(feature = "testing")]
    6191              :     struct TestTimelineSpecification {
    6192              :         start_lsn: Lsn,
    6193              :         last_record_lsn: Lsn,
    6194              : 
    6195              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6196              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6197              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6198              : 
    6199              :         gap_chance: u8,
    6200              :         will_init_chance: u8,
    6201              :     }
    6202              : 
    6203              :     #[cfg(feature = "testing")]
    6204              :     struct Storage {
    6205              :         storage: HashMap<(Key, Lsn), Value>,
    6206              :         start_lsn: Lsn,
    6207              :     }
    6208              : 
    6209              :     #[cfg(feature = "testing")]
    6210              :     impl Storage {
    6211        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6212              :             use bytes::BufMut;
    6213              : 
    6214        32000 :             let mut crnt_lsn = lsn;
    6215        32000 :             let mut got_base = false;
    6216              : 
    6217        32000 :             let mut acc = Vec::new();
    6218              : 
    6219      2831871 :             while crnt_lsn >= self.start_lsn {
    6220      2831871 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6221      1421172 :                     acc.push(value.clone());
    6222              : 
    6223      1402881 :                     match value {
    6224      1402881 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6225      1402881 :                             if *will_init {
    6226        13709 :                                 got_base = true;
    6227        13709 :                                 break;
    6228      1389172 :                             }
    6229              :                         }
    6230              :                         Value::Image(_) => {
    6231        18291 :                             got_base = true;
    6232        18291 :                             break;
    6233              :                         }
    6234            0 :                         _ => unreachable!(),
    6235              :                     }
    6236      1410699 :                 }
    6237              : 
    6238      2799871 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6239              :             }
    6240              : 
    6241        32000 :             assert!(
    6242        32000 :                 got_base,
    6243            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6244              :             );
    6245              : 
    6246        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6247              : 
    6248        32000 :             let mut blob = BytesMut::new();
    6249      1421172 :             for value in acc.into_iter().rev() {
    6250      1402881 :                 match value {
    6251      1402881 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6252      1402881 :                         blob.extend_from_slice(append.as_bytes());
    6253      1402881 :                     }
    6254        18291 :                     Value::Image(img) => {
    6255        18291 :                         blob.put(img);
    6256        18291 :                     }
    6257            0 :                     _ => unreachable!(),
    6258              :                 }
    6259              :             }
    6260              : 
    6261        32000 :             blob.into()
    6262        32000 :         }
    6263              :     }
    6264              : 
    6265              :     #[cfg(feature = "testing")]
    6266              :     #[allow(clippy::too_many_arguments)]
    6267            1 :     async fn randomize_timeline(
    6268            1 :         tenant: &Arc<TenantShard>,
    6269            1 :         new_timeline_id: TimelineId,
    6270            1 :         pg_version: PgMajorVersion,
    6271            1 :         spec: TestTimelineSpecification,
    6272            1 :         random: &mut rand::rngs::StdRng,
    6273            1 :         ctx: &RequestContext,
    6274            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6275            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6276            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6277              : 
    6278            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6279            2 :             let mut lsn = lsn_range.start;
    6280          202 :             while lsn < lsn_range.end {
    6281          200 :                 let mut key = key_range.start;
    6282        21018 :                 while key < key_range.end {
    6283        20818 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6284        20818 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6285              : 
    6286        20818 :                     if gap {
    6287         1018 :                         continue;
    6288        19800 :                     }
    6289              : 
    6290        19800 :                     let record = if will_init {
    6291          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6292              :                     } else {
    6293        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6294              :                     };
    6295              : 
    6296        19800 :                     storage.insert((key, lsn), record);
    6297              : 
    6298        19800 :                     key = key.next();
    6299              :                 }
    6300          200 :                 lsn = Lsn(lsn.0 + 1);
    6301              :             }
    6302              : 
    6303              :             // Stash some interesting LSN for future use
    6304            6 :             for offset in [0, 5, 100].iter() {
    6305            6 :                 if *offset == 0 {
    6306            2 :                     interesting_lsns.push(lsn_range.start);
    6307            2 :                 } else {
    6308            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6309            4 :                     match below {
    6310            4 :                         Some(v) if v >= spec.start_lsn => {
    6311            4 :                             interesting_lsns.push(v);
    6312            4 :                         }
    6313            0 :                         _ => {}
    6314              :                     }
    6315              : 
    6316            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6317            4 :                     interesting_lsns.push(above);
    6318              :                 }
    6319              :             }
    6320              :         }
    6321              : 
    6322            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6323            3 :             let mut lsn = lsn_range.start;
    6324          315 :             while lsn < lsn_range.end {
    6325          312 :                 let mut key = key_range.start;
    6326        11112 :                 while key < key_range.end {
    6327        10800 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6328        10800 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6329              : 
    6330        10800 :                     if gap {
    6331          504 :                         continue;
    6332        10296 :                     }
    6333              : 
    6334        10296 :                     let record = if will_init {
    6335          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6336              :                     } else {
    6337        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6338              :                     };
    6339              : 
    6340        10296 :                     storage.insert((key, lsn), record);
    6341              : 
    6342        10296 :                     key = key.next();
    6343              :                 }
    6344          312 :                 lsn = Lsn(lsn.0 + 1);
    6345              :             }
    6346              : 
    6347              :             // Stash some interesting LSN for future use
    6348            9 :             for offset in [0, 5, 100].iter() {
    6349            9 :                 if *offset == 0 {
    6350            3 :                     interesting_lsns.push(lsn_range.start);
    6351            3 :                 } else {
    6352            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6353            6 :                     match below {
    6354            6 :                         Some(v) if v >= spec.start_lsn => {
    6355            3 :                             interesting_lsns.push(v);
    6356            3 :                         }
    6357            3 :                         _ => {}
    6358              :                     }
    6359              : 
    6360            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6361            6 :                     interesting_lsns.push(above);
    6362              :                 }
    6363              :             }
    6364              :         }
    6365              : 
    6366            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6367            3 :             let mut key = key_range.start;
    6368          142 :             while key < key_range.end {
    6369          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6370          139 :                 let record = Value::Image(blob.clone());
    6371          139 :                 storage.insert((key, *lsn), record);
    6372          139 : 
    6373          139 :                 key = key.next();
    6374          139 :             }
    6375              : 
    6376              :             // Stash some interesting LSN for future use
    6377            9 :             for offset in [0, 5, 100].iter() {
    6378            9 :                 if *offset == 0 {
    6379            3 :                     interesting_lsns.push(*lsn);
    6380            3 :                 } else {
    6381            6 :                     let below = lsn.checked_sub(*offset);
    6382            6 :                     match below {
    6383            6 :                         Some(v) if v >= spec.start_lsn => {
    6384            4 :                             interesting_lsns.push(v);
    6385            4 :                         }
    6386            2 :                         _ => {}
    6387              :                     }
    6388              : 
    6389            6 :                     let above = Lsn(lsn.0 + offset);
    6390            6 :                     interesting_lsns.push(above);
    6391              :                 }
    6392              :             }
    6393              :         }
    6394              : 
    6395            1 :         let in_memory_test_layers = {
    6396            1 :             let mut acc = Vec::new();
    6397              : 
    6398            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6399            2 :                 let mut data = Vec::new();
    6400              : 
    6401            2 :                 let mut lsn = lsn_range.start;
    6402          202 :                 while lsn < lsn_range.end {
    6403          200 :                     let mut key = key_range.start;
    6404        20000 :                     while key < key_range.end {
    6405        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6406        19800 :                             data.push((key, lsn, record.clone()));
    6407        19800 :                         }
    6408              : 
    6409        19800 :                         key = key.next();
    6410              :                     }
    6411          200 :                     lsn = Lsn(lsn.0 + 1);
    6412              :                 }
    6413              : 
    6414            2 :                 acc.push(InMemoryLayerTestDesc {
    6415            2 :                     data,
    6416            2 :                     lsn_range: lsn_range.clone(),
    6417            2 :                     is_open: false,
    6418            2 :                 })
    6419              :             }
    6420              : 
    6421            1 :             acc
    6422              :         };
    6423              : 
    6424            1 :         let delta_test_layers = {
    6425            1 :             let mut acc = Vec::new();
    6426              : 
    6427            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6428            3 :                 let mut data = Vec::new();
    6429              : 
    6430            3 :                 let mut lsn = lsn_range.start;
    6431          315 :                 while lsn < lsn_range.end {
    6432          312 :                     let mut key = key_range.start;
    6433        10608 :                     while key < key_range.end {
    6434        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6435        10296 :                             data.push((key, lsn, record.clone()));
    6436        10296 :                         }
    6437              : 
    6438        10296 :                         key = key.next();
    6439              :                     }
    6440          312 :                     lsn = Lsn(lsn.0 + 1);
    6441              :                 }
    6442              : 
    6443            3 :                 acc.push(DeltaLayerTestDesc {
    6444            3 :                     data,
    6445            3 :                     lsn_range: lsn_range.clone(),
    6446            3 :                     key_range: key_range.clone(),
    6447            3 :                 })
    6448              :             }
    6449              : 
    6450            1 :             acc
    6451              :         };
    6452              : 
    6453            1 :         let image_test_layers = {
    6454            1 :             let mut acc = Vec::new();
    6455              : 
    6456            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6457            3 :                 let mut data = Vec::new();
    6458              : 
    6459            3 :                 let mut key = key_range.start;
    6460          142 :                 while key < key_range.end {
    6461          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6462          139 :                         let blob = match record {
    6463          139 :                             Value::Image(blob) => blob.clone(),
    6464            0 :                             _ => unreachable!(),
    6465              :                         };
    6466              : 
    6467          139 :                         data.push((key, blob));
    6468            0 :                     }
    6469              : 
    6470          139 :                     key = key.next();
    6471              :                 }
    6472              : 
    6473            3 :                 acc.push((*lsn, data));
    6474              :             }
    6475              : 
    6476            1 :             acc
    6477              :         };
    6478              : 
    6479            1 :         let tline = tenant
    6480            1 :             .create_test_timeline_with_layers(
    6481            1 :                 new_timeline_id,
    6482            1 :                 spec.start_lsn,
    6483            1 :                 pg_version,
    6484            1 :                 ctx,
    6485            1 :                 in_memory_test_layers,
    6486            1 :                 delta_test_layers,
    6487            1 :                 image_test_layers,
    6488            1 :                 spec.last_record_lsn,
    6489            1 :             )
    6490            1 :             .await?;
    6491              : 
    6492            1 :         Ok((
    6493            1 :             tline,
    6494            1 :             Storage {
    6495            1 :                 storage,
    6496            1 :                 start_lsn: spec.start_lsn,
    6497            1 :             },
    6498            1 :             interesting_lsns,
    6499            1 :         ))
    6500            1 :     }
    6501              : 
    6502              :     #[tokio::test]
    6503            1 :     async fn test_basic() -> anyhow::Result<()> {
    6504            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6505            1 :         let tline = tenant
    6506            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6507            1 :             .await?;
    6508              : 
    6509            1 :         let mut writer = tline.writer().await;
    6510            1 :         writer
    6511            1 :             .put(
    6512            1 :                 *TEST_KEY,
    6513            1 :                 Lsn(0x10),
    6514            1 :                 &Value::Image(test_img("foo at 0x10")),
    6515            1 :                 &ctx,
    6516            1 :             )
    6517            1 :             .await?;
    6518            1 :         writer.finish_write(Lsn(0x10));
    6519            1 :         drop(writer);
    6520              : 
    6521            1 :         let mut writer = tline.writer().await;
    6522            1 :         writer
    6523            1 :             .put(
    6524            1 :                 *TEST_KEY,
    6525            1 :                 Lsn(0x20),
    6526            1 :                 &Value::Image(test_img("foo at 0x20")),
    6527            1 :                 &ctx,
    6528            1 :             )
    6529            1 :             .await?;
    6530            1 :         writer.finish_write(Lsn(0x20));
    6531            1 :         drop(writer);
    6532              : 
    6533            1 :         assert_eq!(
    6534            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6535            1 :             test_img("foo at 0x10")
    6536              :         );
    6537            1 :         assert_eq!(
    6538            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6539            1 :             test_img("foo at 0x10")
    6540              :         );
    6541            1 :         assert_eq!(
    6542            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6543            1 :             test_img("foo at 0x20")
    6544              :         );
    6545              : 
    6546            2 :         Ok(())
    6547            1 :     }
    6548              : 
    6549              :     #[tokio::test]
    6550            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6551            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6552            1 :             .await?
    6553            1 :             .load()
    6554            1 :             .await;
    6555            1 :         let _ = tenant
    6556            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6557            1 :             .await?;
    6558              : 
    6559            1 :         match tenant
    6560            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6561            1 :             .await
    6562            1 :         {
    6563            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6564            1 :             Err(e) => assert_eq!(
    6565            1 :                 e.to_string(),
    6566            1 :                 "timeline already exists with different parameters".to_string()
    6567            1 :             ),
    6568            1 :         }
    6569            1 : 
    6570            1 :         Ok(())
    6571            1 :     }
    6572              : 
    6573              :     /// Convenience function to create a page image with given string as the only content
    6574            5 :     pub fn test_value(s: &str) -> Value {
    6575            5 :         let mut buf = BytesMut::new();
    6576            5 :         buf.extend_from_slice(s.as_bytes());
    6577            5 :         Value::Image(buf.freeze())
    6578            5 :     }
    6579              : 
    6580              :     ///
    6581              :     /// Test branch creation
    6582              :     ///
    6583              :     #[tokio::test]
    6584            1 :     async fn test_branch() -> anyhow::Result<()> {
    6585              :         use std::str::from_utf8;
    6586              : 
    6587            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6588            1 :         let tline = tenant
    6589            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6590            1 :             .await?;
    6591            1 :         let mut writer = tline.writer().await;
    6592              : 
    6593              :         #[allow(non_snake_case)]
    6594            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6595              :         #[allow(non_snake_case)]
    6596            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6597              : 
    6598              :         // Insert a value on the timeline
    6599            1 :         writer
    6600            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6601            1 :             .await?;
    6602            1 :         writer
    6603            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6604            1 :             .await?;
    6605            1 :         writer.finish_write(Lsn(0x20));
    6606              : 
    6607            1 :         writer
    6608            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6609            1 :             .await?;
    6610            1 :         writer.finish_write(Lsn(0x30));
    6611            1 :         writer
    6612            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6613            1 :             .await?;
    6614            1 :         writer.finish_write(Lsn(0x40));
    6615              : 
    6616              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6617              : 
    6618              :         // Branch the history, modify relation differently on the new timeline
    6619            1 :         tenant
    6620            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6621            1 :             .await?;
    6622            1 :         let newtline = tenant
    6623            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6624            1 :             .expect("Should have a local timeline");
    6625            1 :         let mut new_writer = newtline.writer().await;
    6626            1 :         new_writer
    6627            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6628            1 :             .await?;
    6629            1 :         new_writer.finish_write(Lsn(0x40));
    6630              : 
    6631              :         // Check page contents on both branches
    6632            1 :         assert_eq!(
    6633            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6634              :             "foo at 0x40"
    6635              :         );
    6636            1 :         assert_eq!(
    6637            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6638              :             "bar at 0x40"
    6639              :         );
    6640            1 :         assert_eq!(
    6641            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6642              :             "foobar at 0x20"
    6643              :         );
    6644              : 
    6645              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6646              : 
    6647            2 :         Ok(())
    6648            1 :     }
    6649              : 
    6650           10 :     async fn make_some_layers(
    6651           10 :         tline: &Timeline,
    6652           10 :         start_lsn: Lsn,
    6653           10 :         ctx: &RequestContext,
    6654           10 :     ) -> anyhow::Result<()> {
    6655           10 :         let mut lsn = start_lsn;
    6656              :         {
    6657           10 :             let mut writer = tline.writer().await;
    6658              :             // Create a relation on the timeline
    6659           10 :             writer
    6660           10 :                 .put(
    6661           10 :                     *TEST_KEY,
    6662           10 :                     lsn,
    6663           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6664           10 :                     ctx,
    6665           10 :                 )
    6666           10 :                 .await?;
    6667           10 :             writer.finish_write(lsn);
    6668           10 :             lsn += 0x10;
    6669           10 :             writer
    6670           10 :                 .put(
    6671           10 :                     *TEST_KEY,
    6672           10 :                     lsn,
    6673           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6674           10 :                     ctx,
    6675           10 :                 )
    6676           10 :                 .await?;
    6677           10 :             writer.finish_write(lsn);
    6678           10 :             lsn += 0x10;
    6679              :         }
    6680           10 :         tline.freeze_and_flush().await?;
    6681              :         {
    6682           10 :             let mut writer = tline.writer().await;
    6683           10 :             writer
    6684           10 :                 .put(
    6685           10 :                     *TEST_KEY,
    6686           10 :                     lsn,
    6687           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6688           10 :                     ctx,
    6689           10 :                 )
    6690           10 :                 .await?;
    6691           10 :             writer.finish_write(lsn);
    6692           10 :             lsn += 0x10;
    6693           10 :             writer
    6694           10 :                 .put(
    6695           10 :                     *TEST_KEY,
    6696           10 :                     lsn,
    6697           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6698           10 :                     ctx,
    6699           10 :                 )
    6700           10 :                 .await?;
    6701           10 :             writer.finish_write(lsn);
    6702              :         }
    6703           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6704           10 :     }
    6705              : 
    6706              :     #[tokio::test]
    6707            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6708            1 :         let (tenant, ctx) =
    6709            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6710            1 :                 .await?
    6711            1 :                 .load()
    6712            1 :                 .await;
    6713            1 :         let tline = tenant
    6714            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6715            1 :             .await?;
    6716            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6717              : 
    6718              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6719              :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6720              :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6721              :         // below should fail.
    6722            1 :         tenant
    6723            1 :             .gc_iteration(
    6724            1 :                 Some(TIMELINE_ID),
    6725            1 :                 0x10,
    6726            1 :                 Duration::ZERO,
    6727            1 :                 &CancellationToken::new(),
    6728            1 :                 &ctx,
    6729            1 :             )
    6730            1 :             .await?;
    6731              : 
    6732              :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6733            1 :         match tenant
    6734            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6735            1 :             .await
    6736            1 :         {
    6737            1 :             Ok(_) => panic!("branching should have failed"),
    6738            1 :             Err(err) => {
    6739            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6740            1 :                     panic!("wrong error type")
    6741            1 :                 };
    6742            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6743            1 :                 assert!(
    6744            1 :                     err.source()
    6745            1 :                         .unwrap()
    6746            1 :                         .to_string()
    6747            1 :                         .contains("we might've already garbage collected needed data")
    6748            1 :                 )
    6749            1 :             }
    6750            1 :         }
    6751            1 : 
    6752            1 :         Ok(())
    6753            1 :     }
    6754              : 
    6755              :     #[tokio::test]
    6756            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6757            1 :         let (tenant, ctx) =
    6758            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6759            1 :                 .await?
    6760            1 :                 .load()
    6761            1 :                 .await;
    6762              : 
    6763            1 :         let tline = tenant
    6764            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6765            1 :             .await?;
    6766              :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6767            1 :         match tenant
    6768            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6769            1 :             .await
    6770            1 :         {
    6771            1 :             Ok(_) => panic!("branching should have failed"),
    6772            1 :             Err(err) => {
    6773            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6774            1 :                     panic!("wrong error type");
    6775            1 :                 };
    6776            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6777            1 :                 assert!(
    6778            1 :                     &err.source()
    6779            1 :                         .unwrap()
    6780            1 :                         .to_string()
    6781            1 :                         .contains("is earlier than latest GC cutoff")
    6782            1 :                 );
    6783            1 :             }
    6784            1 :         }
    6785            1 : 
    6786            1 :         Ok(())
    6787            1 :     }
    6788              : 
    6789              :     /*
    6790              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6791              :     // remove the old value, we'd need to work a little harder
    6792              :     #[tokio::test]
    6793              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6794              :         let repo =
    6795              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6796              :             .load();
    6797              : 
    6798              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6799              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6800              : 
    6801              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6802              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6803              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6804              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6805              :             Ok(_) => panic!("request for page should have failed"),
    6806              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6807              :         }
    6808              :         Ok(())
    6809              :     }
    6810              :      */
    6811              : 
    6812              :     #[tokio::test]
    6813            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6814            1 :         let (tenant, ctx) =
    6815            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6816            1 :                 .await?
    6817            1 :                 .load()
    6818            1 :                 .await;
    6819            1 :         let tline = tenant
    6820            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6821            1 :             .await?;
    6822            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6823              : 
    6824            1 :         tenant
    6825            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6826            1 :             .await?;
    6827            1 :         let newtline = tenant
    6828            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6829            1 :             .expect("Should have a local timeline");
    6830              : 
    6831            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6832              : 
    6833            1 :         tline.set_broken("test".to_owned());
    6834              : 
    6835            1 :         tenant
    6836            1 :             .gc_iteration(
    6837            1 :                 Some(TIMELINE_ID),
    6838            1 :                 0x10,
    6839            1 :                 Duration::ZERO,
    6840            1 :                 &CancellationToken::new(),
    6841            1 :                 &ctx,
    6842            1 :             )
    6843            1 :             .await?;
    6844              : 
    6845              :         // The branchpoints should contain all timelines, even ones marked
    6846              :         // as Broken.
    6847              :         {
    6848            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6849            1 :             assert_eq!(branchpoints.len(), 1);
    6850            1 :             assert_eq!(
    6851            1 :                 branchpoints[0],
    6852              :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6853              :             );
    6854              :         }
    6855              : 
    6856              :         // You can read the key from the child branch even though the parent is
    6857              :         // Broken, as long as you don't need to access data from the parent.
    6858            1 :         assert_eq!(
    6859            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6860            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6861              :         );
    6862              : 
    6863              :         // This needs to traverse to the parent, and fails.
    6864            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6865            1 :         assert!(
    6866            1 :             err.to_string().starts_with(&format!(
    6867            1 :                 "bad state on timeline {}: Broken",
    6868            1 :                 tline.timeline_id
    6869            1 :             )),
    6870            0 :             "{err}"
    6871              :         );
    6872              : 
    6873            2 :         Ok(())
    6874            1 :     }
    6875              : 
    6876              :     #[tokio::test]
    6877            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6878            1 :         let (tenant, ctx) =
    6879            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6880            1 :                 .await?
    6881            1 :                 .load()
    6882            1 :                 .await;
    6883            1 :         let tline = tenant
    6884            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6885            1 :             .await?;
    6886            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6887              : 
    6888            1 :         tenant
    6889            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6890            1 :             .await?;
    6891            1 :         let newtline = tenant
    6892            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6893            1 :             .expect("Should have a local timeline");
    6894              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6895            1 :         tenant
    6896            1 :             .gc_iteration(
    6897            1 :                 Some(TIMELINE_ID),
    6898            1 :                 0x10,
    6899            1 :                 Duration::ZERO,
    6900            1 :                 &CancellationToken::new(),
    6901            1 :                 &ctx,
    6902            1 :             )
    6903            1 :             .await?;
    6904            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6905              : 
    6906            2 :         Ok(())
    6907            1 :     }
    6908              :     #[tokio::test]
    6909            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6910            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6911            1 :             .await?
    6912            1 :             .load()
    6913            1 :             .await;
    6914            1 :         let tline = tenant
    6915            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6916            1 :             .await?;
    6917            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6918              : 
    6919            1 :         tenant
    6920            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6921            1 :             .await?;
    6922            1 :         let newtline = tenant
    6923            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6924            1 :             .expect("Should have a local timeline");
    6925              : 
    6926            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6927              : 
    6928              :         // run gc on parent
    6929            1 :         tenant
    6930            1 :             .gc_iteration(
    6931            1 :                 Some(TIMELINE_ID),
    6932            1 :                 0x10,
    6933            1 :                 Duration::ZERO,
    6934            1 :                 &CancellationToken::new(),
    6935            1 :                 &ctx,
    6936            1 :             )
    6937            1 :             .await?;
    6938              : 
    6939              :         // Check that the data is still accessible on the branch.
    6940            1 :         assert_eq!(
    6941            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6942            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6943              :         );
    6944              : 
    6945            2 :         Ok(())
    6946            1 :     }
    6947              : 
    6948              :     #[tokio::test]
    6949            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6950              :         const TEST_NAME: &str = "timeline_load";
    6951            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6952              :         {
    6953            1 :             let (tenant, ctx) = harness.load().await;
    6954            1 :             let tline = tenant
    6955            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6956            1 :                 .await?;
    6957            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6958              :             // so that all uploads finish & we can call harness.load() below again
    6959            1 :             tenant
    6960            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6961            1 :                 .instrument(harness.span())
    6962            1 :                 .await
    6963            1 :                 .ok()
    6964            1 :                 .unwrap();
    6965              :         }
    6966              : 
    6967            1 :         let (tenant, _ctx) = harness.load().await;
    6968            1 :         tenant
    6969            1 :             .get_timeline(TIMELINE_ID, true)
    6970            1 :             .expect("cannot load timeline");
    6971              : 
    6972            2 :         Ok(())
    6973            1 :     }
    6974              : 
    6975              :     #[tokio::test]
    6976            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6977              :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6978            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6979              :         // create two timelines
    6980              :         {
    6981            1 :             let (tenant, ctx) = harness.load().await;
    6982            1 :             let tline = tenant
    6983            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6984            1 :                 .await?;
    6985              : 
    6986            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6987              : 
    6988            1 :             let child_tline = tenant
    6989            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6990            1 :                 .await?;
    6991            1 :             child_tline.set_state(TimelineState::Active);
    6992              : 
    6993            1 :             let newtline = tenant
    6994            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6995            1 :                 .expect("Should have a local timeline");
    6996              : 
    6997            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6998              : 
    6999              :             // so that all uploads finish & we can call harness.load() below again
    7000            1 :             tenant
    7001            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    7002            1 :                 .instrument(harness.span())
    7003            1 :                 .await
    7004            1 :                 .ok()
    7005            1 :                 .unwrap();
    7006              :         }
    7007              : 
    7008              :         // check that both of them are initially unloaded
    7009            1 :         let (tenant, _ctx) = harness.load().await;
    7010              : 
    7011              :         // check that both, child and ancestor are loaded
    7012            1 :         let _child_tline = tenant
    7013            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    7014            1 :             .expect("cannot get child timeline loaded");
    7015              : 
    7016            1 :         let _ancestor_tline = tenant
    7017            1 :             .get_timeline(TIMELINE_ID, true)
    7018            1 :             .expect("cannot get ancestor timeline loaded");
    7019              : 
    7020            2 :         Ok(())
    7021            1 :     }
    7022              : 
    7023              :     #[tokio::test]
    7024            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    7025              :         use storage_layer::AsLayerDesc;
    7026            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    7027            1 :             .await?
    7028            1 :             .load()
    7029            1 :             .await;
    7030            1 :         let tline = tenant
    7031            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7032            1 :             .await?;
    7033            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7034              : 
    7035            1 :         let layer_map = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7036            1 :         let level0_deltas = layer_map
    7037            1 :             .layer_map()?
    7038            1 :             .level0_deltas()
    7039            1 :             .iter()
    7040            2 :             .map(|desc| layer_map.get_from_desc(desc))
    7041            1 :             .collect::<Vec<_>>();
    7042              : 
    7043            1 :         assert!(!level0_deltas.is_empty());
    7044              : 
    7045            3 :         for delta in level0_deltas {
    7046            1 :             // Ensure we are dumping a delta layer here
    7047            2 :             assert!(delta.layer_desc().is_delta);
    7048            2 :             delta.dump(true, &ctx).await.unwrap();
    7049            1 :         }
    7050            1 : 
    7051            1 :         Ok(())
    7052            1 :     }
    7053              : 
    7054              :     #[tokio::test]
    7055            1 :     async fn test_images() -> anyhow::Result<()> {
    7056            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    7057            1 :         let tline = tenant
    7058            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7059            1 :             .await?;
    7060              : 
    7061            1 :         let mut writer = tline.writer().await;
    7062            1 :         writer
    7063            1 :             .put(
    7064            1 :                 *TEST_KEY,
    7065            1 :                 Lsn(0x10),
    7066            1 :                 &Value::Image(test_img("foo at 0x10")),
    7067            1 :                 &ctx,
    7068            1 :             )
    7069            1 :             .await?;
    7070            1 :         writer.finish_write(Lsn(0x10));
    7071            1 :         drop(writer);
    7072              : 
    7073            1 :         tline.freeze_and_flush().await?;
    7074            1 :         tline
    7075            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7076            1 :             .await?;
    7077              : 
    7078            1 :         let mut writer = tline.writer().await;
    7079            1 :         writer
    7080            1 :             .put(
    7081            1 :                 *TEST_KEY,
    7082            1 :                 Lsn(0x20),
    7083            1 :                 &Value::Image(test_img("foo at 0x20")),
    7084            1 :                 &ctx,
    7085            1 :             )
    7086            1 :             .await?;
    7087            1 :         writer.finish_write(Lsn(0x20));
    7088            1 :         drop(writer);
    7089              : 
    7090            1 :         tline.freeze_and_flush().await?;
    7091            1 :         tline
    7092            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7093            1 :             .await?;
    7094              : 
    7095            1 :         let mut writer = tline.writer().await;
    7096            1 :         writer
    7097            1 :             .put(
    7098            1 :                 *TEST_KEY,
    7099            1 :                 Lsn(0x30),
    7100            1 :                 &Value::Image(test_img("foo at 0x30")),
    7101            1 :                 &ctx,
    7102            1 :             )
    7103            1 :             .await?;
    7104            1 :         writer.finish_write(Lsn(0x30));
    7105            1 :         drop(writer);
    7106              : 
    7107            1 :         tline.freeze_and_flush().await?;
    7108            1 :         tline
    7109            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7110            1 :             .await?;
    7111              : 
    7112            1 :         let mut writer = tline.writer().await;
    7113            1 :         writer
    7114            1 :             .put(
    7115            1 :                 *TEST_KEY,
    7116            1 :                 Lsn(0x40),
    7117            1 :                 &Value::Image(test_img("foo at 0x40")),
    7118            1 :                 &ctx,
    7119            1 :             )
    7120            1 :             .await?;
    7121            1 :         writer.finish_write(Lsn(0x40));
    7122            1 :         drop(writer);
    7123              : 
    7124            1 :         tline.freeze_and_flush().await?;
    7125            1 :         tline
    7126            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7127            1 :             .await?;
    7128              : 
    7129            1 :         assert_eq!(
    7130            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    7131            1 :             test_img("foo at 0x10")
    7132              :         );
    7133            1 :         assert_eq!(
    7134            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    7135            1 :             test_img("foo at 0x10")
    7136              :         );
    7137            1 :         assert_eq!(
    7138            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    7139            1 :             test_img("foo at 0x20")
    7140              :         );
    7141            1 :         assert_eq!(
    7142            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    7143            1 :             test_img("foo at 0x30")
    7144              :         );
    7145            1 :         assert_eq!(
    7146            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    7147            1 :             test_img("foo at 0x40")
    7148              :         );
    7149              : 
    7150            2 :         Ok(())
    7151            1 :     }
    7152              : 
    7153            2 :     async fn bulk_insert_compact_gc(
    7154            2 :         tenant: &TenantShard,
    7155            2 :         timeline: &Arc<Timeline>,
    7156            2 :         ctx: &RequestContext,
    7157            2 :         lsn: Lsn,
    7158            2 :         repeat: usize,
    7159            2 :         key_count: usize,
    7160            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7161            2 :         let compact = true;
    7162            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    7163            2 :     }
    7164              : 
    7165            4 :     async fn bulk_insert_maybe_compact_gc(
    7166            4 :         tenant: &TenantShard,
    7167            4 :         timeline: &Arc<Timeline>,
    7168            4 :         ctx: &RequestContext,
    7169            4 :         mut lsn: Lsn,
    7170            4 :         repeat: usize,
    7171            4 :         key_count: usize,
    7172            4 :         compact: bool,
    7173            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7174            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    7175              : 
    7176            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7177            4 :         let mut blknum = 0;
    7178              : 
    7179              :         // Enforce that key range is monotonously increasing
    7180            4 :         let mut keyspace = KeySpaceAccum::new();
    7181              : 
    7182            4 :         let cancel = CancellationToken::new();
    7183              : 
    7184            4 :         for _ in 0..repeat {
    7185          200 :             for _ in 0..key_count {
    7186      2000000 :                 test_key.field6 = blknum;
    7187      2000000 :                 let mut writer = timeline.writer().await;
    7188      2000000 :                 writer
    7189      2000000 :                     .put(
    7190      2000000 :                         test_key,
    7191      2000000 :                         lsn,
    7192      2000000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7193      2000000 :                         ctx,
    7194      2000000 :                     )
    7195      2000000 :                     .await?;
    7196      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7197      2000000 :                 writer.finish_write(lsn);
    7198      2000000 :                 drop(writer);
    7199              : 
    7200      2000000 :                 keyspace.add_key(test_key);
    7201              : 
    7202      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7203      2000000 :                 blknum += 1;
    7204              :             }
    7205              : 
    7206          200 :             timeline.freeze_and_flush().await?;
    7207          200 :             if compact {
    7208              :                 // this requires timeline to be &Arc<Timeline>
    7209          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7210          100 :             }
    7211              : 
    7212              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7213              :             // originally was.
    7214          200 :             let res = tenant
    7215          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7216          200 :                 .await?;
    7217              : 
    7218          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7219              :         }
    7220              : 
    7221            4 :         Ok(inserted)
    7222            4 :     }
    7223              : 
    7224              :     //
    7225              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7226              :     // Repeat 50 times.
    7227              :     //
    7228              :     #[tokio::test]
    7229            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7230            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7231            1 :         let (tenant, ctx) = harness.load().await;
    7232            1 :         let tline = tenant
    7233            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7234            1 :             .await?;
    7235              : 
    7236            1 :         let lsn = Lsn(0x10);
    7237            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7238              : 
    7239            2 :         Ok(())
    7240            1 :     }
    7241              : 
    7242              :     // Test the vectored get real implementation against a simple sequential implementation.
    7243              :     //
    7244              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7245              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7246              :     // grow to the right on the X axis.
    7247              :     //                       [Delta]
    7248              :     //                 [Delta]
    7249              :     //           [Delta]
    7250              :     //    [Delta]
    7251              :     // ------------ Image ---------------
    7252              :     //
    7253              :     // After layer generation we pick the ranges to query as follows:
    7254              :     // 1. The beginning of each delta layer
    7255              :     // 2. At the seam between two adjacent delta layers
    7256              :     //
    7257              :     // There's one major downside to this test: delta layers only contains images,
    7258              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7259              :     #[tokio::test]
    7260            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7261            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7262            1 :         let (tenant, ctx) = harness.load().await;
    7263            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7264            1 :         let tline = tenant
    7265            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7266            1 :             .await?;
    7267              : 
    7268            1 :         let lsn = Lsn(0x10);
    7269            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7270              : 
    7271            1 :         let guard = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7272            1 :         let lm = guard.layer_map()?;
    7273              : 
    7274            1 :         lm.dump(true, &ctx).await?;
    7275              : 
    7276            1 :         let mut reads = Vec::new();
    7277            1 :         let mut prev = None;
    7278            6 :         lm.iter_historic_layers().for_each(|desc| {
    7279            6 :             if !desc.is_delta() {
    7280            1 :                 prev = Some(desc.clone());
    7281            1 :                 return;
    7282            5 :             }
    7283              : 
    7284            5 :             let start = desc.key_range.start;
    7285            5 :             let end = desc
    7286            5 :                 .key_range
    7287            5 :                 .start
    7288            5 :                 .add(tenant.conf.max_get_vectored_keys.get() as u32);
    7289            5 :             reads.push(KeySpace {
    7290            5 :                 ranges: vec![start..end],
    7291            5 :             });
    7292              : 
    7293            5 :             if let Some(prev) = &prev {
    7294            5 :                 if !prev.is_delta() {
    7295            5 :                     return;
    7296            0 :                 }
    7297              : 
    7298            0 :                 let first_range = Key {
    7299            0 :                     field6: prev.key_range.end.field6 - 4,
    7300            0 :                     ..prev.key_range.end
    7301            0 :                 }..prev.key_range.end;
    7302              : 
    7303            0 :                 let second_range = desc.key_range.start..Key {
    7304            0 :                     field6: desc.key_range.start.field6 + 4,
    7305            0 :                     ..desc.key_range.start
    7306            0 :                 };
    7307              : 
    7308            0 :                 reads.push(KeySpace {
    7309            0 :                     ranges: vec![first_range, second_range],
    7310            0 :                 });
    7311            0 :             };
    7312              : 
    7313            0 :             prev = Some(desc.clone());
    7314            6 :         });
    7315              : 
    7316            1 :         drop(guard);
    7317              : 
    7318              :         // Pick a big LSN such that we query over all the changes.
    7319            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7320              : 
    7321            6 :         for read in reads {
    7322            5 :             info!("Doing vectored read on {:?}", read);
    7323            1 : 
    7324            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7325            1 : 
    7326            5 :             let vectored_res = tline
    7327            5 :                 .get_vectored_impl(
    7328            5 :                     query,
    7329            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7330            5 :                     &ctx,
    7331            5 :                 )
    7332            5 :                 .await;
    7333            1 : 
    7334            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7335            5 :             let mut expect_missing = false;
    7336            5 :             let mut key = read.start().unwrap();
    7337          165 :             while key != read.end().unwrap() {
    7338          160 :                 if let Some(lsns) = inserted.get(&key) {
    7339          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7340          160 :                     match expected_lsn {
    7341          160 :                         Some(lsn) => {
    7342          160 :                             expected_lsns.insert(key, *lsn);
    7343          160 :                         }
    7344            1 :                         None => {
    7345            1 :                             expect_missing = true;
    7346            1 :                             break;
    7347            1 :                         }
    7348            1 :                     }
    7349            1 :                 } else {
    7350            1 :                     expect_missing = true;
    7351            1 :                     break;
    7352            1 :                 }
    7353            1 : 
    7354          160 :                 key = key.next();
    7355            1 :             }
    7356            1 : 
    7357            5 :             if expect_missing {
    7358            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7359            1 :             } else {
    7360          160 :                 for (key, image) in vectored_res? {
    7361          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7362          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7363          160 :                     assert_eq!(image?, expected_image);
    7364            1 :                 }
    7365            1 :             }
    7366            1 :         }
    7367            1 : 
    7368            1 :         Ok(())
    7369            1 :     }
    7370              : 
    7371              :     #[tokio::test]
    7372            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7373            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7374              : 
    7375            1 :         let (tenant, ctx) = harness.load().await;
    7376            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7377            1 :         let (tline, ctx) = tenant
    7378            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7379            1 :             .await?;
    7380            1 :         let tline = tline.raw_timeline().unwrap();
    7381              : 
    7382            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7383            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7384            1 :         modification.set_lsn(Lsn(0x1008))?;
    7385            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7386            1 :         modification.commit(&ctx).await?;
    7387              : 
    7388            1 :         let child_timeline_id = TimelineId::generate();
    7389            1 :         tenant
    7390            1 :             .branch_timeline_test(
    7391            1 :                 tline,
    7392            1 :                 child_timeline_id,
    7393            1 :                 Some(tline.get_last_record_lsn()),
    7394            1 :                 &ctx,
    7395            1 :             )
    7396            1 :             .await?;
    7397              : 
    7398            1 :         let child_timeline = tenant
    7399            1 :             .get_timeline(child_timeline_id, true)
    7400            1 :             .expect("Should have the branched timeline");
    7401              : 
    7402            1 :         let aux_keyspace = KeySpace {
    7403            1 :             ranges: vec![NON_INHERITED_RANGE],
    7404            1 :         };
    7405            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7406              : 
    7407            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7408              : 
    7409            1 :         let vectored_res = child_timeline
    7410            1 :             .get_vectored_impl(
    7411            1 :                 query,
    7412            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7413            1 :                 &ctx,
    7414            1 :             )
    7415            1 :             .await;
    7416              : 
    7417            1 :         let images = vectored_res?;
    7418            1 :         assert!(images.is_empty());
    7419            2 :         Ok(())
    7420            1 :     }
    7421              : 
    7422              :     // Test that vectored get handles layer gaps correctly
    7423              :     // by advancing into the next ancestor timeline if required.
    7424              :     //
    7425              :     // The test generates timelines that look like the diagram below.
    7426              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7427              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7428              :     //
    7429              :     // ```
    7430              :     //-------------------------------+
    7431              :     //                          ...  |
    7432              :     //               [   L1   ]      |
    7433              :     //     [ / L1   ]                | Child Timeline
    7434              :     // ...                           |
    7435              :     // ------------------------------+
    7436              :     //     [ X L1   ]                | Parent Timeline
    7437              :     // ------------------------------+
    7438              :     // ```
    7439              :     #[tokio::test]
    7440            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7441            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7442            1 :             // Make compaction deterministic
    7443            1 :             gc_period: Some(Duration::ZERO),
    7444            1 :             compaction_period: Some(Duration::ZERO),
    7445            1 :             // Encourage creation of L1 layers
    7446            1 :             checkpoint_distance: Some(16 * 1024),
    7447            1 :             compaction_target_size: Some(8 * 1024),
    7448            1 :             ..Default::default()
    7449            1 :         };
    7450              : 
    7451            1 :         let harness = TenantHarness::create_custom(
    7452            1 :             "test_get_vectored_key_gap",
    7453            1 :             tenant_conf,
    7454            1 :             TenantId::generate(),
    7455            1 :             ShardIdentity::unsharded(),
    7456            1 :             Generation::new(0xdeadbeef),
    7457            1 :         )
    7458            1 :         .await?;
    7459            1 :         let (tenant, ctx) = harness.load().await;
    7460            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7461              : 
    7462            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7463            1 :         let gap_at_key = current_key.add(100);
    7464            1 :         let mut current_lsn = Lsn(0x10);
    7465              : 
    7466              :         const KEY_COUNT: usize = 10_000;
    7467              : 
    7468            1 :         let timeline_id = TimelineId::generate();
    7469            1 :         let current_timeline = tenant
    7470            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7471            1 :             .await?;
    7472              : 
    7473            1 :         current_lsn += 0x100;
    7474              : 
    7475            1 :         let mut writer = current_timeline.writer().await;
    7476            1 :         writer
    7477            1 :             .put(
    7478            1 :                 gap_at_key,
    7479            1 :                 current_lsn,
    7480            1 :                 &Value::Image(test_img(&format!("{gap_at_key} at {current_lsn}"))),
    7481            1 :                 &ctx,
    7482            1 :             )
    7483            1 :             .await?;
    7484            1 :         writer.finish_write(current_lsn);
    7485            1 :         drop(writer);
    7486              : 
    7487            1 :         let mut latest_lsns = HashMap::new();
    7488            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7489              : 
    7490            1 :         current_timeline.freeze_and_flush().await?;
    7491              : 
    7492            1 :         let child_timeline_id = TimelineId::generate();
    7493              : 
    7494            1 :         tenant
    7495            1 :             .branch_timeline_test(
    7496            1 :                 &current_timeline,
    7497            1 :                 child_timeline_id,
    7498            1 :                 Some(current_lsn),
    7499            1 :                 &ctx,
    7500            1 :             )
    7501            1 :             .await?;
    7502            1 :         let child_timeline = tenant
    7503            1 :             .get_timeline(child_timeline_id, true)
    7504            1 :             .expect("Should have the branched timeline");
    7505              : 
    7506        10001 :         for i in 0..KEY_COUNT {
    7507        10000 :             if current_key == gap_at_key {
    7508            1 :                 current_key = current_key.next();
    7509            1 :                 continue;
    7510         9999 :             }
    7511              : 
    7512         9999 :             current_lsn += 0x10;
    7513              : 
    7514         9999 :             let mut writer = child_timeline.writer().await;
    7515         9999 :             writer
    7516         9999 :                 .put(
    7517         9999 :                     current_key,
    7518         9999 :                     current_lsn,
    7519         9999 :                     &Value::Image(test_img(&format!("{current_key} at {current_lsn}"))),
    7520         9999 :                     &ctx,
    7521         9999 :                 )
    7522         9999 :                 .await?;
    7523         9999 :             writer.finish_write(current_lsn);
    7524         9999 :             drop(writer);
    7525              : 
    7526         9999 :             latest_lsns.insert(current_key, current_lsn);
    7527         9999 :             current_key = current_key.next();
    7528              : 
    7529              :             // Flush every now and then to encourage layer file creation.
    7530         9999 :             if i % 500 == 0 {
    7531           20 :                 child_timeline.freeze_and_flush().await?;
    7532         9979 :             }
    7533              :         }
    7534              : 
    7535            1 :         child_timeline.freeze_and_flush().await?;
    7536            1 :         let mut flags = EnumSet::new();
    7537            1 :         flags.insert(CompactFlags::ForceRepartition);
    7538            1 :         child_timeline
    7539            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7540            1 :             .await?;
    7541              : 
    7542            1 :         let key_near_end = {
    7543            1 :             let mut tmp = current_key;
    7544            1 :             tmp.field6 -= 10;
    7545            1 :             tmp
    7546              :         };
    7547              : 
    7548            1 :         let key_near_gap = {
    7549            1 :             let mut tmp = gap_at_key;
    7550            1 :             tmp.field6 -= 10;
    7551            1 :             tmp
    7552              :         };
    7553              : 
    7554            1 :         let read = KeySpace {
    7555            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7556            1 :         };
    7557              : 
    7558            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7559              : 
    7560            1 :         let results = child_timeline
    7561            1 :             .get_vectored_impl(
    7562            1 :                 query,
    7563            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7564            1 :                 &ctx,
    7565            1 :             )
    7566            1 :             .await?;
    7567              : 
    7568           22 :         for (key, img_res) in results {
    7569           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7570           21 :             assert_eq!(img_res?, expected);
    7571            1 :         }
    7572            1 : 
    7573            1 :         Ok(())
    7574            1 :     }
    7575              : 
    7576              :     // Test that vectored get descends into ancestor timelines correctly and
    7577              :     // does not return an image that's newer than requested.
    7578              :     //
    7579              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7580              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7581              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7582              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7583              :     // order to avoid returning an image that's too new. The test below constructs such
    7584              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7585              :     // ```
    7586              :     //    LSN
    7587              :     //     ^
    7588              :     //     |
    7589              :     //     |
    7590              :     // 500 | --------------------------------------> branch point
    7591              :     // 400 |        X
    7592              :     // 300 |        X
    7593              :     // 200 | --------------------------------------> requested lsn
    7594              :     // 100 |        X
    7595              :     //     |---------------------------------------> Key
    7596              :     //              |
    7597              :     //              ------> requested key
    7598              :     //
    7599              :     // Legend:
    7600              :     // * X - page images
    7601              :     // ```
    7602              :     #[tokio::test]
    7603            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7604            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7605            1 :         let (tenant, ctx) = harness.load().await;
    7606            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7607              : 
    7608            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7609            1 :         let end_key = start_key.add(1000);
    7610            1 :         let child_gap_at_key = start_key.add(500);
    7611            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7612              : 
    7613            1 :         let mut current_lsn = Lsn(0x10);
    7614              : 
    7615            1 :         let timeline_id = TimelineId::generate();
    7616            1 :         let parent_timeline = tenant
    7617            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7618            1 :             .await?;
    7619              : 
    7620            1 :         current_lsn += 0x100;
    7621              : 
    7622            4 :         for _ in 0..3 {
    7623            3 :             let mut key = start_key;
    7624         3003 :             while key < end_key {
    7625         3000 :                 current_lsn += 0x10;
    7626              : 
    7627         3000 :                 let image_value = format!("{child_gap_at_key} at {current_lsn}");
    7628              : 
    7629         3000 :                 let mut writer = parent_timeline.writer().await;
    7630         3000 :                 writer
    7631         3000 :                     .put(
    7632         3000 :                         key,
    7633         3000 :                         current_lsn,
    7634         3000 :                         &Value::Image(test_img(&image_value)),
    7635         3000 :                         &ctx,
    7636         3000 :                     )
    7637         3000 :                     .await?;
    7638         3000 :                 writer.finish_write(current_lsn);
    7639              : 
    7640         3000 :                 if key == child_gap_at_key {
    7641            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7642         2997 :                 }
    7643              : 
    7644         3000 :                 key = key.next();
    7645              :             }
    7646              : 
    7647            3 :             parent_timeline.freeze_and_flush().await?;
    7648              :         }
    7649              : 
    7650            1 :         let child_timeline_id = TimelineId::generate();
    7651              : 
    7652            1 :         let child_timeline = tenant
    7653            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7654            1 :             .await?;
    7655              : 
    7656            1 :         let mut key = start_key;
    7657         1001 :         while key < end_key {
    7658         1000 :             if key == child_gap_at_key {
    7659            1 :                 key = key.next();
    7660            1 :                 continue;
    7661          999 :             }
    7662              : 
    7663          999 :             current_lsn += 0x10;
    7664              : 
    7665          999 :             let mut writer = child_timeline.writer().await;
    7666          999 :             writer
    7667          999 :                 .put(
    7668          999 :                     key,
    7669          999 :                     current_lsn,
    7670          999 :                     &Value::Image(test_img(&format!("{key} at {current_lsn}"))),
    7671          999 :                     &ctx,
    7672          999 :                 )
    7673          999 :                 .await?;
    7674          999 :             writer.finish_write(current_lsn);
    7675              : 
    7676          999 :             key = key.next();
    7677              :         }
    7678              : 
    7679            1 :         child_timeline.freeze_and_flush().await?;
    7680              : 
    7681            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7682            1 :         let mut query_lsns = Vec::new();
    7683            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7684           18 :             for offset in lsn_offsets {
    7685           15 :                 query_lsns.push(Lsn(image_lsn
    7686           15 :                     .0
    7687           15 :                     .checked_add_signed(offset)
    7688           15 :                     .expect("Shouldn't overflow")));
    7689           15 :             }
    7690            1 :         }
    7691            1 : 
    7692           16 :         for query_lsn in query_lsns {
    7693           15 :             let query = VersionedKeySpaceQuery::uniform(
    7694           15 :                 KeySpace {
    7695           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7696           15 :                 },
    7697           15 :                 query_lsn,
    7698            1 :             );
    7699            1 : 
    7700           15 :             let results = child_timeline
    7701           15 :                 .get_vectored_impl(
    7702           15 :                     query,
    7703           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7704           15 :                     &ctx,
    7705           15 :                 )
    7706           15 :                 .await;
    7707            1 : 
    7708           15 :             let expected_item = parent_gap_lsns
    7709           15 :                 .iter()
    7710           15 :                 .rev()
    7711           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7712            1 : 
    7713           15 :             info!(
    7714            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7715            1 :                 query_lsn, expected_item
    7716            1 :             );
    7717            1 : 
    7718           15 :             match expected_item {
    7719           13 :                 Some((_, img_value)) => {
    7720           13 :                     let key_results = results.expect("No vectored get error expected");
    7721           13 :                     let key_result = &key_results[&child_gap_at_key];
    7722           13 :                     let returned_img = key_result
    7723           13 :                         .as_ref()
    7724           13 :                         .expect("No page reconstruct error expected");
    7725            1 : 
    7726           13 :                     info!(
    7727            1 :                         "Vectored read at LSN {} returned image {}",
    7728            1 :                         query_lsn,
    7729            1 :                         std::str::from_utf8(returned_img)?
    7730            1 :                     );
    7731           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7732            1 :                 }
    7733            1 :                 None => {
    7734            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7735            1 :                 }
    7736            1 :             }
    7737            1 :         }
    7738            1 : 
    7739            1 :         Ok(())
    7740            1 :     }
    7741              : 
    7742              :     #[tokio::test]
    7743            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7744            1 :         let names_algorithms = [
    7745            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7746            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7747            1 :         ];
    7748            3 :         for (name, algorithm) in names_algorithms {
    7749            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7750            1 :         }
    7751            1 :         Ok(())
    7752            1 :     }
    7753              : 
    7754            2 :     async fn test_random_updates_algorithm(
    7755            2 :         name: &'static str,
    7756            2 :         compaction_algorithm: CompactionAlgorithm,
    7757            2 :     ) -> anyhow::Result<()> {
    7758            2 :         let mut harness = TenantHarness::create(name).await?;
    7759            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7760            2 :             kind: compaction_algorithm,
    7761            2 :         });
    7762            2 :         let (tenant, ctx) = harness.load().await;
    7763            2 :         let tline = tenant
    7764            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7765            2 :             .await?;
    7766              : 
    7767              :         const NUM_KEYS: usize = 1000;
    7768            2 :         let cancel = CancellationToken::new();
    7769              : 
    7770            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7771            2 :         let mut test_key_end = test_key;
    7772            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7773            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7774              : 
    7775            2 :         let mut keyspace = KeySpaceAccum::new();
    7776              : 
    7777              :         // Track when each page was last modified. Used to assert that
    7778              :         // a read sees the latest page version.
    7779            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7780              : 
    7781            2 :         let mut lsn = Lsn(0x10);
    7782              :         #[allow(clippy::needless_range_loop)]
    7783         2002 :         for blknum in 0..NUM_KEYS {
    7784         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7785         2000 :             test_key.field6 = blknum as u32;
    7786         2000 :             let mut writer = tline.writer().await;
    7787         2000 :             writer
    7788         2000 :                 .put(
    7789         2000 :                     test_key,
    7790         2000 :                     lsn,
    7791         2000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7792         2000 :                     &ctx,
    7793         2000 :                 )
    7794         2000 :                 .await?;
    7795         2000 :             writer.finish_write(lsn);
    7796         2000 :             updated[blknum] = lsn;
    7797         2000 :             drop(writer);
    7798              : 
    7799         2000 :             keyspace.add_key(test_key);
    7800              :         }
    7801              : 
    7802          102 :         for _ in 0..50 {
    7803       100100 :             for _ in 0..NUM_KEYS {
    7804       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7805       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7806       100000 :                 test_key.field6 = blknum as u32;
    7807       100000 :                 let mut writer = tline.writer().await;
    7808       100000 :                 writer
    7809       100000 :                     .put(
    7810       100000 :                         test_key,
    7811       100000 :                         lsn,
    7812       100000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7813       100000 :                         &ctx,
    7814       100000 :                     )
    7815       100000 :                     .await?;
    7816       100000 :                 writer.finish_write(lsn);
    7817       100000 :                 drop(writer);
    7818       100000 :                 updated[blknum] = lsn;
    7819              :             }
    7820              : 
    7821              :             // Read all the blocks
    7822       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7823       100000 :                 test_key.field6 = blknum as u32;
    7824       100000 :                 assert_eq!(
    7825       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7826       100000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7827              :                 );
    7828              :             }
    7829              : 
    7830              :             // Perform a cycle of flush, and GC
    7831          100 :             tline.freeze_and_flush().await?;
    7832          100 :             tenant
    7833          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7834          100 :                 .await?;
    7835              :         }
    7836              : 
    7837            2 :         Ok(())
    7838            2 :     }
    7839              : 
    7840              :     #[tokio::test]
    7841            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7842            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7843            1 :             .await?
    7844            1 :             .load()
    7845            1 :             .await;
    7846            1 :         let mut tline = tenant
    7847            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7848            1 :             .await?;
    7849              : 
    7850              :         const NUM_KEYS: usize = 1000;
    7851              : 
    7852            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7853              : 
    7854            1 :         let mut keyspace = KeySpaceAccum::new();
    7855              : 
    7856            1 :         let cancel = CancellationToken::new();
    7857              : 
    7858              :         // Track when each page was last modified. Used to assert that
    7859              :         // a read sees the latest page version.
    7860            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7861              : 
    7862            1 :         let mut lsn = Lsn(0x10);
    7863            1 :         #[allow(clippy::needless_range_loop)]
    7864         1001 :         for blknum in 0..NUM_KEYS {
    7865         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7866         1000 :             test_key.field6 = blknum as u32;
    7867         1000 :             let mut writer = tline.writer().await;
    7868         1000 :             writer
    7869         1000 :                 .put(
    7870         1000 :                     test_key,
    7871         1000 :                     lsn,
    7872         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7873         1000 :                     &ctx,
    7874         1000 :                 )
    7875         1000 :                 .await?;
    7876         1000 :             writer.finish_write(lsn);
    7877         1000 :             updated[blknum] = lsn;
    7878         1000 :             drop(writer);
    7879            1 : 
    7880         1000 :             keyspace.add_key(test_key);
    7881            1 :         }
    7882            1 : 
    7883           51 :         for _ in 0..50 {
    7884           50 :             let new_tline_id = TimelineId::generate();
    7885           50 :             tenant
    7886           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7887           50 :                 .await?;
    7888           50 :             tline = tenant
    7889           50 :                 .get_timeline(new_tline_id, true)
    7890           50 :                 .expect("Should have the branched timeline");
    7891            1 : 
    7892        50050 :             for _ in 0..NUM_KEYS {
    7893        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7894        50000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7895        50000 :                 test_key.field6 = blknum as u32;
    7896        50000 :                 let mut writer = tline.writer().await;
    7897        50000 :                 writer
    7898        50000 :                     .put(
    7899        50000 :                         test_key,
    7900        50000 :                         lsn,
    7901        50000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7902        50000 :                         &ctx,
    7903        50000 :                     )
    7904        50000 :                     .await?;
    7905        50000 :                 println!("updating {blknum} at {lsn}");
    7906        50000 :                 writer.finish_write(lsn);
    7907        50000 :                 drop(writer);
    7908        50000 :                 updated[blknum] = lsn;
    7909            1 :             }
    7910            1 : 
    7911            1 :             // Read all the blocks
    7912        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7913        50000 :                 test_key.field6 = blknum as u32;
    7914        50000 :                 assert_eq!(
    7915        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7916        50000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7917            1 :                 );
    7918            1 :             }
    7919            1 : 
    7920            1 :             // Perform a cycle of flush, compact, and GC
    7921           50 :             tline.freeze_and_flush().await?;
    7922           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7923           50 :             tenant
    7924           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7925           50 :                 .await?;
    7926            1 :         }
    7927            1 : 
    7928            1 :         Ok(())
    7929            1 :     }
    7930              : 
    7931              :     #[tokio::test]
    7932            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7933            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7934            1 :             .await?
    7935            1 :             .load()
    7936            1 :             .await;
    7937            1 :         let mut tline = tenant
    7938            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7939            1 :             .await?;
    7940              : 
    7941              :         const NUM_KEYS: usize = 100;
    7942              :         const NUM_TLINES: usize = 50;
    7943              : 
    7944            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7945              :         // Track page mutation lsns across different timelines.
    7946            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7947              : 
    7948            1 :         let mut lsn = Lsn(0x10);
    7949              : 
    7950            1 :         #[allow(clippy::needless_range_loop)]
    7951           51 :         for idx in 0..NUM_TLINES {
    7952           50 :             let new_tline_id = TimelineId::generate();
    7953           50 :             tenant
    7954           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7955           50 :                 .await?;
    7956           50 :             tline = tenant
    7957           50 :                 .get_timeline(new_tline_id, true)
    7958           50 :                 .expect("Should have the branched timeline");
    7959            1 : 
    7960         5050 :             for _ in 0..NUM_KEYS {
    7961         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7962         5000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7963         5000 :                 test_key.field6 = blknum as u32;
    7964         5000 :                 let mut writer = tline.writer().await;
    7965         5000 :                 writer
    7966         5000 :                     .put(
    7967         5000 :                         test_key,
    7968         5000 :                         lsn,
    7969         5000 :                         &Value::Image(test_img(&format!("{idx} {blknum} at {lsn}"))),
    7970         5000 :                         &ctx,
    7971         5000 :                     )
    7972         5000 :                     .await?;
    7973         5000 :                 println!("updating [{idx}][{blknum}] at {lsn}");
    7974         5000 :                 writer.finish_write(lsn);
    7975         5000 :                 drop(writer);
    7976         5000 :                 updated[idx][blknum] = lsn;
    7977            1 :             }
    7978            1 :         }
    7979            1 : 
    7980            1 :         // Read pages from leaf timeline across all ancestors.
    7981           50 :         for (idx, lsns) in updated.iter().enumerate() {
    7982         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7983            1 :                 // Skip empty mutations.
    7984         5000 :                 if lsn.0 == 0 {
    7985         1797 :                     continue;
    7986         3203 :                 }
    7987         3203 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7988         3203 :                 test_key.field6 = blknum as u32;
    7989         3203 :                 assert_eq!(
    7990         3203 :                     tline.get(test_key, *lsn, &ctx).await?,
    7991         3203 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7992            1 :                 );
    7993            1 :             }
    7994            1 :         }
    7995            1 :         Ok(())
    7996            1 :     }
    7997              : 
    7998              :     #[tokio::test]
    7999            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    8000            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    8001            1 :             .await?
    8002            1 :             .load()
    8003            1 :             .await;
    8004              : 
    8005            1 :         let initdb_lsn = Lsn(0x20);
    8006            1 :         let (utline, ctx) = tenant
    8007            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    8008            1 :             .await?;
    8009            1 :         let tline = utline.raw_timeline().unwrap();
    8010              : 
    8011              :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    8012            1 :         tline.maybe_spawn_flush_loop();
    8013              : 
    8014              :         // Make sure the timeline has the minimum set of required keys for operation.
    8015              :         // The only operation you can always do on an empty timeline is to `put` new data.
    8016              :         // Except if you `put` at `initdb_lsn`.
    8017              :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    8018              :         // It uses `repartition()`, which assumes some keys to be present.
    8019              :         // Let's make sure the test timeline can handle that case.
    8020              :         {
    8021            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    8022            1 :             assert_eq!(
    8023              :                 timeline::FlushLoopState::Running {
    8024              :                     expect_initdb_optimization: false,
    8025              :                     initdb_optimization_count: 0,
    8026              :                 },
    8027            1 :                 *state
    8028              :             );
    8029            1 :             *state = timeline::FlushLoopState::Running {
    8030            1 :                 expect_initdb_optimization: true,
    8031            1 :                 initdb_optimization_count: 0,
    8032            1 :             };
    8033              :         }
    8034              : 
    8035              :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    8036              :         // As explained above, the optimization requires some keys to be present.
    8037              :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    8038              :         // This is what `create_test_timeline` does, by the way.
    8039            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    8040            1 :         modification
    8041            1 :             .init_empty_test_timeline()
    8042            1 :             .context("init_empty_test_timeline")?;
    8043            1 :         modification
    8044            1 :             .commit(&ctx)
    8045            1 :             .await
    8046            1 :             .context("commit init_empty_test_timeline modification")?;
    8047              : 
    8048              :         // Do the flush. The flush code will check the expectations that we set above.
    8049            1 :         tline.freeze_and_flush().await?;
    8050              : 
    8051              :         // assert freeze_and_flush exercised the initdb optimization
    8052            1 :         {
    8053            1 :             let state = tline.flush_loop_state.lock().unwrap();
    8054            1 :             let timeline::FlushLoopState::Running {
    8055            1 :                 expect_initdb_optimization,
    8056            1 :                 initdb_optimization_count,
    8057            1 :             } = *state
    8058            1 :             else {
    8059            1 :                 panic!("unexpected state: {:?}", *state);
    8060            1 :             };
    8061            1 :             assert!(expect_initdb_optimization);
    8062            1 :             assert!(initdb_optimization_count > 0);
    8063            1 :         }
    8064            1 :         Ok(())
    8065            1 :     }
    8066              : 
    8067              :     #[tokio::test]
    8068            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    8069            1 :         let name = "test_create_guard_crash";
    8070            1 :         let harness = TenantHarness::create(name).await?;
    8071              :         {
    8072            1 :             let (tenant, ctx) = harness.load().await;
    8073            1 :             let (tline, _ctx) = tenant
    8074            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    8075            1 :                 .await?;
    8076              :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    8077            1 :             let raw_tline = tline.raw_timeline().unwrap();
    8078            1 :             raw_tline
    8079            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    8080            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))
    8081            1 :                 .await;
    8082            1 :             std::mem::forget(tline);
    8083              :         }
    8084              : 
    8085            1 :         let (tenant, _) = harness.load().await;
    8086            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    8087            0 :             Ok(_) => panic!("timeline should've been removed during load"),
    8088            1 :             Err(e) => {
    8089            1 :                 assert_eq!(
    8090              :                     e,
    8091            1 :                     GetTimelineError::NotFound {
    8092            1 :                         tenant_id: tenant.tenant_shard_id,
    8093            1 :                         timeline_id: TIMELINE_ID,
    8094            1 :                     }
    8095              :                 )
    8096              :             }
    8097              :         }
    8098              : 
    8099            1 :         assert!(
    8100            1 :             !harness
    8101            1 :                 .conf
    8102            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    8103            1 :                 .exists()
    8104              :         );
    8105              : 
    8106            2 :         Ok(())
    8107            1 :     }
    8108              : 
    8109              :     #[tokio::test]
    8110            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    8111            1 :         let names_algorithms = [
    8112            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    8113            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    8114            1 :         ];
    8115            3 :         for (name, algorithm) in names_algorithms {
    8116            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    8117            1 :         }
    8118            1 :         Ok(())
    8119            1 :     }
    8120              : 
    8121            2 :     async fn test_read_at_max_lsn_algorithm(
    8122            2 :         name: &'static str,
    8123            2 :         compaction_algorithm: CompactionAlgorithm,
    8124            2 :     ) -> anyhow::Result<()> {
    8125            2 :         let mut harness = TenantHarness::create(name).await?;
    8126            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    8127            2 :             kind: compaction_algorithm,
    8128            2 :         });
    8129            2 :         let (tenant, ctx) = harness.load().await;
    8130            2 :         let tline = tenant
    8131            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    8132            2 :             .await?;
    8133              : 
    8134            2 :         let lsn = Lsn(0x10);
    8135            2 :         let compact = false;
    8136            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    8137              : 
    8138            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8139            2 :         let read_lsn = Lsn(u64::MAX - 1);
    8140              : 
    8141            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    8142            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    8143              : 
    8144            2 :         Ok(())
    8145            2 :     }
    8146              : 
    8147              :     #[tokio::test]
    8148            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    8149            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    8150            1 :         let (tenant, ctx) = harness.load().await;
    8151            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8152            1 :         let tline = tenant
    8153            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8154            1 :             .await?;
    8155              : 
    8156              :         const NUM_KEYS: usize = 1000;
    8157              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8158              : 
    8159            1 :         let cancel = CancellationToken::new();
    8160              : 
    8161            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8162            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8163            1 :         let mut test_key = base_key;
    8164              : 
    8165              :         // Track when each page was last modified. Used to assert that
    8166              :         // a read sees the latest page version.
    8167            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    8168              : 
    8169            1 :         let mut lsn = Lsn(0x10);
    8170              :         #[allow(clippy::needless_range_loop)]
    8171         1001 :         for blknum in 0..NUM_KEYS {
    8172         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8173         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8174         1000 :             let mut writer = tline.writer().await;
    8175         1000 :             writer
    8176         1000 :                 .put(
    8177         1000 :                     test_key,
    8178         1000 :                     lsn,
    8179         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8180         1000 :                     &ctx,
    8181         1000 :                 )
    8182         1000 :                 .await?;
    8183         1000 :             writer.finish_write(lsn);
    8184         1000 :             updated[blknum] = lsn;
    8185         1000 :             drop(writer);
    8186              :         }
    8187              : 
    8188            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8189              : 
    8190           12 :         for iter in 0..=10 {
    8191            1 :             // Read all the blocks
    8192        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8193        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8194        11000 :                 assert_eq!(
    8195        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8196        11000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    8197            1 :                 );
    8198            1 :             }
    8199            1 : 
    8200           11 :             let mut cnt = 0;
    8201           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8202            1 : 
    8203        11000 :             for (key, value) in tline
    8204           11 :                 .get_vectored_impl(
    8205           11 :                     query,
    8206           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8207           11 :                     &ctx,
    8208           11 :                 )
    8209           11 :                 .await?
    8210            1 :             {
    8211        11000 :                 let blknum = key.field6 as usize;
    8212        11000 :                 let value = value?;
    8213        11000 :                 assert!(blknum % STEP == 0);
    8214        11000 :                 let blknum = blknum / STEP;
    8215        11000 :                 assert_eq!(
    8216            1 :                     value,
    8217        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8218            1 :                 );
    8219        11000 :                 cnt += 1;
    8220            1 :             }
    8221            1 : 
    8222           11 :             assert_eq!(cnt, NUM_KEYS);
    8223            1 : 
    8224        11011 :             for _ in 0..NUM_KEYS {
    8225        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8226        11000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8227        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8228        11000 :                 let mut writer = tline.writer().await;
    8229        11000 :                 writer
    8230        11000 :                     .put(
    8231        11000 :                         test_key,
    8232        11000 :                         lsn,
    8233        11000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8234        11000 :                         &ctx,
    8235        11000 :                     )
    8236        11000 :                     .await?;
    8237        11000 :                 writer.finish_write(lsn);
    8238        11000 :                 drop(writer);
    8239        11000 :                 updated[blknum] = lsn;
    8240            1 :             }
    8241            1 : 
    8242            1 :             // Perform two cycles of flush, compact, and GC
    8243           33 :             for round in 0..2 {
    8244           22 :                 tline.freeze_and_flush().await?;
    8245           22 :                 tline
    8246           22 :                     .compact(
    8247           22 :                         &cancel,
    8248           22 :                         if iter % 5 == 0 && round == 0 {
    8249            3 :                             let mut flags = EnumSet::new();
    8250            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8251            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8252            3 :                             flags
    8253            1 :                         } else {
    8254           19 :                             EnumSet::empty()
    8255            1 :                         },
    8256           22 :                         &ctx,
    8257            1 :                     )
    8258           22 :                     .await?;
    8259           22 :                 tenant
    8260           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8261           22 :                     .await?;
    8262            1 :             }
    8263            1 :         }
    8264            1 : 
    8265            1 :         Ok(())
    8266            1 :     }
    8267              : 
    8268              :     #[tokio::test]
    8269            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8270            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8271            1 :         let (tenant, ctx) = harness.load().await;
    8272            1 :         let tline = tenant
    8273            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8274            1 :             .await?;
    8275              : 
    8276            1 :         let cancel = CancellationToken::new();
    8277              : 
    8278            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8279            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8280            1 :         let test_key = base_key;
    8281            1 :         let mut lsn = Lsn(0x10);
    8282              : 
    8283           21 :         for _ in 0..20 {
    8284           20 :             lsn = Lsn(lsn.0 + 0x10);
    8285           20 :             let mut writer = tline.writer().await;
    8286           20 :             writer
    8287           20 :                 .put(
    8288           20 :                     test_key,
    8289           20 :                     lsn,
    8290           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8291           20 :                     &ctx,
    8292           20 :                 )
    8293           20 :                 .await?;
    8294           20 :             writer.finish_write(lsn);
    8295           20 :             drop(writer);
    8296           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8297              :         }
    8298              : 
    8299            1 :         let before_num_l0_delta_files = tline
    8300            1 :             .layers
    8301            1 :             .read(LayerManagerLockHolder::Testing)
    8302            1 :             .await
    8303            1 :             .layer_map()?
    8304            1 :             .level0_deltas()
    8305            1 :             .len();
    8306              : 
    8307            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8308              : 
    8309            1 :         let after_num_l0_delta_files = tline
    8310            1 :             .layers
    8311            1 :             .read(LayerManagerLockHolder::Testing)
    8312            1 :             .await
    8313            1 :             .layer_map()?
    8314            1 :             .level0_deltas()
    8315            1 :             .len();
    8316              : 
    8317            1 :         assert!(
    8318            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8319            0 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8320              :         );
    8321              : 
    8322            1 :         assert_eq!(
    8323            1 :             tline.get(test_key, lsn, &ctx).await?,
    8324            1 :             test_img(&format!("{} at {}", 0, lsn))
    8325              :         );
    8326              : 
    8327            2 :         Ok(())
    8328            1 :     }
    8329              : 
    8330              :     #[tokio::test]
    8331            1 :     async fn test_aux_file_e2e() {
    8332            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8333              : 
    8334            1 :         let (tenant, ctx) = harness.load().await;
    8335            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8336              : 
    8337            1 :         let mut lsn = Lsn(0x08);
    8338              : 
    8339            1 :         let tline: Arc<Timeline> = tenant
    8340            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8341            1 :             .await
    8342            1 :             .unwrap();
    8343              : 
    8344              :         {
    8345            1 :             lsn += 8;
    8346            1 :             let mut modification = tline.begin_modification(lsn);
    8347            1 :             modification
    8348            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8349            1 :                 .await
    8350            1 :                 .unwrap();
    8351            1 :             modification.commit(&ctx).await.unwrap();
    8352              :         }
    8353              : 
    8354              :         // we can read everything from the storage
    8355            1 :         let files = tline
    8356            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8357            1 :             .await
    8358            1 :             .unwrap();
    8359            1 :         assert_eq!(
    8360            1 :             files.get("pg_logical/mappings/test1"),
    8361            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8362              :         );
    8363              : 
    8364              :         {
    8365            1 :             lsn += 8;
    8366            1 :             let mut modification = tline.begin_modification(lsn);
    8367            1 :             modification
    8368            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8369            1 :                 .await
    8370            1 :                 .unwrap();
    8371            1 :             modification.commit(&ctx).await.unwrap();
    8372              :         }
    8373              : 
    8374            1 :         let files = tline
    8375            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8376            1 :             .await
    8377            1 :             .unwrap();
    8378            1 :         assert_eq!(
    8379            1 :             files.get("pg_logical/mappings/test2"),
    8380            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8381              :         );
    8382              : 
    8383            1 :         let child = tenant
    8384            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8385            1 :             .await
    8386            1 :             .unwrap();
    8387              : 
    8388            1 :         let files = child
    8389            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8390            1 :             .await
    8391            1 :             .unwrap();
    8392            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8393            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8394            1 :     }
    8395              : 
    8396              :     #[tokio::test]
    8397            1 :     async fn test_repl_origin_tombstones() {
    8398            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8399            1 :             .await
    8400            1 :             .unwrap();
    8401              : 
    8402            1 :         let (tenant, ctx) = harness.load().await;
    8403            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8404              : 
    8405            1 :         let mut lsn = Lsn(0x08);
    8406              : 
    8407            1 :         let tline: Arc<Timeline> = tenant
    8408            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8409            1 :             .await
    8410            1 :             .unwrap();
    8411              : 
    8412            1 :         let repl_lsn = Lsn(0x10);
    8413              :         {
    8414            1 :             lsn += 8;
    8415            1 :             let mut modification = tline.begin_modification(lsn);
    8416            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8417            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8418            1 :             modification.commit(&ctx).await.unwrap();
    8419              :         }
    8420              : 
    8421              :         // we can read everything from the storage
    8422            1 :         let repl_origins = tline
    8423            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8424            1 :             .await
    8425            1 :             .unwrap();
    8426            1 :         assert_eq!(repl_origins.len(), 1);
    8427            1 :         assert_eq!(repl_origins[&1], lsn);
    8428              : 
    8429              :         {
    8430            1 :             lsn += 8;
    8431            1 :             let mut modification = tline.begin_modification(lsn);
    8432            1 :             modification.put_for_unit_test(
    8433            1 :                 repl_origin_key(3),
    8434            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8435              :             );
    8436            1 :             modification.commit(&ctx).await.unwrap();
    8437              :         }
    8438            1 :         let result = tline
    8439            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8440            1 :             .await;
    8441            1 :         assert!(result.is_err());
    8442            1 :     }
    8443              : 
    8444              :     #[tokio::test]
    8445            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8446            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8447            1 :         let (tenant, ctx) = harness.load().await;
    8448            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8449            1 :         let tline = tenant
    8450            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8451            1 :             .await?;
    8452              : 
    8453              :         const NUM_KEYS: usize = 1000;
    8454              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8455              : 
    8456            1 :         let cancel = CancellationToken::new();
    8457              : 
    8458            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8459            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8460            1 :         let mut test_key = base_key;
    8461            1 :         let mut lsn = Lsn(0x10);
    8462              : 
    8463            4 :         async fn scan_with_statistics(
    8464            4 :             tline: &Timeline,
    8465            4 :             keyspace: &KeySpace,
    8466            4 :             lsn: Lsn,
    8467            4 :             ctx: &RequestContext,
    8468            4 :             io_concurrency: IoConcurrency,
    8469            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8470            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8471            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8472            4 :             let res = tline
    8473            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8474            4 :                 .await?;
    8475            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8476            4 :         }
    8477              : 
    8478         1001 :         for blknum in 0..NUM_KEYS {
    8479         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8480         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8481         1000 :             let mut writer = tline.writer().await;
    8482         1000 :             writer
    8483         1000 :                 .put(
    8484         1000 :                     test_key,
    8485         1000 :                     lsn,
    8486         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8487         1000 :                     &ctx,
    8488         1000 :                 )
    8489         1000 :                 .await?;
    8490         1000 :             writer.finish_write(lsn);
    8491         1000 :             drop(writer);
    8492              :         }
    8493              : 
    8494            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8495              : 
    8496           11 :         for iter in 1..=10 {
    8497        10010 :             for _ in 0..NUM_KEYS {
    8498        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8499        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8500        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8501        10000 :                 let mut writer = tline.writer().await;
    8502        10000 :                 writer
    8503        10000 :                     .put(
    8504        10000 :                         test_key,
    8505        10000 :                         lsn,
    8506        10000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8507        10000 :                         &ctx,
    8508        10000 :                     )
    8509        10000 :                     .await?;
    8510        10000 :                 writer.finish_write(lsn);
    8511        10000 :                 drop(writer);
    8512            1 :             }
    8513            1 : 
    8514           10 :             tline.freeze_and_flush().await?;
    8515            1 :             // Force layers to L1
    8516           10 :             tline
    8517           10 :                 .compact(
    8518           10 :                     &cancel,
    8519           10 :                     {
    8520           10 :                         let mut flags = EnumSet::new();
    8521           10 :                         flags.insert(CompactFlags::ForceL0Compaction);
    8522           10 :                         flags
    8523           10 :                     },
    8524           10 :                     &ctx,
    8525           10 :                 )
    8526           10 :                 .await?;
    8527            1 : 
    8528           10 :             if iter % 5 == 0 {
    8529            2 :                 let scan_lsn = Lsn(lsn.0 + 1);
    8530            2 :                 info!("scanning at {}", scan_lsn);
    8531            2 :                 let (_, before_delta_file_accessed) =
    8532            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8533            2 :                         .await?;
    8534            2 :                 tline
    8535            2 :                     .compact(
    8536            2 :                         &cancel,
    8537            2 :                         {
    8538            2 :                             let mut flags = EnumSet::new();
    8539            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8540            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8541            2 :                             flags.insert(CompactFlags::ForceL0Compaction);
    8542            2 :                             flags
    8543            2 :                         },
    8544            2 :                         &ctx,
    8545            2 :                     )
    8546            2 :                     .await?;
    8547            2 :                 let (_, after_delta_file_accessed) =
    8548            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8549            2 :                         .await?;
    8550            2 :                 assert!(
    8551            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8552            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8553            1 :                 );
    8554            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.
    8555            2 :                 assert!(
    8556            2 :                     after_delta_file_accessed <= 2,
    8557            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8558            1 :                 );
    8559            8 :             }
    8560            1 :         }
    8561            1 : 
    8562            1 :         Ok(())
    8563            1 :     }
    8564              : 
    8565              :     #[tokio::test]
    8566            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8567            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8568            1 :         let (tenant, ctx) = harness.load().await;
    8569              : 
    8570            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8571            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8572            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8573              : 
    8574            1 :         let tline = tenant
    8575            1 :             .create_test_timeline_with_layers(
    8576            1 :                 TIMELINE_ID,
    8577            1 :                 Lsn(0x10),
    8578            1 :                 DEFAULT_PG_VERSION,
    8579            1 :                 &ctx,
    8580            1 :                 Vec::new(), // in-memory layers
    8581            1 :                 Vec::new(), // delta layers
    8582            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8583            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
    8584            1 :             )
    8585            1 :             .await?;
    8586            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8587              : 
    8588            1 :         let child = tenant
    8589            1 :             .branch_timeline_test_with_layers(
    8590            1 :                 &tline,
    8591            1 :                 NEW_TIMELINE_ID,
    8592            1 :                 Some(Lsn(0x20)),
    8593            1 :                 &ctx,
    8594            1 :                 Vec::new(), // delta layers
    8595            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8596            1 :                 Lsn(0x30),
    8597            1 :             )
    8598            1 :             .await
    8599            1 :             .unwrap();
    8600              : 
    8601            1 :         let lsn = Lsn(0x30);
    8602              : 
    8603              :         // test vectored get on parent timeline
    8604            1 :         assert_eq!(
    8605            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8606            1 :             Some(test_img("data key 1"))
    8607              :         );
    8608            1 :         assert!(
    8609            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8610            1 :                 .await
    8611            1 :                 .unwrap_err()
    8612            1 :                 .is_missing_key_error()
    8613              :         );
    8614            1 :         assert!(
    8615            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8616            1 :                 .await
    8617            1 :                 .unwrap_err()
    8618            1 :                 .is_missing_key_error()
    8619              :         );
    8620              : 
    8621              :         // test vectored get on child timeline
    8622            1 :         assert_eq!(
    8623            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8624            1 :             Some(test_img("data key 1"))
    8625              :         );
    8626            1 :         assert_eq!(
    8627            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8628            1 :             Some(test_img("data key 2"))
    8629              :         );
    8630            1 :         assert!(
    8631            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8632            1 :                 .await
    8633            1 :                 .unwrap_err()
    8634            1 :                 .is_missing_key_error()
    8635              :         );
    8636              : 
    8637            2 :         Ok(())
    8638            1 :     }
    8639              : 
    8640              :     #[tokio::test]
    8641            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8642            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8643            1 :         let (tenant, ctx) = harness.load().await;
    8644            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8645              : 
    8646            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8647            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8648            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8649            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8650              : 
    8651            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8652            1 :         let base_inherited_key_child =
    8653            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8654            1 :         let base_inherited_key_nonexist =
    8655            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8656            1 :         let base_inherited_key_overwrite =
    8657            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8658              : 
    8659            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8660            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8661              : 
    8662            1 :         let tline = tenant
    8663            1 :             .create_test_timeline_with_layers(
    8664            1 :                 TIMELINE_ID,
    8665            1 :                 Lsn(0x10),
    8666            1 :                 DEFAULT_PG_VERSION,
    8667            1 :                 &ctx,
    8668            1 :                 Vec::new(), // in-memory layers
    8669            1 :                 Vec::new(), // delta layers
    8670            1 :                 vec![(
    8671            1 :                     Lsn(0x20),
    8672            1 :                     vec![
    8673            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8674            1 :                         (
    8675            1 :                             base_inherited_key_overwrite,
    8676            1 :                             test_img("metadata key overwrite 1a"),
    8677            1 :                         ),
    8678            1 :                         (base_key, test_img("metadata key 1")),
    8679            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8680            1 :                     ],
    8681            1 :                 )], // image layers
    8682            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
    8683            1 :             )
    8684            1 :             .await?;
    8685              : 
    8686            1 :         let child = tenant
    8687            1 :             .branch_timeline_test_with_layers(
    8688            1 :                 &tline,
    8689            1 :                 NEW_TIMELINE_ID,
    8690            1 :                 Some(Lsn(0x20)),
    8691            1 :                 &ctx,
    8692            1 :                 Vec::new(), // delta layers
    8693            1 :                 vec![(
    8694            1 :                     Lsn(0x30),
    8695            1 :                     vec![
    8696            1 :                         (
    8697            1 :                             base_inherited_key_child,
    8698            1 :                             test_img("metadata inherited key 2"),
    8699            1 :                         ),
    8700            1 :                         (
    8701            1 :                             base_inherited_key_overwrite,
    8702            1 :                             test_img("metadata key overwrite 2a"),
    8703            1 :                         ),
    8704            1 :                         (base_key_child, test_img("metadata key 2")),
    8705            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8706            1 :                     ],
    8707            1 :                 )], // image layers
    8708            1 :                 Lsn(0x30),
    8709            1 :             )
    8710            1 :             .await
    8711            1 :             .unwrap();
    8712              : 
    8713            1 :         let lsn = Lsn(0x30);
    8714              : 
    8715              :         // test vectored get on parent timeline
    8716            1 :         assert_eq!(
    8717            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8718            1 :             Some(test_img("metadata key 1"))
    8719              :         );
    8720            1 :         assert_eq!(
    8721            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8722              :             None
    8723              :         );
    8724            1 :         assert_eq!(
    8725            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8726              :             None
    8727              :         );
    8728            1 :         assert_eq!(
    8729            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8730            1 :             Some(test_img("metadata key overwrite 1b"))
    8731              :         );
    8732            1 :         assert_eq!(
    8733            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8734            1 :             Some(test_img("metadata inherited key 1"))
    8735              :         );
    8736            1 :         assert_eq!(
    8737            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8738              :             None
    8739              :         );
    8740            1 :         assert_eq!(
    8741            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8742              :             None
    8743              :         );
    8744            1 :         assert_eq!(
    8745            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8746            1 :             Some(test_img("metadata key overwrite 1a"))
    8747              :         );
    8748              : 
    8749              :         // test vectored get on child timeline
    8750            1 :         assert_eq!(
    8751            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8752              :             None
    8753              :         );
    8754            1 :         assert_eq!(
    8755            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8756            1 :             Some(test_img("metadata key 2"))
    8757              :         );
    8758            1 :         assert_eq!(
    8759            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8760              :             None
    8761              :         );
    8762            1 :         assert_eq!(
    8763            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8764            1 :             Some(test_img("metadata inherited key 1"))
    8765              :         );
    8766            1 :         assert_eq!(
    8767            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8768            1 :             Some(test_img("metadata inherited key 2"))
    8769              :         );
    8770            1 :         assert_eq!(
    8771            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8772              :             None
    8773              :         );
    8774            1 :         assert_eq!(
    8775            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8776            1 :             Some(test_img("metadata key overwrite 2b"))
    8777              :         );
    8778            1 :         assert_eq!(
    8779            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8780            1 :             Some(test_img("metadata key overwrite 2a"))
    8781              :         );
    8782              : 
    8783              :         // test vectored scan on parent timeline
    8784            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8785            1 :         let query =
    8786            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8787            1 :         let res = tline
    8788            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8789            1 :             .await?;
    8790              : 
    8791            1 :         assert_eq!(
    8792            1 :             res.into_iter()
    8793            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8794            1 :                 .collect::<Vec<_>>(),
    8795            1 :             vec![
    8796            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8797            1 :                 (
    8798            1 :                     base_inherited_key_overwrite,
    8799            1 :                     test_img("metadata key overwrite 1a")
    8800            1 :                 ),
    8801            1 :                 (base_key, test_img("metadata key 1")),
    8802            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8803              :             ]
    8804              :         );
    8805              : 
    8806              :         // test vectored scan on child timeline
    8807            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8808            1 :         let query =
    8809            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8810            1 :         let res = child
    8811            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8812            1 :             .await?;
    8813              : 
    8814            1 :         assert_eq!(
    8815            1 :             res.into_iter()
    8816            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8817            1 :                 .collect::<Vec<_>>(),
    8818            1 :             vec![
    8819            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8820            1 :                 (
    8821            1 :                     base_inherited_key_child,
    8822            1 :                     test_img("metadata inherited key 2")
    8823            1 :                 ),
    8824            1 :                 (
    8825            1 :                     base_inherited_key_overwrite,
    8826            1 :                     test_img("metadata key overwrite 2a")
    8827            1 :                 ),
    8828            1 :                 (base_key_child, test_img("metadata key 2")),
    8829            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8830              :             ]
    8831              :         );
    8832              : 
    8833            2 :         Ok(())
    8834            1 :     }
    8835              : 
    8836           28 :     async fn get_vectored_impl_wrapper(
    8837           28 :         tline: &Arc<Timeline>,
    8838           28 :         key: Key,
    8839           28 :         lsn: Lsn,
    8840           28 :         ctx: &RequestContext,
    8841           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8842           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8843           28 :             tline.conf.get_vectored_concurrent_io,
    8844           28 :             tline.gate.enter().unwrap(),
    8845              :         );
    8846           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8847           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8848           28 :         let mut res = tline
    8849           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8850           28 :             .await?;
    8851           25 :         Ok(res.pop_last().map(|(k, v)| {
    8852           16 :             assert_eq!(k, key);
    8853           16 :             v.unwrap()
    8854           16 :         }))
    8855           28 :     }
    8856              : 
    8857              :     #[tokio::test]
    8858            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8859            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8860            1 :         let (tenant, ctx) = harness.load().await;
    8861            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8862            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8863            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8864            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8865              : 
    8866              :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8867              :         // Lsn 0x30 key0, key3, no key1+key2
    8868              :         // Lsn 0x20 key1+key2 tomestones
    8869              :         // Lsn 0x10 key1 in image, key2 in delta
    8870            1 :         let tline = tenant
    8871            1 :             .create_test_timeline_with_layers(
    8872            1 :                 TIMELINE_ID,
    8873            1 :                 Lsn(0x10),
    8874            1 :                 DEFAULT_PG_VERSION,
    8875            1 :                 &ctx,
    8876            1 :                 Vec::new(), // in-memory layers
    8877            1 :                 // delta layers
    8878            1 :                 vec![
    8879            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8880            1 :                         Lsn(0x10)..Lsn(0x20),
    8881            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8882            1 :                     ),
    8883            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8884            1 :                         Lsn(0x20)..Lsn(0x30),
    8885            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8886            1 :                     ),
    8887            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8888            1 :                         Lsn(0x20)..Lsn(0x30),
    8889            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8890            1 :                     ),
    8891            1 :                 ],
    8892            1 :                 // image layers
    8893            1 :                 vec![
    8894            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8895            1 :                     (
    8896            1 :                         Lsn(0x30),
    8897            1 :                         vec![
    8898            1 :                             (key0, test_img("metadata key 0")),
    8899            1 :                             (key3, test_img("metadata key 3")),
    8900            1 :                         ],
    8901            1 :                     ),
    8902            1 :                 ],
    8903            1 :                 Lsn(0x30),
    8904            1 :             )
    8905            1 :             .await?;
    8906              : 
    8907            1 :         let lsn = Lsn(0x30);
    8908            1 :         let old_lsn = Lsn(0x20);
    8909              : 
    8910            1 :         assert_eq!(
    8911            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8912            1 :             Some(test_img("metadata key 0"))
    8913              :         );
    8914            1 :         assert_eq!(
    8915            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8916              :             None,
    8917              :         );
    8918            1 :         assert_eq!(
    8919            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8920              :             None,
    8921              :         );
    8922            1 :         assert_eq!(
    8923            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8924            1 :             Some(Bytes::new()),
    8925              :         );
    8926            1 :         assert_eq!(
    8927            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8928            1 :             Some(Bytes::new()),
    8929              :         );
    8930            1 :         assert_eq!(
    8931            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8932            1 :             Some(test_img("metadata key 3"))
    8933              :         );
    8934              : 
    8935            2 :         Ok(())
    8936            1 :     }
    8937              : 
    8938              :     #[tokio::test]
    8939            1 :     async fn test_metadata_tombstone_image_creation() {
    8940            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8941            1 :             .await
    8942            1 :             .unwrap();
    8943            1 :         let (tenant, ctx) = harness.load().await;
    8944            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8945              : 
    8946            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8947            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8948            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8949            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8950              : 
    8951            1 :         let tline = tenant
    8952            1 :             .create_test_timeline_with_layers(
    8953            1 :                 TIMELINE_ID,
    8954            1 :                 Lsn(0x10),
    8955            1 :                 DEFAULT_PG_VERSION,
    8956            1 :                 &ctx,
    8957            1 :                 Vec::new(), // in-memory layers
    8958            1 :                 // delta layers
    8959            1 :                 vec![
    8960            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8961            1 :                         Lsn(0x10)..Lsn(0x20),
    8962            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8963            1 :                     ),
    8964            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8965            1 :                         Lsn(0x20)..Lsn(0x30),
    8966            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8967            1 :                     ),
    8968            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8969            1 :                         Lsn(0x20)..Lsn(0x30),
    8970            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8971            1 :                     ),
    8972            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8973            1 :                         Lsn(0x30)..Lsn(0x40),
    8974            1 :                         vec![
    8975            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8976            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8977            1 :                         ],
    8978            1 :                     ),
    8979            1 :                 ],
    8980            1 :                 // image layers
    8981            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8982            1 :                 Lsn(0x40),
    8983            1 :             )
    8984            1 :             .await
    8985            1 :             .unwrap();
    8986              : 
    8987            1 :         let cancel = CancellationToken::new();
    8988              : 
    8989              :         // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
    8990            1 :         tline.force_set_disk_consistent_lsn(Lsn(0x40));
    8991            1 :         tline
    8992            1 :             .compact(
    8993            1 :                 &cancel,
    8994            1 :                 {
    8995            1 :                     let mut flags = EnumSet::new();
    8996            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8997            1 :                     flags.insert(CompactFlags::ForceRepartition);
    8998            1 :                     flags
    8999            1 :                 },
    9000            1 :                 &ctx,
    9001            1 :             )
    9002            1 :             .await
    9003            1 :             .unwrap();
    9004              :         // Image layers are created at repartition LSN
    9005            1 :         let images = tline
    9006            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    9007            1 :             .await
    9008            1 :             .unwrap()
    9009            1 :             .into_iter()
    9010            9 :             .filter(|(k, _)| k.is_metadata_key())
    9011            1 :             .collect::<Vec<_>>();
    9012            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    9013            1 :     }
    9014              : 
    9015              :     #[tokio::test]
    9016            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    9017            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    9018            1 :             .await
    9019            1 :             .unwrap();
    9020            1 :         let (tenant, ctx) = harness.load().await;
    9021            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9022              : 
    9023            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    9024            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    9025              : 
    9026            1 :         let tline = tenant
    9027            1 :             .create_test_timeline_with_layers(
    9028            1 :                 TIMELINE_ID,
    9029            1 :                 Lsn(0x10),
    9030            1 :                 DEFAULT_PG_VERSION,
    9031            1 :                 &ctx,
    9032            1 :                 Vec::new(), // in-memory layers
    9033            1 :                 // delta layers
    9034            1 :                 vec![
    9035            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9036            1 :                         Lsn(0x10)..Lsn(0x20),
    9037            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    9038            1 :                     ),
    9039            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9040            1 :                         Lsn(0x20)..Lsn(0x30),
    9041            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    9042            1 :                     ),
    9043            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9044            1 :                         Lsn(0x20)..Lsn(0x30),
    9045            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    9046            1 :                     ),
    9047            1 :                 ],
    9048            1 :                 // image layers
    9049            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9050            1 :                 Lsn(0x30),
    9051            1 :             )
    9052            1 :             .await
    9053            1 :             .unwrap();
    9054              : 
    9055            1 :         let cancel = CancellationToken::new();
    9056              : 
    9057            1 :         tline
    9058            1 :             .compact(
    9059            1 :                 &cancel,
    9060            1 :                 {
    9061            1 :                     let mut flags = EnumSet::new();
    9062            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9063            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9064            1 :                     flags
    9065            1 :                 },
    9066            1 :                 &ctx,
    9067            1 :             )
    9068            1 :             .await
    9069            1 :             .unwrap();
    9070              : 
    9071              :         // Image layers are created at last_record_lsn
    9072            1 :         let images = tline
    9073            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9074            1 :             .await
    9075            1 :             .unwrap()
    9076            1 :             .into_iter()
    9077            7 :             .filter(|(k, _)| k.is_metadata_key())
    9078            1 :             .collect::<Vec<_>>();
    9079            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    9080            1 :     }
    9081              : 
    9082              :     #[tokio::test]
    9083            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    9084            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    9085            1 :         let (tenant, ctx) = harness.load().await;
    9086            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9087              : 
    9088           51 :         fn get_key(id: u32) -> Key {
    9089              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9090           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9091           51 :             key.field6 = id;
    9092           51 :             key
    9093           51 :         }
    9094              : 
    9095              :         // We create
    9096              :         // - one bottom-most image layer,
    9097              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9098              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9099              :         // - a delta layer D3 above the horizon.
    9100              :         //
    9101              :         //                             | D3 |
    9102              :         //  | D1 |
    9103              :         // -|    |-- gc horizon -----------------
    9104              :         //  |    |                | D2 |
    9105              :         // --------- img layer ------------------
    9106              :         //
    9107              :         // What we should expact from this compaction is:
    9108              :         //                             | D3 |
    9109              :         //  | Part of D1 |
    9110              :         // --------- img layer with D1+D2 at GC horizon------------------
    9111              : 
    9112              :         // img layer at 0x10
    9113            1 :         let img_layer = (0..10)
    9114           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9115            1 :             .collect_vec();
    9116              : 
    9117            1 :         let delta1 = vec![
    9118            1 :             (
    9119            1 :                 get_key(1),
    9120            1 :                 Lsn(0x20),
    9121            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    9122            1 :             ),
    9123            1 :             (
    9124            1 :                 get_key(2),
    9125            1 :                 Lsn(0x30),
    9126            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    9127            1 :             ),
    9128            1 :             (
    9129            1 :                 get_key(3),
    9130            1 :                 Lsn(0x40),
    9131            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    9132            1 :             ),
    9133              :         ];
    9134            1 :         let delta2 = vec![
    9135            1 :             (
    9136            1 :                 get_key(5),
    9137            1 :                 Lsn(0x20),
    9138            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    9139            1 :             ),
    9140            1 :             (
    9141            1 :                 get_key(6),
    9142            1 :                 Lsn(0x20),
    9143            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    9144            1 :             ),
    9145              :         ];
    9146            1 :         let delta3 = vec![
    9147            1 :             (
    9148            1 :                 get_key(8),
    9149            1 :                 Lsn(0x48),
    9150            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    9151            1 :             ),
    9152            1 :             (
    9153            1 :                 get_key(9),
    9154            1 :                 Lsn(0x48),
    9155            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    9156            1 :             ),
    9157              :         ];
    9158              : 
    9159            1 :         let tline = tenant
    9160            1 :             .create_test_timeline_with_layers(
    9161            1 :                 TIMELINE_ID,
    9162            1 :                 Lsn(0x10),
    9163            1 :                 DEFAULT_PG_VERSION,
    9164            1 :                 &ctx,
    9165            1 :                 Vec::new(), // in-memory layers
    9166            1 :                 vec![
    9167            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9168            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9169            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9170            1 :                 ], // delta layers
    9171            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9172            1 :                 Lsn(0x50),
    9173            1 :             )
    9174            1 :             .await?;
    9175              :         {
    9176            1 :             tline
    9177            1 :                 .applied_gc_cutoff_lsn
    9178            1 :                 .lock_for_write()
    9179            1 :                 .store_and_unlock(Lsn(0x30))
    9180            1 :                 .wait()
    9181            1 :                 .await;
    9182              :             // Update GC info
    9183            1 :             let mut guard = tline.gc_info.write().unwrap();
    9184            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    9185            1 :             guard.cutoffs.space = Lsn(0x30);
    9186              :         }
    9187              : 
    9188            1 :         let expected_result = [
    9189            1 :             Bytes::from_static(b"value 0@0x10"),
    9190            1 :             Bytes::from_static(b"value 1@0x20"),
    9191            1 :             Bytes::from_static(b"value 2@0x30"),
    9192            1 :             Bytes::from_static(b"value 3@0x40"),
    9193            1 :             Bytes::from_static(b"value 4@0x10"),
    9194            1 :             Bytes::from_static(b"value 5@0x20"),
    9195            1 :             Bytes::from_static(b"value 6@0x20"),
    9196            1 :             Bytes::from_static(b"value 7@0x10"),
    9197            1 :             Bytes::from_static(b"value 8@0x48"),
    9198            1 :             Bytes::from_static(b"value 9@0x48"),
    9199            1 :         ];
    9200              : 
    9201           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9202           10 :             assert_eq!(
    9203           10 :                 tline
    9204           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9205           10 :                     .await
    9206           10 :                     .unwrap(),
    9207              :                 expected
    9208              :             );
    9209              :         }
    9210              : 
    9211            1 :         let cancel = CancellationToken::new();
    9212            1 :         tline
    9213            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9214            1 :             .await
    9215            1 :             .unwrap();
    9216              : 
    9217           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9218           10 :             assert_eq!(
    9219           10 :                 tline
    9220           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9221           10 :                     .await
    9222           10 :                     .unwrap(),
    9223              :                 expected
    9224              :             );
    9225              :         }
    9226              : 
    9227              :         // Check if the image layer at the GC horizon contains exactly what we want
    9228            1 :         let image_at_gc_horizon = tline
    9229            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9230            1 :             .await
    9231            1 :             .unwrap()
    9232            1 :             .into_iter()
    9233           17 :             .filter(|(k, _)| k.is_metadata_key())
    9234            1 :             .collect::<Vec<_>>();
    9235              : 
    9236            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9237            1 :         let expected_result = [
    9238            1 :             Bytes::from_static(b"value 0@0x10"),
    9239            1 :             Bytes::from_static(b"value 1@0x20"),
    9240            1 :             Bytes::from_static(b"value 2@0x30"),
    9241            1 :             Bytes::from_static(b"value 3@0x10"),
    9242            1 :             Bytes::from_static(b"value 4@0x10"),
    9243            1 :             Bytes::from_static(b"value 5@0x20"),
    9244            1 :             Bytes::from_static(b"value 6@0x20"),
    9245            1 :             Bytes::from_static(b"value 7@0x10"),
    9246            1 :             Bytes::from_static(b"value 8@0x10"),
    9247            1 :             Bytes::from_static(b"value 9@0x10"),
    9248            1 :         ];
    9249           11 :         for idx in 0..10 {
    9250           10 :             assert_eq!(
    9251           10 :                 image_at_gc_horizon[idx],
    9252           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9253              :             );
    9254              :         }
    9255              : 
    9256              :         // Check if old layers are removed / new layers have the expected LSN
    9257            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9258            1 :         assert_eq!(
    9259              :             all_layers,
    9260            1 :             vec![
    9261              :                 // Image layer at GC horizon
    9262            1 :                 PersistentLayerKey {
    9263            1 :                     key_range: Key::MIN..Key::MAX,
    9264            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9265            1 :                     is_delta: false
    9266            1 :                 },
    9267              :                 // The delta layer below the horizon
    9268            1 :                 PersistentLayerKey {
    9269            1 :                     key_range: get_key(3)..get_key(4),
    9270            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9271            1 :                     is_delta: true
    9272            1 :                 },
    9273              :                 // The delta3 layer that should not be picked for the compaction
    9274            1 :                 PersistentLayerKey {
    9275            1 :                     key_range: get_key(8)..get_key(10),
    9276            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9277            1 :                     is_delta: true
    9278            1 :                 }
    9279              :             ]
    9280              :         );
    9281              : 
    9282              :         // increase GC horizon and compact again
    9283              :         {
    9284            1 :             tline
    9285            1 :                 .applied_gc_cutoff_lsn
    9286            1 :                 .lock_for_write()
    9287            1 :                 .store_and_unlock(Lsn(0x40))
    9288            1 :                 .wait()
    9289            1 :                 .await;
    9290              :             // Update GC info
    9291            1 :             let mut guard = tline.gc_info.write().unwrap();
    9292            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9293            1 :             guard.cutoffs.space = Lsn(0x40);
    9294              :         }
    9295            1 :         tline
    9296            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9297            1 :             .await
    9298            1 :             .unwrap();
    9299              : 
    9300            2 :         Ok(())
    9301            1 :     }
    9302              : 
    9303              :     #[cfg(feature = "testing")]
    9304              :     #[tokio::test]
    9305            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9306            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9307            1 :         let (tenant, ctx) = harness.load().await;
    9308              : 
    9309           17 :         fn get_key(id: u32) -> Key {
    9310              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9311           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9312           17 :             key.field6 = id;
    9313           17 :             key
    9314           17 :         }
    9315              : 
    9316            1 :         let delta1 = vec![
    9317            1 :             (
    9318            1 :                 get_key(1),
    9319            1 :                 Lsn(0x20),
    9320            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9321            1 :             ),
    9322            1 :             (
    9323            1 :                 get_key(1),
    9324            1 :                 Lsn(0x30),
    9325            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9326            1 :             ),
    9327            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9328            1 :             (
    9329            1 :                 get_key(2),
    9330            1 :                 Lsn(0x20),
    9331            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9332            1 :             ),
    9333            1 :             (
    9334            1 :                 get_key(2),
    9335            1 :                 Lsn(0x30),
    9336            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9337            1 :             ),
    9338            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9339            1 :             (
    9340            1 :                 get_key(3),
    9341            1 :                 Lsn(0x20),
    9342            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9343            1 :             ),
    9344            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9345            1 :             (
    9346            1 :                 get_key(4),
    9347            1 :                 Lsn(0x20),
    9348            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9349            1 :             ),
    9350            1 :             (
    9351            1 :                 get_key(4),
    9352            1 :                 Lsn(0x30),
    9353            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9354            1 :             ),
    9355            1 :             (
    9356            1 :                 get_key(5),
    9357            1 :                 Lsn(0x20),
    9358            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9359            1 :             ),
    9360            1 :             (
    9361            1 :                 get_key(5),
    9362            1 :                 Lsn(0x30),
    9363            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9364            1 :             ),
    9365              :         ];
    9366            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9367              : 
    9368            1 :         let tline = tenant
    9369            1 :             .create_test_timeline_with_layers(
    9370            1 :                 TIMELINE_ID,
    9371            1 :                 Lsn(0x10),
    9372            1 :                 DEFAULT_PG_VERSION,
    9373            1 :                 &ctx,
    9374            1 :                 Vec::new(), // in-memory layers
    9375            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9376            1 :                     Lsn(0x10)..Lsn(0x40),
    9377            1 :                     delta1,
    9378            1 :                 )], // delta layers
    9379            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9380            1 :                 Lsn(0x50),
    9381            1 :             )
    9382            1 :             .await?;
    9383              : 
    9384            1 :         assert_eq!(
    9385            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9386            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9387              :         );
    9388            1 :         assert_eq!(
    9389            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9390            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9391              :         );
    9392              : 
    9393              :         // Need to remove the limit of "Neon WAL redo requires base image".
    9394              : 
    9395            1 :         assert_eq!(
    9396            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9397            1 :             Bytes::from_static(b"c")
    9398              :         );
    9399            1 :         assert_eq!(
    9400            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9401            1 :             Bytes::from_static(b"ij")
    9402              :         );
    9403              : 
    9404              :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9405              :         // cannot enable this assertion in the unit test.
    9406              :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9407              : 
    9408            2 :         Ok(())
    9409            1 :     }
    9410              : 
    9411              :     #[tokio::test]
    9412            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9413            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9414            1 :             .await
    9415            1 :             .unwrap()
    9416            1 :             .load()
    9417            1 :             .await;
    9418              :         // set a non-zero lease length to test the feature
    9419            1 :         tenant
    9420            1 :             .update_tenant_config(|mut conf| {
    9421            1 :                 conf.lsn_lease_length = Some(LsnLease::DEFAULT_LENGTH);
    9422            1 :                 Ok(conf)
    9423            1 :             })
    9424            1 :             .unwrap();
    9425              : 
    9426            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9427              : 
    9428            1 :         let end_lsn = Lsn(0x100);
    9429            1 :         let image_layers = (0x20..=0x90)
    9430            1 :             .step_by(0x10)
    9431            8 :             .map(|n| (Lsn(n), vec![(key, test_img(&format!("data key at {n:x}")))]))
    9432            1 :             .collect();
    9433              : 
    9434            1 :         let timeline = tenant
    9435            1 :             .create_test_timeline_with_layers(
    9436            1 :                 TIMELINE_ID,
    9437            1 :                 Lsn(0x10),
    9438            1 :                 DEFAULT_PG_VERSION,
    9439            1 :                 &ctx,
    9440            1 :                 Vec::new(), // in-memory layers
    9441            1 :                 Vec::new(),
    9442            1 :                 image_layers,
    9443            1 :                 end_lsn,
    9444            1 :             )
    9445            1 :             .await?;
    9446              : 
    9447            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9448            1 :         let mut leases = Vec::new();
    9449            3 :         leased_lsns.iter().for_each(|n| {
    9450            3 :             leases.push(
    9451            3 :                 timeline
    9452            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9453            3 :                     .expect("lease request should succeed"),
    9454              :             );
    9455            3 :         });
    9456              : 
    9457            1 :         let updated_lease_0 = timeline
    9458            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9459            1 :             .expect("lease renewal should succeed");
    9460            1 :         assert_eq!(
    9461            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9462            0 :             " Renewing with shorter lease should not change the lease."
    9463              :         );
    9464              : 
    9465            1 :         let updated_lease_1 = timeline
    9466            1 :             .renew_lsn_lease(
    9467            1 :                 Lsn(leased_lsns[1]),
    9468            1 :                 timeline.get_lsn_lease_length() * 2,
    9469            1 :                 &ctx,
    9470            1 :             )
    9471            1 :             .expect("lease renewal should succeed");
    9472            1 :         assert!(
    9473            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9474            0 :             "Renewing with a long lease should renew lease with later expiration time."
    9475              :         );
    9476              : 
    9477              :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9478            1 :         info!(
    9479            0 :             "applied_gc_cutoff_lsn: {}",
    9480            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9481              :         );
    9482            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9483              : 
    9484            1 :         let res = tenant
    9485            1 :             .gc_iteration(
    9486            1 :                 Some(TIMELINE_ID),
    9487            1 :                 0,
    9488            1 :                 Duration::ZERO,
    9489            1 :                 &CancellationToken::new(),
    9490            1 :                 &ctx,
    9491            1 :             )
    9492            1 :             .await
    9493            1 :             .unwrap();
    9494              : 
    9495              :         // Keeping everything <= Lsn(0x80) b/c leases:
    9496              :         // 0/10: initdb layer
    9497              :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9498            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9499              :         // Keeping 0/90 b/c it is the latest layer.
    9500            1 :         assert_eq!(res.layers_not_updated, 1);
    9501              :         // Removed 0/80.
    9502            1 :         assert_eq!(res.layers_removed, 1);
    9503              : 
    9504              :         // Make lease on a already GC-ed LSN.
    9505              :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9506            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9507            1 :         timeline
    9508            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9509            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9510              : 
    9511              :         // Should still be able to renew a currently valid lease
    9512              :         // Assumption: original lease to is still valid for 0/50.
    9513              :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9514            1 :         timeline
    9515            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9516            1 :             .expect("lease renewal with validation should succeed");
    9517              : 
    9518            2 :         Ok(())
    9519            1 :     }
    9520              : 
    9521              :     #[tokio::test]
    9522            1 :     async fn test_failed_flush_should_not_update_disk_consistent_lsn() -> anyhow::Result<()> {
    9523              :         //
    9524              :         // Setup
    9525              :         //
    9526            1 :         let harness = TenantHarness::create_custom(
    9527            1 :             "test_failed_flush_should_not_upload_disk_consistent_lsn",
    9528            1 :             pageserver_api::models::TenantConfig::default(),
    9529            1 :             TenantId::generate(),
    9530            1 :             ShardIdentity::new(ShardNumber(0), ShardCount(4), ShardStripeSize(128)).unwrap(),
    9531            1 :             Generation::new(1),
    9532            1 :         )
    9533            1 :         .await?;
    9534            1 :         let (tenant, ctx) = harness.load().await;
    9535              : 
    9536            1 :         let timeline = tenant
    9537            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9538            1 :             .await?;
    9539            1 :         assert_eq!(timeline.get_shard_identity().count, ShardCount(4));
    9540            1 :         let mut writer = timeline.writer().await;
    9541            1 :         writer
    9542            1 :             .put(
    9543            1 :                 *TEST_KEY,
    9544            1 :                 Lsn(0x20),
    9545            1 :                 &Value::Image(test_img("foo at 0x20")),
    9546            1 :                 &ctx,
    9547            1 :             )
    9548            1 :             .await?;
    9549            1 :         writer.finish_write(Lsn(0x20));
    9550            1 :         drop(writer);
    9551            1 :         timeline.freeze_and_flush().await.unwrap();
    9552              : 
    9553            1 :         timeline.remote_client.wait_completion().await.unwrap();
    9554            1 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    9555            1 :         let remote_consistent_lsn = timeline.get_remote_consistent_lsn_projected();
    9556            1 :         assert_eq!(Some(disk_consistent_lsn), remote_consistent_lsn);
    9557              : 
    9558              :         //
    9559              :         // Test
    9560              :         //
    9561              : 
    9562            1 :         let mut writer = timeline.writer().await;
    9563            1 :         writer
    9564            1 :             .put(
    9565            1 :                 *TEST_KEY,
    9566            1 :                 Lsn(0x30),
    9567            1 :                 &Value::Image(test_img("foo at 0x30")),
    9568            1 :                 &ctx,
    9569            1 :             )
    9570            1 :             .await?;
    9571            1 :         writer.finish_write(Lsn(0x30));
    9572            1 :         drop(writer);
    9573              : 
    9574            1 :         fail::cfg(
    9575              :             "flush-layer-before-update-remote-consistent-lsn",
    9576            1 :             "return()",
    9577              :         )
    9578            1 :         .unwrap();
    9579              : 
    9580            1 :         let flush_res = timeline.freeze_and_flush().await;
    9581              :         // if flush failed, the disk/remote consistent LSN should not be updated
    9582            1 :         assert!(flush_res.is_err());
    9583            1 :         assert_eq!(disk_consistent_lsn, timeline.get_disk_consistent_lsn());
    9584            1 :         assert_eq!(
    9585              :             remote_consistent_lsn,
    9586            1 :             timeline.get_remote_consistent_lsn_projected()
    9587              :         );
    9588              : 
    9589            2 :         Ok(())
    9590            1 :     }
    9591              : 
    9592              :     #[cfg(feature = "testing")]
    9593              :     #[tokio::test]
    9594            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9595            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9596            2 :             "test_simple_bottom_most_compaction_deltas_1",
    9597            2 :             false,
    9598            2 :         )
    9599            2 :         .await
    9600            1 :     }
    9601              : 
    9602              :     #[cfg(feature = "testing")]
    9603              :     #[tokio::test]
    9604            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9605            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9606            2 :             "test_simple_bottom_most_compaction_deltas_2",
    9607            2 :             true,
    9608            2 :         )
    9609            2 :         .await
    9610            1 :     }
    9611              : 
    9612              :     #[cfg(feature = "testing")]
    9613            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9614            2 :         test_name: &'static str,
    9615            2 :         use_delta_bottom_layer: bool,
    9616            2 :     ) -> anyhow::Result<()> {
    9617            2 :         let harness = TenantHarness::create(test_name).await?;
    9618            2 :         let (tenant, ctx) = harness.load().await;
    9619              : 
    9620          138 :         fn get_key(id: u32) -> Key {
    9621              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9622          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9623          138 :             key.field6 = id;
    9624          138 :             key
    9625          138 :         }
    9626              : 
    9627              :         // We create
    9628              :         // - one bottom-most image layer,
    9629              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9630              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9631              :         // - a delta layer D3 above the horizon.
    9632              :         //
    9633              :         //                             | D3 |
    9634              :         //  | D1 |
    9635              :         // -|    |-- gc horizon -----------------
    9636              :         //  |    |                | D2 |
    9637              :         // --------- img layer ------------------
    9638              :         //
    9639              :         // What we should expact from this compaction is:
    9640              :         //                             | D3 |
    9641              :         //  | Part of D1 |
    9642              :         // --------- img layer with D1+D2 at GC horizon------------------
    9643              : 
    9644              :         // img layer at 0x10
    9645            2 :         let img_layer = (0..10)
    9646           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9647            2 :             .collect_vec();
    9648              :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9649            2 :         let delta4 = (0..10)
    9650           20 :             .map(|id| {
    9651           20 :                 (
    9652           20 :                     get_key(id),
    9653           20 :                     Lsn(0x08),
    9654           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9655           20 :                 )
    9656           20 :             })
    9657            2 :             .collect_vec();
    9658              : 
    9659            2 :         let delta1 = vec![
    9660            2 :             (
    9661            2 :                 get_key(1),
    9662            2 :                 Lsn(0x20),
    9663            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9664            2 :             ),
    9665            2 :             (
    9666            2 :                 get_key(2),
    9667            2 :                 Lsn(0x30),
    9668            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9669            2 :             ),
    9670            2 :             (
    9671            2 :                 get_key(3),
    9672            2 :                 Lsn(0x28),
    9673            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9674            2 :             ),
    9675            2 :             (
    9676            2 :                 get_key(3),
    9677            2 :                 Lsn(0x30),
    9678            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9679            2 :             ),
    9680            2 :             (
    9681            2 :                 get_key(3),
    9682            2 :                 Lsn(0x40),
    9683            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9684            2 :             ),
    9685              :         ];
    9686            2 :         let delta2 = vec![
    9687            2 :             (
    9688            2 :                 get_key(5),
    9689            2 :                 Lsn(0x20),
    9690            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9691            2 :             ),
    9692            2 :             (
    9693            2 :                 get_key(6),
    9694            2 :                 Lsn(0x20),
    9695            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9696            2 :             ),
    9697              :         ];
    9698            2 :         let delta3 = vec![
    9699            2 :             (
    9700            2 :                 get_key(8),
    9701            2 :                 Lsn(0x48),
    9702            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9703            2 :             ),
    9704            2 :             (
    9705            2 :                 get_key(9),
    9706            2 :                 Lsn(0x48),
    9707            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9708            2 :             ),
    9709              :         ];
    9710              : 
    9711            2 :         let tline = if use_delta_bottom_layer {
    9712            1 :             tenant
    9713            1 :                 .create_test_timeline_with_layers(
    9714            1 :                     TIMELINE_ID,
    9715            1 :                     Lsn(0x08),
    9716            1 :                     DEFAULT_PG_VERSION,
    9717            1 :                     &ctx,
    9718            1 :                     Vec::new(), // in-memory layers
    9719            1 :                     vec![
    9720            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9721            1 :                             Lsn(0x08)..Lsn(0x10),
    9722            1 :                             delta4,
    9723            1 :                         ),
    9724            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9725            1 :                             Lsn(0x20)..Lsn(0x48),
    9726            1 :                             delta1,
    9727            1 :                         ),
    9728            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9729            1 :                             Lsn(0x20)..Lsn(0x48),
    9730            1 :                             delta2,
    9731            1 :                         ),
    9732            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9733            1 :                             Lsn(0x48)..Lsn(0x50),
    9734            1 :                             delta3,
    9735            1 :                         ),
    9736            1 :                     ], // delta layers
    9737            1 :                     vec![],     // image layers
    9738            1 :                     Lsn(0x50),
    9739            1 :                 )
    9740            1 :                 .await?
    9741              :         } else {
    9742            1 :             tenant
    9743            1 :                 .create_test_timeline_with_layers(
    9744            1 :                     TIMELINE_ID,
    9745            1 :                     Lsn(0x10),
    9746            1 :                     DEFAULT_PG_VERSION,
    9747            1 :                     &ctx,
    9748            1 :                     Vec::new(), // in-memory layers
    9749            1 :                     vec![
    9750            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9751            1 :                             Lsn(0x10)..Lsn(0x48),
    9752            1 :                             delta1,
    9753            1 :                         ),
    9754            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9755            1 :                             Lsn(0x10)..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![(Lsn(0x10), img_layer)], // image layers
    9764            1 :                     Lsn(0x50),
    9765            1 :                 )
    9766            1 :                 .await?
    9767              :         };
    9768              :         {
    9769            2 :             tline
    9770            2 :                 .applied_gc_cutoff_lsn
    9771            2 :                 .lock_for_write()
    9772            2 :                 .store_and_unlock(Lsn(0x30))
    9773            2 :                 .wait()
    9774            2 :                 .await;
    9775              :             // Update GC info
    9776            2 :             let mut guard = tline.gc_info.write().unwrap();
    9777            2 :             *guard = GcInfo {
    9778            2 :                 retain_lsns: vec![],
    9779            2 :                 cutoffs: GcCutoffs {
    9780            2 :                     time: Some(Lsn(0x30)),
    9781            2 :                     space: Lsn(0x30),
    9782            2 :                 },
    9783            2 :                 leases: Default::default(),
    9784            2 :                 within_ancestor_pitr: false,
    9785            2 :             };
    9786              :         }
    9787              : 
    9788            2 :         let expected_result = [
    9789            2 :             Bytes::from_static(b"value 0@0x10"),
    9790            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9791            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9792            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9793            2 :             Bytes::from_static(b"value 4@0x10"),
    9794            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9795            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9796            2 :             Bytes::from_static(b"value 7@0x10"),
    9797            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9798            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9799            2 :         ];
    9800              : 
    9801            2 :         let expected_result_at_gc_horizon = [
    9802            2 :             Bytes::from_static(b"value 0@0x10"),
    9803            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9804            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9805            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9806            2 :             Bytes::from_static(b"value 4@0x10"),
    9807            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9808            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9809            2 :             Bytes::from_static(b"value 7@0x10"),
    9810            2 :             Bytes::from_static(b"value 8@0x10"),
    9811            2 :             Bytes::from_static(b"value 9@0x10"),
    9812            2 :         ];
    9813              : 
    9814           22 :         for idx in 0..10 {
    9815           20 :             assert_eq!(
    9816           20 :                 tline
    9817           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9818           20 :                     .await
    9819           20 :                     .unwrap(),
    9820           20 :                 &expected_result[idx]
    9821              :             );
    9822           20 :             assert_eq!(
    9823           20 :                 tline
    9824           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9825           20 :                     .await
    9826           20 :                     .unwrap(),
    9827           20 :                 &expected_result_at_gc_horizon[idx]
    9828              :             );
    9829              :         }
    9830              : 
    9831            2 :         let cancel = CancellationToken::new();
    9832            2 :         tline
    9833            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9834            2 :             .await
    9835            2 :             .unwrap();
    9836              : 
    9837           22 :         for idx in 0..10 {
    9838           20 :             assert_eq!(
    9839           20 :                 tline
    9840           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9841           20 :                     .await
    9842           20 :                     .unwrap(),
    9843           20 :                 &expected_result[idx]
    9844              :             );
    9845           20 :             assert_eq!(
    9846           20 :                 tline
    9847           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9848           20 :                     .await
    9849           20 :                     .unwrap(),
    9850           20 :                 &expected_result_at_gc_horizon[idx]
    9851              :             );
    9852              :         }
    9853              : 
    9854              :         // increase GC horizon and compact again
    9855              :         {
    9856            2 :             tline
    9857            2 :                 .applied_gc_cutoff_lsn
    9858            2 :                 .lock_for_write()
    9859            2 :                 .store_and_unlock(Lsn(0x40))
    9860            2 :                 .wait()
    9861            2 :                 .await;
    9862              :             // Update GC info
    9863            2 :             let mut guard = tline.gc_info.write().unwrap();
    9864            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9865            2 :             guard.cutoffs.space = Lsn(0x40);
    9866              :         }
    9867            2 :         tline
    9868            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9869            2 :             .await
    9870            2 :             .unwrap();
    9871              : 
    9872            2 :         Ok(())
    9873            2 :     }
    9874              : 
    9875              :     #[cfg(feature = "testing")]
    9876              :     #[tokio::test]
    9877            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9878            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9879            1 :         let (tenant, ctx) = harness.load().await;
    9880            1 :         let tline = tenant
    9881            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9882            1 :             .await?;
    9883            1 :         tline.force_advance_lsn(Lsn(0x70));
    9884            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9885            1 :         let history = vec![
    9886            1 :             (
    9887            1 :                 key,
    9888            1 :                 Lsn(0x10),
    9889            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9890            1 :             ),
    9891            1 :             (
    9892            1 :                 key,
    9893            1 :                 Lsn(0x20),
    9894            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9895            1 :             ),
    9896            1 :             (
    9897            1 :                 key,
    9898            1 :                 Lsn(0x30),
    9899            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9900            1 :             ),
    9901            1 :             (
    9902            1 :                 key,
    9903            1 :                 Lsn(0x40),
    9904            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9905            1 :             ),
    9906            1 :             (
    9907            1 :                 key,
    9908            1 :                 Lsn(0x50),
    9909            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9910            1 :             ),
    9911            1 :             (
    9912            1 :                 key,
    9913            1 :                 Lsn(0x60),
    9914            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9915            1 :             ),
    9916            1 :             (
    9917            1 :                 key,
    9918            1 :                 Lsn(0x70),
    9919            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9920            1 :             ),
    9921            1 :             (
    9922            1 :                 key,
    9923            1 :                 Lsn(0x80),
    9924            1 :                 Value::Image(Bytes::copy_from_slice(
    9925            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9926            1 :                 )),
    9927            1 :             ),
    9928            1 :             (
    9929            1 :                 key,
    9930            1 :                 Lsn(0x90),
    9931            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9932            1 :             ),
    9933              :         ];
    9934            1 :         let res = tline
    9935            1 :             .generate_key_retention(
    9936            1 :                 key,
    9937            1 :                 &history,
    9938            1 :                 Lsn(0x60),
    9939            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9940            1 :                 3,
    9941            1 :                 None,
    9942            1 :                 true,
    9943            1 :             )
    9944            1 :             .await
    9945            1 :             .unwrap();
    9946            1 :         let expected_res = KeyHistoryRetention {
    9947            1 :             below_horizon: vec![
    9948            1 :                 (
    9949            1 :                     Lsn(0x20),
    9950            1 :                     KeyLogAtLsn(vec![(
    9951            1 :                         Lsn(0x20),
    9952            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9953            1 :                     )]),
    9954            1 :                 ),
    9955            1 :                 (
    9956            1 :                     Lsn(0x40),
    9957            1 :                     KeyLogAtLsn(vec![
    9958            1 :                         (
    9959            1 :                             Lsn(0x30),
    9960            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9961            1 :                         ),
    9962            1 :                         (
    9963            1 :                             Lsn(0x40),
    9964            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9965            1 :                         ),
    9966            1 :                     ]),
    9967            1 :                 ),
    9968            1 :                 (
    9969            1 :                     Lsn(0x50),
    9970            1 :                     KeyLogAtLsn(vec![(
    9971            1 :                         Lsn(0x50),
    9972            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9973            1 :                     )]),
    9974            1 :                 ),
    9975            1 :                 (
    9976            1 :                     Lsn(0x60),
    9977            1 :                     KeyLogAtLsn(vec![(
    9978            1 :                         Lsn(0x60),
    9979            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9980            1 :                     )]),
    9981            1 :                 ),
    9982            1 :             ],
    9983            1 :             above_horizon: KeyLogAtLsn(vec![
    9984            1 :                 (
    9985            1 :                     Lsn(0x70),
    9986            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9987            1 :                 ),
    9988            1 :                 (
    9989            1 :                     Lsn(0x80),
    9990            1 :                     Value::Image(Bytes::copy_from_slice(
    9991            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9992            1 :                     )),
    9993            1 :                 ),
    9994            1 :                 (
    9995            1 :                     Lsn(0x90),
    9996            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9997            1 :                 ),
    9998            1 :             ]),
    9999            1 :         };
   10000            1 :         assert_eq!(res, expected_res);
   10001              : 
   10002              :         // We expect GC-compaction to run with the original GC. This would create a situation that
   10003              :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
   10004              :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
   10005              :         // For example, we have
   10006              :         // ```plain
   10007              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
   10008              :         // ```
   10009              :         // Now the GC horizon moves up, and we have
   10010              :         // ```plain
   10011              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
   10012              :         // ```
   10013              :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
   10014              :         // We will end up with
   10015              :         // ```plain
   10016              :         // delta @ 0x30, image @ 0x40 (gc_horizon)
   10017              :         // ```
   10018              :         // Now we run the GC-compaction, and this key does not have a full history.
   10019              :         // We should be able to handle this partial history and drop everything before the
   10020              :         // gc_horizon image.
   10021              : 
   10022            1 :         let history = vec![
   10023            1 :             (
   10024            1 :                 key,
   10025            1 :                 Lsn(0x20),
   10026            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10027            1 :             ),
   10028            1 :             (
   10029            1 :                 key,
   10030            1 :                 Lsn(0x30),
   10031            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10032            1 :             ),
   10033            1 :             (
   10034            1 :                 key,
   10035            1 :                 Lsn(0x40),
   10036            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10037            1 :             ),
   10038            1 :             (
   10039            1 :                 key,
   10040            1 :                 Lsn(0x50),
   10041            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10042            1 :             ),
   10043            1 :             (
   10044            1 :                 key,
   10045            1 :                 Lsn(0x60),
   10046            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10047            1 :             ),
   10048            1 :             (
   10049            1 :                 key,
   10050            1 :                 Lsn(0x70),
   10051            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10052            1 :             ),
   10053            1 :             (
   10054            1 :                 key,
   10055            1 :                 Lsn(0x80),
   10056            1 :                 Value::Image(Bytes::copy_from_slice(
   10057            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10058            1 :                 )),
   10059            1 :             ),
   10060            1 :             (
   10061            1 :                 key,
   10062            1 :                 Lsn(0x90),
   10063            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10064            1 :             ),
   10065              :         ];
   10066            1 :         let res = tline
   10067            1 :             .generate_key_retention(
   10068            1 :                 key,
   10069            1 :                 &history,
   10070            1 :                 Lsn(0x60),
   10071            1 :                 &[Lsn(0x40), Lsn(0x50)],
   10072            1 :                 3,
   10073            1 :                 None,
   10074            1 :                 true,
   10075            1 :             )
   10076            1 :             .await
   10077            1 :             .unwrap();
   10078            1 :         let expected_res = KeyHistoryRetention {
   10079            1 :             below_horizon: vec![
   10080            1 :                 (
   10081            1 :                     Lsn(0x40),
   10082            1 :                     KeyLogAtLsn(vec![(
   10083            1 :                         Lsn(0x40),
   10084            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10085            1 :                     )]),
   10086            1 :                 ),
   10087            1 :                 (
   10088            1 :                     Lsn(0x50),
   10089            1 :                     KeyLogAtLsn(vec![(
   10090            1 :                         Lsn(0x50),
   10091            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10092            1 :                     )]),
   10093            1 :                 ),
   10094            1 :                 (
   10095            1 :                     Lsn(0x60),
   10096            1 :                     KeyLogAtLsn(vec![(
   10097            1 :                         Lsn(0x60),
   10098            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10099            1 :                     )]),
   10100            1 :                 ),
   10101            1 :             ],
   10102            1 :             above_horizon: KeyLogAtLsn(vec![
   10103            1 :                 (
   10104            1 :                     Lsn(0x70),
   10105            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10106            1 :                 ),
   10107            1 :                 (
   10108            1 :                     Lsn(0x80),
   10109            1 :                     Value::Image(Bytes::copy_from_slice(
   10110            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10111            1 :                     )),
   10112            1 :                 ),
   10113            1 :                 (
   10114            1 :                     Lsn(0x90),
   10115            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10116            1 :                 ),
   10117            1 :             ]),
   10118            1 :         };
   10119            1 :         assert_eq!(res, expected_res);
   10120              : 
   10121              :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
   10122              :         // the ancestor image in the test case.
   10123              : 
   10124            1 :         let history = vec![
   10125            1 :             (
   10126            1 :                 key,
   10127            1 :                 Lsn(0x20),
   10128            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10129            1 :             ),
   10130            1 :             (
   10131            1 :                 key,
   10132            1 :                 Lsn(0x30),
   10133            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10134            1 :             ),
   10135            1 :             (
   10136            1 :                 key,
   10137            1 :                 Lsn(0x40),
   10138            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10139            1 :             ),
   10140            1 :             (
   10141            1 :                 key,
   10142            1 :                 Lsn(0x70),
   10143            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10144            1 :             ),
   10145              :         ];
   10146            1 :         let res = tline
   10147            1 :             .generate_key_retention(
   10148            1 :                 key,
   10149            1 :                 &history,
   10150            1 :                 Lsn(0x60),
   10151            1 :                 &[],
   10152            1 :                 3,
   10153            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10154            1 :                 true,
   10155            1 :             )
   10156            1 :             .await
   10157            1 :             .unwrap();
   10158            1 :         let expected_res = KeyHistoryRetention {
   10159            1 :             below_horizon: vec![(
   10160            1 :                 Lsn(0x60),
   10161            1 :                 KeyLogAtLsn(vec![(
   10162            1 :                     Lsn(0x60),
   10163            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
   10164            1 :                 )]),
   10165            1 :             )],
   10166            1 :             above_horizon: KeyLogAtLsn(vec![(
   10167            1 :                 Lsn(0x70),
   10168            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10169            1 :             )]),
   10170            1 :         };
   10171            1 :         assert_eq!(res, expected_res);
   10172              : 
   10173            1 :         let history = vec![
   10174            1 :             (
   10175            1 :                 key,
   10176            1 :                 Lsn(0x20),
   10177            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10178            1 :             ),
   10179            1 :             (
   10180            1 :                 key,
   10181            1 :                 Lsn(0x40),
   10182            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10183            1 :             ),
   10184            1 :             (
   10185            1 :                 key,
   10186            1 :                 Lsn(0x60),
   10187            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10188            1 :             ),
   10189            1 :             (
   10190            1 :                 key,
   10191            1 :                 Lsn(0x70),
   10192            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10193            1 :             ),
   10194              :         ];
   10195            1 :         let res = tline
   10196            1 :             .generate_key_retention(
   10197            1 :                 key,
   10198            1 :                 &history,
   10199            1 :                 Lsn(0x60),
   10200            1 :                 &[Lsn(0x30)],
   10201            1 :                 3,
   10202            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10203            1 :                 true,
   10204            1 :             )
   10205            1 :             .await
   10206            1 :             .unwrap();
   10207            1 :         let expected_res = KeyHistoryRetention {
   10208            1 :             below_horizon: vec![
   10209            1 :                 (
   10210            1 :                     Lsn(0x30),
   10211            1 :                     KeyLogAtLsn(vec![(
   10212            1 :                         Lsn(0x20),
   10213            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10214            1 :                     )]),
   10215            1 :                 ),
   10216            1 :                 (
   10217            1 :                     Lsn(0x60),
   10218            1 :                     KeyLogAtLsn(vec![(
   10219            1 :                         Lsn(0x60),
   10220            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
   10221            1 :                     )]),
   10222            1 :                 ),
   10223            1 :             ],
   10224            1 :             above_horizon: KeyLogAtLsn(vec![(
   10225            1 :                 Lsn(0x70),
   10226            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10227            1 :             )]),
   10228            1 :         };
   10229            1 :         assert_eq!(res, expected_res);
   10230              : 
   10231            2 :         Ok(())
   10232            1 :     }
   10233              : 
   10234              :     #[cfg(feature = "testing")]
   10235              :     #[tokio::test]
   10236            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
   10237            1 :         let harness =
   10238            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
   10239            1 :         let (tenant, ctx) = harness.load().await;
   10240              : 
   10241          259 :         fn get_key(id: u32) -> Key {
   10242              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10243          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10244          259 :             key.field6 = id;
   10245          259 :             key
   10246          259 :         }
   10247              : 
   10248            1 :         let img_layer = (0..10)
   10249           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10250            1 :             .collect_vec();
   10251              : 
   10252            1 :         let delta1 = vec![
   10253            1 :             (
   10254            1 :                 get_key(1),
   10255            1 :                 Lsn(0x20),
   10256            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10257            1 :             ),
   10258            1 :             (
   10259            1 :                 get_key(2),
   10260            1 :                 Lsn(0x30),
   10261            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10262            1 :             ),
   10263            1 :             (
   10264            1 :                 get_key(3),
   10265            1 :                 Lsn(0x28),
   10266            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10267            1 :             ),
   10268            1 :             (
   10269            1 :                 get_key(3),
   10270            1 :                 Lsn(0x30),
   10271            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10272            1 :             ),
   10273            1 :             (
   10274            1 :                 get_key(3),
   10275            1 :                 Lsn(0x40),
   10276            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10277            1 :             ),
   10278              :         ];
   10279            1 :         let delta2 = vec![
   10280            1 :             (
   10281            1 :                 get_key(5),
   10282            1 :                 Lsn(0x20),
   10283            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10284            1 :             ),
   10285            1 :             (
   10286            1 :                 get_key(6),
   10287            1 :                 Lsn(0x20),
   10288            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10289            1 :             ),
   10290              :         ];
   10291            1 :         let delta3 = vec![
   10292            1 :             (
   10293            1 :                 get_key(8),
   10294            1 :                 Lsn(0x48),
   10295            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10296            1 :             ),
   10297            1 :             (
   10298            1 :                 get_key(9),
   10299            1 :                 Lsn(0x48),
   10300            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10301            1 :             ),
   10302              :         ];
   10303              : 
   10304            1 :         let tline = tenant
   10305            1 :             .create_test_timeline_with_layers(
   10306            1 :                 TIMELINE_ID,
   10307            1 :                 Lsn(0x10),
   10308            1 :                 DEFAULT_PG_VERSION,
   10309            1 :                 &ctx,
   10310            1 :                 Vec::new(), // in-memory layers
   10311            1 :                 vec![
   10312            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10313            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10314            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10315            1 :                 ], // delta layers
   10316            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10317            1 :                 Lsn(0x50),
   10318            1 :             )
   10319            1 :             .await?;
   10320              :         {
   10321            1 :             tline
   10322            1 :                 .applied_gc_cutoff_lsn
   10323            1 :                 .lock_for_write()
   10324            1 :                 .store_and_unlock(Lsn(0x30))
   10325            1 :                 .wait()
   10326            1 :                 .await;
   10327              :             // Update GC info
   10328            1 :             let mut guard = tline.gc_info.write().unwrap();
   10329            1 :             *guard = GcInfo {
   10330            1 :                 retain_lsns: vec![
   10331            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10332            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10333            1 :                 ],
   10334            1 :                 cutoffs: GcCutoffs {
   10335            1 :                     time: Some(Lsn(0x30)),
   10336            1 :                     space: Lsn(0x30),
   10337            1 :                 },
   10338            1 :                 leases: Default::default(),
   10339            1 :                 within_ancestor_pitr: false,
   10340            1 :             };
   10341              :         }
   10342              : 
   10343            1 :         let expected_result = [
   10344            1 :             Bytes::from_static(b"value 0@0x10"),
   10345            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10346            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10347            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10348            1 :             Bytes::from_static(b"value 4@0x10"),
   10349            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10350            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10351            1 :             Bytes::from_static(b"value 7@0x10"),
   10352            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10353            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10354            1 :         ];
   10355              : 
   10356            1 :         let expected_result_at_gc_horizon = [
   10357            1 :             Bytes::from_static(b"value 0@0x10"),
   10358            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10359            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10360            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10361            1 :             Bytes::from_static(b"value 4@0x10"),
   10362            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10363            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10364            1 :             Bytes::from_static(b"value 7@0x10"),
   10365            1 :             Bytes::from_static(b"value 8@0x10"),
   10366            1 :             Bytes::from_static(b"value 9@0x10"),
   10367            1 :         ];
   10368              : 
   10369            1 :         let expected_result_at_lsn_20 = [
   10370            1 :             Bytes::from_static(b"value 0@0x10"),
   10371            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10372            1 :             Bytes::from_static(b"value 2@0x10"),
   10373            1 :             Bytes::from_static(b"value 3@0x10"),
   10374            1 :             Bytes::from_static(b"value 4@0x10"),
   10375            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10376            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10377            1 :             Bytes::from_static(b"value 7@0x10"),
   10378            1 :             Bytes::from_static(b"value 8@0x10"),
   10379            1 :             Bytes::from_static(b"value 9@0x10"),
   10380            1 :         ];
   10381              : 
   10382            1 :         let expected_result_at_lsn_10 = [
   10383            1 :             Bytes::from_static(b"value 0@0x10"),
   10384            1 :             Bytes::from_static(b"value 1@0x10"),
   10385            1 :             Bytes::from_static(b"value 2@0x10"),
   10386            1 :             Bytes::from_static(b"value 3@0x10"),
   10387            1 :             Bytes::from_static(b"value 4@0x10"),
   10388            1 :             Bytes::from_static(b"value 5@0x10"),
   10389            1 :             Bytes::from_static(b"value 6@0x10"),
   10390            1 :             Bytes::from_static(b"value 7@0x10"),
   10391            1 :             Bytes::from_static(b"value 8@0x10"),
   10392            1 :             Bytes::from_static(b"value 9@0x10"),
   10393            1 :         ];
   10394              : 
   10395            6 :         let verify_result = || async {
   10396            6 :             let gc_horizon = {
   10397            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10398            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10399              :             };
   10400           66 :             for idx in 0..10 {
   10401           60 :                 assert_eq!(
   10402           60 :                     tline
   10403           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10404           60 :                         .await
   10405           60 :                         .unwrap(),
   10406           60 :                     &expected_result[idx]
   10407              :                 );
   10408           60 :                 assert_eq!(
   10409           60 :                     tline
   10410           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10411           60 :                         .await
   10412           60 :                         .unwrap(),
   10413           60 :                     &expected_result_at_gc_horizon[idx]
   10414              :                 );
   10415           60 :                 assert_eq!(
   10416           60 :                     tline
   10417           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10418           60 :                         .await
   10419           60 :                         .unwrap(),
   10420           60 :                     &expected_result_at_lsn_20[idx]
   10421              :                 );
   10422           60 :                 assert_eq!(
   10423           60 :                     tline
   10424           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10425           60 :                         .await
   10426           60 :                         .unwrap(),
   10427           60 :                     &expected_result_at_lsn_10[idx]
   10428              :                 );
   10429              :             }
   10430           12 :         };
   10431              : 
   10432            1 :         verify_result().await;
   10433              : 
   10434            1 :         let cancel = CancellationToken::new();
   10435            1 :         let mut dryrun_flags = EnumSet::new();
   10436            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10437              : 
   10438            1 :         tline
   10439            1 :             .compact_with_gc(
   10440            1 :                 &cancel,
   10441            1 :                 CompactOptions {
   10442            1 :                     flags: dryrun_flags,
   10443            1 :                     ..Default::default()
   10444            1 :                 },
   10445            1 :                 &ctx,
   10446            1 :             )
   10447            1 :             .await
   10448            1 :             .unwrap();
   10449              :         // 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
   10450              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10451            1 :         verify_result().await;
   10452              : 
   10453            1 :         tline
   10454            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10455            1 :             .await
   10456            1 :             .unwrap();
   10457            1 :         verify_result().await;
   10458              : 
   10459              :         // compact again
   10460            1 :         tline
   10461            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10462            1 :             .await
   10463            1 :             .unwrap();
   10464            1 :         verify_result().await;
   10465              : 
   10466              :         // increase GC horizon and compact again
   10467              :         {
   10468            1 :             tline
   10469            1 :                 .applied_gc_cutoff_lsn
   10470            1 :                 .lock_for_write()
   10471            1 :                 .store_and_unlock(Lsn(0x38))
   10472            1 :                 .wait()
   10473            1 :                 .await;
   10474              :             // Update GC info
   10475            1 :             let mut guard = tline.gc_info.write().unwrap();
   10476            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10477            1 :             guard.cutoffs.space = Lsn(0x38);
   10478              :         }
   10479            1 :         tline
   10480            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10481            1 :             .await
   10482            1 :             .unwrap();
   10483            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10484              : 
   10485              :         // not increasing the GC horizon and compact again
   10486            1 :         tline
   10487            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10488            1 :             .await
   10489            1 :             .unwrap();
   10490            1 :         verify_result().await;
   10491              : 
   10492            2 :         Ok(())
   10493            1 :     }
   10494              : 
   10495              :     #[cfg(feature = "testing")]
   10496              :     #[tokio::test]
   10497            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10498            1 :     {
   10499            1 :         let harness =
   10500            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10501            1 :                 .await?;
   10502            1 :         let (tenant, ctx) = harness.load().await;
   10503              : 
   10504          176 :         fn get_key(id: u32) -> Key {
   10505              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10506          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10507          176 :             key.field6 = id;
   10508          176 :             key
   10509          176 :         }
   10510              : 
   10511            1 :         let img_layer = (0..10)
   10512           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10513            1 :             .collect_vec();
   10514              : 
   10515            1 :         let delta1 = vec![
   10516            1 :             (
   10517            1 :                 get_key(1),
   10518            1 :                 Lsn(0x20),
   10519            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10520            1 :             ),
   10521            1 :             (
   10522            1 :                 get_key(1),
   10523            1 :                 Lsn(0x28),
   10524            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10525            1 :             ),
   10526              :         ];
   10527            1 :         let delta2 = vec![
   10528            1 :             (
   10529            1 :                 get_key(1),
   10530            1 :                 Lsn(0x30),
   10531            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10532            1 :             ),
   10533            1 :             (
   10534            1 :                 get_key(1),
   10535            1 :                 Lsn(0x38),
   10536            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10537            1 :             ),
   10538              :         ];
   10539            1 :         let delta3 = vec![
   10540            1 :             (
   10541            1 :                 get_key(8),
   10542            1 :                 Lsn(0x48),
   10543            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10544            1 :             ),
   10545            1 :             (
   10546            1 :                 get_key(9),
   10547            1 :                 Lsn(0x48),
   10548            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10549            1 :             ),
   10550              :         ];
   10551              : 
   10552            1 :         let tline = tenant
   10553            1 :             .create_test_timeline_with_layers(
   10554            1 :                 TIMELINE_ID,
   10555            1 :                 Lsn(0x10),
   10556            1 :                 DEFAULT_PG_VERSION,
   10557            1 :                 &ctx,
   10558            1 :                 Vec::new(), // in-memory layers
   10559            1 :                 vec![
   10560            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10561            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10562            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10563            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10564            1 :                 ], // delta layers
   10565            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10566            1 :                 Lsn(0x50),
   10567            1 :             )
   10568            1 :             .await?;
   10569              :         {
   10570            1 :             tline
   10571            1 :                 .applied_gc_cutoff_lsn
   10572            1 :                 .lock_for_write()
   10573            1 :                 .store_and_unlock(Lsn(0x30))
   10574            1 :                 .wait()
   10575            1 :                 .await;
   10576              :             // Update GC info
   10577            1 :             let mut guard = tline.gc_info.write().unwrap();
   10578            1 :             *guard = GcInfo {
   10579            1 :                 retain_lsns: vec![
   10580            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10581            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10582            1 :                 ],
   10583            1 :                 cutoffs: GcCutoffs {
   10584            1 :                     time: Some(Lsn(0x30)),
   10585            1 :                     space: Lsn(0x30),
   10586            1 :                 },
   10587            1 :                 leases: Default::default(),
   10588            1 :                 within_ancestor_pitr: false,
   10589            1 :             };
   10590              :         }
   10591              : 
   10592            1 :         let expected_result = [
   10593            1 :             Bytes::from_static(b"value 0@0x10"),
   10594            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10595            1 :             Bytes::from_static(b"value 2@0x10"),
   10596            1 :             Bytes::from_static(b"value 3@0x10"),
   10597            1 :             Bytes::from_static(b"value 4@0x10"),
   10598            1 :             Bytes::from_static(b"value 5@0x10"),
   10599            1 :             Bytes::from_static(b"value 6@0x10"),
   10600            1 :             Bytes::from_static(b"value 7@0x10"),
   10601            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10602            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10603            1 :         ];
   10604              : 
   10605            1 :         let expected_result_at_gc_horizon = [
   10606            1 :             Bytes::from_static(b"value 0@0x10"),
   10607            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10608            1 :             Bytes::from_static(b"value 2@0x10"),
   10609            1 :             Bytes::from_static(b"value 3@0x10"),
   10610            1 :             Bytes::from_static(b"value 4@0x10"),
   10611            1 :             Bytes::from_static(b"value 5@0x10"),
   10612            1 :             Bytes::from_static(b"value 6@0x10"),
   10613            1 :             Bytes::from_static(b"value 7@0x10"),
   10614            1 :             Bytes::from_static(b"value 8@0x10"),
   10615            1 :             Bytes::from_static(b"value 9@0x10"),
   10616            1 :         ];
   10617              : 
   10618            1 :         let expected_result_at_lsn_20 = [
   10619            1 :             Bytes::from_static(b"value 0@0x10"),
   10620            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10621            1 :             Bytes::from_static(b"value 2@0x10"),
   10622            1 :             Bytes::from_static(b"value 3@0x10"),
   10623            1 :             Bytes::from_static(b"value 4@0x10"),
   10624            1 :             Bytes::from_static(b"value 5@0x10"),
   10625            1 :             Bytes::from_static(b"value 6@0x10"),
   10626            1 :             Bytes::from_static(b"value 7@0x10"),
   10627            1 :             Bytes::from_static(b"value 8@0x10"),
   10628            1 :             Bytes::from_static(b"value 9@0x10"),
   10629            1 :         ];
   10630              : 
   10631            1 :         let expected_result_at_lsn_10 = [
   10632            1 :             Bytes::from_static(b"value 0@0x10"),
   10633            1 :             Bytes::from_static(b"value 1@0x10"),
   10634            1 :             Bytes::from_static(b"value 2@0x10"),
   10635            1 :             Bytes::from_static(b"value 3@0x10"),
   10636            1 :             Bytes::from_static(b"value 4@0x10"),
   10637            1 :             Bytes::from_static(b"value 5@0x10"),
   10638            1 :             Bytes::from_static(b"value 6@0x10"),
   10639            1 :             Bytes::from_static(b"value 7@0x10"),
   10640            1 :             Bytes::from_static(b"value 8@0x10"),
   10641            1 :             Bytes::from_static(b"value 9@0x10"),
   10642            1 :         ];
   10643              : 
   10644            4 :         let verify_result = || async {
   10645            4 :             let gc_horizon = {
   10646            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10647            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10648              :             };
   10649           44 :             for idx in 0..10 {
   10650           40 :                 assert_eq!(
   10651           40 :                     tline
   10652           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10653           40 :                         .await
   10654           40 :                         .unwrap(),
   10655           40 :                     &expected_result[idx]
   10656              :                 );
   10657           40 :                 assert_eq!(
   10658           40 :                     tline
   10659           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10660           40 :                         .await
   10661           40 :                         .unwrap(),
   10662           40 :                     &expected_result_at_gc_horizon[idx]
   10663              :                 );
   10664           40 :                 assert_eq!(
   10665           40 :                     tline
   10666           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10667           40 :                         .await
   10668           40 :                         .unwrap(),
   10669           40 :                     &expected_result_at_lsn_20[idx]
   10670              :                 );
   10671           40 :                 assert_eq!(
   10672           40 :                     tline
   10673           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10674           40 :                         .await
   10675           40 :                         .unwrap(),
   10676           40 :                     &expected_result_at_lsn_10[idx]
   10677              :                 );
   10678              :             }
   10679            8 :         };
   10680              : 
   10681            1 :         verify_result().await;
   10682              : 
   10683            1 :         let cancel = CancellationToken::new();
   10684            1 :         let mut dryrun_flags = EnumSet::new();
   10685            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10686              : 
   10687            1 :         tline
   10688            1 :             .compact_with_gc(
   10689            1 :                 &cancel,
   10690            1 :                 CompactOptions {
   10691            1 :                     flags: dryrun_flags,
   10692            1 :                     ..Default::default()
   10693            1 :                 },
   10694            1 :                 &ctx,
   10695            1 :             )
   10696            1 :             .await
   10697            1 :             .unwrap();
   10698              :         // 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
   10699              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10700            1 :         verify_result().await;
   10701              : 
   10702            1 :         tline
   10703            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10704            1 :             .await
   10705            1 :             .unwrap();
   10706            1 :         verify_result().await;
   10707              : 
   10708              :         // compact again
   10709            1 :         tline
   10710            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10711            1 :             .await
   10712            1 :             .unwrap();
   10713            1 :         verify_result().await;
   10714              : 
   10715            2 :         Ok(())
   10716            1 :     }
   10717              : 
   10718              :     #[cfg(feature = "testing")]
   10719              :     #[tokio::test]
   10720            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10721              :         use models::CompactLsnRange;
   10722              : 
   10723            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10724            1 :         let (tenant, ctx) = harness.load().await;
   10725              : 
   10726           83 :         fn get_key(id: u32) -> Key {
   10727           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10728           83 :             key.field6 = id;
   10729           83 :             key
   10730           83 :         }
   10731              : 
   10732            1 :         let img_layer = (0..10)
   10733           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10734            1 :             .collect_vec();
   10735              : 
   10736            1 :         let delta1 = vec![
   10737            1 :             (
   10738            1 :                 get_key(1),
   10739            1 :                 Lsn(0x20),
   10740            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10741            1 :             ),
   10742            1 :             (
   10743            1 :                 get_key(2),
   10744            1 :                 Lsn(0x30),
   10745            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10746            1 :             ),
   10747            1 :             (
   10748            1 :                 get_key(3),
   10749            1 :                 Lsn(0x28),
   10750            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10751            1 :             ),
   10752            1 :             (
   10753            1 :                 get_key(3),
   10754            1 :                 Lsn(0x30),
   10755            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10756            1 :             ),
   10757            1 :             (
   10758            1 :                 get_key(3),
   10759            1 :                 Lsn(0x40),
   10760            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10761            1 :             ),
   10762              :         ];
   10763            1 :         let delta2 = vec![
   10764            1 :             (
   10765            1 :                 get_key(5),
   10766            1 :                 Lsn(0x20),
   10767            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10768            1 :             ),
   10769            1 :             (
   10770            1 :                 get_key(6),
   10771            1 :                 Lsn(0x20),
   10772            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10773            1 :             ),
   10774              :         ];
   10775            1 :         let delta3 = vec![
   10776            1 :             (
   10777            1 :                 get_key(8),
   10778            1 :                 Lsn(0x48),
   10779            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10780            1 :             ),
   10781            1 :             (
   10782            1 :                 get_key(9),
   10783            1 :                 Lsn(0x48),
   10784            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10785            1 :             ),
   10786              :         ];
   10787              : 
   10788            1 :         let parent_tline = tenant
   10789            1 :             .create_test_timeline_with_layers(
   10790            1 :                 TIMELINE_ID,
   10791            1 :                 Lsn(0x10),
   10792            1 :                 DEFAULT_PG_VERSION,
   10793            1 :                 &ctx,
   10794            1 :                 vec![],                       // in-memory layers
   10795            1 :                 vec![],                       // delta layers
   10796            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10797            1 :                 Lsn(0x18),
   10798            1 :             )
   10799            1 :             .await?;
   10800              : 
   10801            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10802              : 
   10803            1 :         let branch_tline = tenant
   10804            1 :             .branch_timeline_test_with_layers(
   10805            1 :                 &parent_tline,
   10806            1 :                 NEW_TIMELINE_ID,
   10807            1 :                 Some(Lsn(0x18)),
   10808            1 :                 &ctx,
   10809            1 :                 vec![
   10810            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10811            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10812            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10813            1 :                 ], // delta layers
   10814            1 :                 vec![], // image layers
   10815            1 :                 Lsn(0x50),
   10816            1 :             )
   10817            1 :             .await?;
   10818              : 
   10819            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10820              : 
   10821              :         {
   10822            1 :             parent_tline
   10823            1 :                 .applied_gc_cutoff_lsn
   10824            1 :                 .lock_for_write()
   10825            1 :                 .store_and_unlock(Lsn(0x10))
   10826            1 :                 .wait()
   10827            1 :                 .await;
   10828              :             // Update GC info
   10829            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10830            1 :             *guard = GcInfo {
   10831            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10832            1 :                 cutoffs: GcCutoffs {
   10833            1 :                     time: Some(Lsn(0x10)),
   10834            1 :                     space: Lsn(0x10),
   10835            1 :                 },
   10836            1 :                 leases: Default::default(),
   10837            1 :                 within_ancestor_pitr: false,
   10838            1 :             };
   10839              :         }
   10840              : 
   10841              :         {
   10842            1 :             branch_tline
   10843            1 :                 .applied_gc_cutoff_lsn
   10844            1 :                 .lock_for_write()
   10845            1 :                 .store_and_unlock(Lsn(0x50))
   10846            1 :                 .wait()
   10847            1 :                 .await;
   10848              :             // Update GC info
   10849            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10850            1 :             *guard = GcInfo {
   10851            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10852            1 :                 cutoffs: GcCutoffs {
   10853            1 :                     time: Some(Lsn(0x50)),
   10854            1 :                     space: Lsn(0x50),
   10855            1 :                 },
   10856            1 :                 leases: Default::default(),
   10857            1 :                 within_ancestor_pitr: false,
   10858            1 :             };
   10859              :         }
   10860              : 
   10861            1 :         let expected_result_at_gc_horizon = [
   10862            1 :             Bytes::from_static(b"value 0@0x10"),
   10863            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10864            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10865            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10866            1 :             Bytes::from_static(b"value 4@0x10"),
   10867            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10868            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10869            1 :             Bytes::from_static(b"value 7@0x10"),
   10870            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10871            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10872            1 :         ];
   10873              : 
   10874            1 :         let expected_result_at_lsn_40 = [
   10875            1 :             Bytes::from_static(b"value 0@0x10"),
   10876            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10877            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10878            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10879            1 :             Bytes::from_static(b"value 4@0x10"),
   10880            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10881            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10882            1 :             Bytes::from_static(b"value 7@0x10"),
   10883            1 :             Bytes::from_static(b"value 8@0x10"),
   10884            1 :             Bytes::from_static(b"value 9@0x10"),
   10885            1 :         ];
   10886              : 
   10887            3 :         let verify_result = || async {
   10888           33 :             for idx in 0..10 {
   10889           30 :                 assert_eq!(
   10890           30 :                     branch_tline
   10891           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10892           30 :                         .await
   10893           30 :                         .unwrap(),
   10894           30 :                     &expected_result_at_gc_horizon[idx]
   10895              :                 );
   10896           30 :                 assert_eq!(
   10897           30 :                     branch_tline
   10898           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10899           30 :                         .await
   10900           30 :                         .unwrap(),
   10901           30 :                     &expected_result_at_lsn_40[idx]
   10902              :                 );
   10903              :             }
   10904            6 :         };
   10905              : 
   10906            1 :         verify_result().await;
   10907              : 
   10908            1 :         let cancel = CancellationToken::new();
   10909            1 :         branch_tline
   10910            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10911            1 :             .await
   10912            1 :             .unwrap();
   10913              : 
   10914            1 :         verify_result().await;
   10915              : 
   10916              :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10917              :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10918            1 :         branch_tline
   10919            1 :             .compact_with_gc(
   10920            1 :                 &cancel,
   10921            1 :                 CompactOptions {
   10922            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10923            1 :                     ..Default::default()
   10924            1 :                 },
   10925            1 :                 &ctx,
   10926            1 :             )
   10927            1 :             .await
   10928            1 :             .unwrap();
   10929              : 
   10930            1 :         verify_result().await;
   10931              : 
   10932            2 :         Ok(())
   10933            1 :     }
   10934              : 
   10935              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10936              :     // Create an image arrangement where we have to read at different LSN ranges
   10937              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10938              :     // a delta layer. Like so:
   10939              :     //
   10940              :     //     A      B
   10941              :     // +----------------+ -> delta_layer
   10942              :     // |                |                           ^ lsn
   10943              :     // |       =========|-> nested_image_layer      |
   10944              :     // |       C        |                           |
   10945              :     // +----------------+                           |
   10946              :     // ======== -> baseline_image_layer             +-------> key
   10947              :     //
   10948              :     //
   10949              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10950              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10951              :     #[cfg(feature = "testing")]
   10952              :     #[tokio::test]
   10953            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10954            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10955            1 :         let (tenant, ctx) = harness.load().await;
   10956              : 
   10957            1 :         let will_init_keys = [2, 6];
   10958           22 :         fn get_key(id: u32) -> Key {
   10959           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10960           22 :             key.field6 = id;
   10961           22 :             key
   10962           22 :         }
   10963              : 
   10964            1 :         let mut expected_key_values = HashMap::new();
   10965              : 
   10966            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10967            1 :         let mut baseline_img_layer = Vec::new();
   10968            6 :         for i in 0..5 {
   10969            5 :             let key = get_key(i);
   10970            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10971              : 
   10972            5 :             let removed = expected_key_values.insert(key, value.clone());
   10973            5 :             assert!(removed.is_none());
   10974              : 
   10975            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10976              :         }
   10977              : 
   10978            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10979            1 :         let mut nested_img_layer = Vec::new();
   10980            6 :         for i in 5..10 {
   10981            5 :             let key = get_key(i);
   10982            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10983              : 
   10984            5 :             let removed = expected_key_values.insert(key, value.clone());
   10985            5 :             assert!(removed.is_none());
   10986              : 
   10987            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10988              :         }
   10989              : 
   10990            1 :         let mut delta_layer_spec = Vec::default();
   10991            1 :         let delta_layer_start_lsn = Lsn(0x20);
   10992            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10993              : 
   10994           11 :         for i in 0..10 {
   10995           10 :             let key = get_key(i);
   10996           10 :             let key_in_nested = nested_img_layer
   10997           10 :                 .iter()
   10998           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10999           10 :             let lsn = {
   11000           10 :                 if key_in_nested {
   11001            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   11002              :                 } else {
   11003            5 :                     delta_layer_start_lsn
   11004              :                 }
   11005              :             };
   11006              : 
   11007           10 :             let will_init = will_init_keys.contains(&i);
   11008           10 :             if will_init {
   11009            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11010            2 : 
   11011            2 :                 expected_key_values.insert(key, "".to_string());
   11012            8 :             } else {
   11013            8 :                 let delta = format!("@{lsn}");
   11014            8 :                 delta_layer_spec.push((
   11015            8 :                     key,
   11016            8 :                     lsn,
   11017            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11018            8 :                 ));
   11019            8 : 
   11020            8 :                 expected_key_values
   11021            8 :                     .get_mut(&key)
   11022            8 :                     .expect("An image exists for each key")
   11023            8 :                     .push_str(delta.as_str());
   11024            8 :             }
   11025           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   11026              :         }
   11027              : 
   11028            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   11029              : 
   11030            1 :         assert!(
   11031            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   11032            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   11033              :         );
   11034              : 
   11035            1 :         let tline = tenant
   11036            1 :             .create_test_timeline_with_layers(
   11037            1 :                 TIMELINE_ID,
   11038            1 :                 baseline_image_layer_lsn,
   11039            1 :                 DEFAULT_PG_VERSION,
   11040            1 :                 &ctx,
   11041            1 :                 vec![], // in-memory layers
   11042            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   11043            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   11044            1 :                     delta_layer_spec,
   11045            1 :                 )], // delta layers
   11046            1 :                 vec![
   11047            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11048            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11049            1 :                 ], // image layers
   11050            1 :                 delta_layer_end_lsn,
   11051            1 :             )
   11052            1 :             .await?;
   11053              : 
   11054            1 :         let query = VersionedKeySpaceQuery::uniform(
   11055            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11056            1 :             delta_layer_end_lsn,
   11057              :         );
   11058              : 
   11059            1 :         let results = tline
   11060            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11061            1 :             .await
   11062            1 :             .expect("No vectored errors");
   11063           11 :         for (key, res) in results {
   11064           10 :             let value = res.expect("No key errors");
   11065           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11066           10 :             assert_eq!(value, Bytes::from(expected_value));
   11067            1 :         }
   11068            1 : 
   11069            1 :         Ok(())
   11070            1 :     }
   11071              : 
   11072              :     #[cfg(feature = "testing")]
   11073              :     #[tokio::test]
   11074            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   11075            1 :         let harness =
   11076            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   11077            1 :         let (tenant, ctx) = harness.load().await;
   11078              : 
   11079            1 :         let will_init_keys = [2, 6];
   11080           32 :         fn get_key(id: u32) -> Key {
   11081           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11082           32 :             key.field6 = id;
   11083           32 :             key
   11084           32 :         }
   11085              : 
   11086            1 :         let mut expected_key_values = HashMap::new();
   11087              : 
   11088            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11089            1 :         let mut baseline_img_layer = Vec::new();
   11090            6 :         for i in 0..5 {
   11091            5 :             let key = get_key(i);
   11092            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11093              : 
   11094            5 :             let removed = expected_key_values.insert(key, value.clone());
   11095            5 :             assert!(removed.is_none());
   11096              : 
   11097            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11098              :         }
   11099              : 
   11100            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11101            1 :         let mut nested_img_layer = Vec::new();
   11102            6 :         for i in 5..10 {
   11103            5 :             let key = get_key(i);
   11104            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11105              : 
   11106            5 :             let removed = expected_key_values.insert(key, value.clone());
   11107            5 :             assert!(removed.is_none());
   11108              : 
   11109            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11110              :         }
   11111              : 
   11112            1 :         let frozen_layer = {
   11113            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   11114            1 :             let mut data = Vec::new();
   11115           11 :             for i in 0..10 {
   11116           10 :                 let key = get_key(i);
   11117           10 :                 let key_in_nested = nested_img_layer
   11118           10 :                     .iter()
   11119           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   11120           10 :                 let lsn = {
   11121           10 :                     if key_in_nested {
   11122            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   11123              :                     } else {
   11124            5 :                         lsn_range.start
   11125              :                     }
   11126              :                 };
   11127              : 
   11128           10 :                 let will_init = will_init_keys.contains(&i);
   11129           10 :                 if will_init {
   11130            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11131            2 : 
   11132            2 :                     expected_key_values.insert(key, "".to_string());
   11133            8 :                 } else {
   11134            8 :                     let delta = format!("@{lsn}");
   11135            8 :                     data.push((
   11136            8 :                         key,
   11137            8 :                         lsn,
   11138            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11139            8 :                     ));
   11140            8 : 
   11141            8 :                     expected_key_values
   11142            8 :                         .get_mut(&key)
   11143            8 :                         .expect("An image exists for each key")
   11144            8 :                         .push_str(delta.as_str());
   11145            8 :                 }
   11146              :             }
   11147              : 
   11148            1 :             InMemoryLayerTestDesc {
   11149            1 :                 lsn_range,
   11150            1 :                 is_open: false,
   11151            1 :                 data,
   11152            1 :             }
   11153              :         };
   11154              : 
   11155            1 :         let (open_layer, last_record_lsn) = {
   11156            1 :             let start_lsn = Lsn(0x70);
   11157            1 :             let mut data = Vec::new();
   11158            1 :             let mut end_lsn = Lsn(0);
   11159           11 :             for i in 0..10 {
   11160           10 :                 let key = get_key(i);
   11161           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   11162           10 :                 let delta = format!("@{lsn}");
   11163           10 :                 data.push((
   11164           10 :                     key,
   11165           10 :                     lsn,
   11166           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11167           10 :                 ));
   11168           10 : 
   11169           10 :                 expected_key_values
   11170           10 :                     .get_mut(&key)
   11171           10 :                     .expect("An image exists for each key")
   11172           10 :                     .push_str(delta.as_str());
   11173           10 : 
   11174           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   11175           10 :             }
   11176              : 
   11177            1 :             (
   11178            1 :                 InMemoryLayerTestDesc {
   11179            1 :                     lsn_range: start_lsn..Lsn::MAX,
   11180            1 :                     is_open: true,
   11181            1 :                     data,
   11182            1 :                 },
   11183            1 :                 end_lsn,
   11184            1 :             )
   11185              :         };
   11186              : 
   11187            1 :         assert!(
   11188            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   11189            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   11190              :         );
   11191              : 
   11192            1 :         let tline = tenant
   11193            1 :             .create_test_timeline_with_layers(
   11194            1 :                 TIMELINE_ID,
   11195            1 :                 baseline_image_layer_lsn,
   11196            1 :                 DEFAULT_PG_VERSION,
   11197            1 :                 &ctx,
   11198            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   11199            1 :                 Vec::new(),                     // delta layers
   11200            1 :                 vec![
   11201            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11202            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11203            1 :                 ], // image layers
   11204            1 :                 last_record_lsn,
   11205            1 :             )
   11206            1 :             .await?;
   11207              : 
   11208            1 :         let query = VersionedKeySpaceQuery::uniform(
   11209            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11210            1 :             last_record_lsn,
   11211              :         );
   11212              : 
   11213            1 :         let results = tline
   11214            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11215            1 :             .await
   11216            1 :             .expect("No vectored errors");
   11217           11 :         for (key, res) in results {
   11218           10 :             let value = res.expect("No key errors");
   11219           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11220           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   11221            1 : 
   11222           10 :             tracing::info!("key={key} value={expected_value}");
   11223            1 :         }
   11224            1 : 
   11225            1 :         Ok(())
   11226            1 :     }
   11227              : 
   11228              :     // A randomized read path test. Generates a layer map according to a deterministic
   11229              :     // specification. Fills the (key, LSN) space in random manner and then performs
   11230              :     // random scattered queries validating the results against in-memory storage.
   11231              :     //
   11232              :     // See this internal Notion page for a diagram of the layer map:
   11233              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   11234              :     //
   11235              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   11236              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   11237              :     // to run multiple instances in parallel:
   11238              :     //
   11239              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   11240              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   11241              :     #[cfg(feature = "testing")]
   11242              :     #[tokio::test]
   11243            1 :     async fn test_read_path() -> anyhow::Result<()> {
   11244              :         use rand::seq::SliceRandom;
   11245              : 
   11246            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   11247            0 :             let seed: u64 = thread_rng().r#gen();
   11248            0 :             seed
   11249              :         } else {
   11250              :             // Use a hard-coded seed when not in fuzzing mode.
   11251              :             // Note that with the current approach results are not reproducible
   11252              :             // accross platforms and Rust releases.
   11253              :             const SEED: u64 = 0;
   11254            1 :             SEED
   11255              :         };
   11256              : 
   11257            1 :         let mut random = StdRng::seed_from_u64(seed);
   11258              : 
   11259            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   11260              :             const QUERIES: u64 = 5000;
   11261            0 :             let will_init_chance: u8 = random.gen_range(0..=10);
   11262            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   11263              : 
   11264            0 :             (QUERIES, will_init_chance, gap_chance)
   11265              :         } else {
   11266              :             const QUERIES: u64 = 1000;
   11267              :             const WILL_INIT_CHANCE: u8 = 1;
   11268              :             const GAP_CHANCE: u8 = 5;
   11269              : 
   11270            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   11271              :         };
   11272              : 
   11273            1 :         let harness = TenantHarness::create("test_read_path").await?;
   11274            1 :         let (tenant, ctx) = harness.load().await;
   11275              : 
   11276            1 :         tracing::info!("Using random seed: {seed}");
   11277            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   11278              : 
   11279              :         // Define the layer map shape. Note that this part is not randomized.
   11280              : 
   11281              :         const KEY_DIMENSION_SIZE: u32 = 99;
   11282            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11283            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11284            1 :         let total_key_range = start_key..end_key;
   11285            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11286            1 :         let total_start_lsn = Lsn(104);
   11287            1 :         let last_record_lsn = Lsn(504);
   11288              : 
   11289            1 :         assert!(total_key_range_size % 3 == 0);
   11290              : 
   11291            1 :         let in_memory_layers_shape = vec![
   11292            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11293            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11294              :         ];
   11295              : 
   11296            1 :         let delta_layers_shape = vec![
   11297            1 :             (
   11298            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11299            1 :                 Lsn(200)..Lsn(304),
   11300            1 :             ),
   11301            1 :             (
   11302            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11303            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11304            1 :                 Lsn(200)..Lsn(304),
   11305            1 :             ),
   11306            1 :             (
   11307            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11308            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11309            1 :                 Lsn(200)..Lsn(304),
   11310            1 :             ),
   11311              :         ];
   11312              : 
   11313            1 :         let image_layers_shape = vec![
   11314            1 :             (
   11315            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11316            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11317            1 :                 Lsn(456),
   11318            1 :             ),
   11319            1 :             (
   11320            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11321            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11322            1 :                 Lsn(256),
   11323            1 :             ),
   11324            1 :             (total_key_range.clone(), total_start_lsn),
   11325              :         ];
   11326              : 
   11327            1 :         let specification = TestTimelineSpecification {
   11328            1 :             start_lsn: total_start_lsn,
   11329            1 :             last_record_lsn,
   11330            1 :             in_memory_layers_shape,
   11331            1 :             delta_layers_shape,
   11332            1 :             image_layers_shape,
   11333            1 :             gap_chance,
   11334            1 :             will_init_chance,
   11335            1 :         };
   11336              : 
   11337              :         // Create and randomly fill in the layers according to the specification
   11338            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11339            1 :             &tenant,
   11340            1 :             TIMELINE_ID,
   11341            1 :             DEFAULT_PG_VERSION,
   11342            1 :             specification,
   11343            1 :             &mut random,
   11344            1 :             &ctx,
   11345            1 :         )
   11346            1 :         .await?;
   11347              : 
   11348              :         // Now generate queries based on the interesting lsns that we've collected.
   11349              :         //
   11350              :         // While there's still room in the query, pick and interesting LSN and a random
   11351              :         // key. Then roll the dice to see if the next key should also be included in
   11352              :         // the query. When the roll fails, break the "batch" and pick another point in the
   11353              :         // (key, LSN) space.
   11354              : 
   11355              :         const PICK_NEXT_CHANCE: u8 = 50;
   11356            1 :         for _ in 0..queries {
   11357         1000 :             let query = {
   11358         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11359         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11360            1 : 
   11361        22536 :                 while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11362        21536 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11363        21536 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11364            1 : 
   11365        37614 :                     while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11366        37093 :                         if used_keys.contains(&selected_key)
   11367        32154 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11368            1 :                         {
   11369         5093 :                             break;
   11370        32000 :                         }
   11371            1 : 
   11372        32000 :                         keyspaces_at_lsn
   11373        32000 :                             .entry(*selected_lsn)
   11374        32000 :                             .or_default()
   11375        32000 :                             .add_key(selected_key);
   11376        32000 :                         used_keys.insert(selected_key);
   11377            1 : 
   11378        32000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11379        32000 :                         if pick_next {
   11380        16078 :                             selected_key = selected_key.next();
   11381        16078 :                         } else {
   11382        15922 :                             break;
   11383            1 :                         }
   11384            1 :                     }
   11385            1 :                 }
   11386            1 : 
   11387         1000 :                 VersionedKeySpaceQuery::scattered(
   11388         1000 :                     keyspaces_at_lsn
   11389         1000 :                         .into_iter()
   11390        11917 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11391         1000 :                         .collect(),
   11392            1 :                 )
   11393            1 :             };
   11394            1 : 
   11395            1 :             // Run the query and validate the results
   11396            1 : 
   11397         1000 :             let results = tline
   11398         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11399         1000 :                 .await;
   11400            1 : 
   11401         1000 :             let blobs = match results {
   11402         1000 :                 Ok(ok) => ok,
   11403            1 :                 Err(err) => {
   11404            1 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11405            1 :                 }
   11406            1 :             };
   11407            1 : 
   11408        32000 :             for (key, key_res) in blobs.into_iter() {
   11409        32000 :                 match key_res {
   11410        32000 :                     Ok(blob) => {
   11411        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11412        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11413            1 : 
   11414        32000 :                         if blob != expected {
   11415            1 :                             tracing::error!(
   11416            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11417            1 :                             );
   11418        32000 :                         }
   11419            1 : 
   11420        32000 :                         assert_eq!(blob, expected);
   11421            1 :                     }
   11422            1 :                     Err(err) => {
   11423            1 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11424            1 : 
   11425            1 :                         panic!(
   11426            1 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11427            1 :                         );
   11428            1 :                     }
   11429            1 :                 }
   11430            1 :             }
   11431            1 :         }
   11432            1 : 
   11433            1 :         Ok(())
   11434            1 :     }
   11435              : 
   11436          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11437          107 :         (
   11438          107 :             k1.is_delta,
   11439          107 :             k1.key_range.start,
   11440          107 :             k1.key_range.end,
   11441          107 :             k1.lsn_range.start,
   11442          107 :             k1.lsn_range.end,
   11443          107 :         )
   11444          107 :             .cmp(&(
   11445          107 :                 k2.is_delta,
   11446          107 :                 k2.key_range.start,
   11447          107 :                 k2.key_range.end,
   11448          107 :                 k2.lsn_range.start,
   11449          107 :                 k2.lsn_range.end,
   11450          107 :             ))
   11451          107 :     }
   11452              : 
   11453           12 :     async fn inspect_and_sort(
   11454           12 :         tline: &Arc<Timeline>,
   11455           12 :         filter: Option<std::ops::Range<Key>>,
   11456           12 :     ) -> Vec<PersistentLayerKey> {
   11457           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11458           12 :         if let Some(filter) = filter {
   11459           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11460            1 :         }
   11461           12 :         all_layers.sort_by(sort_layer_key);
   11462           12 :         all_layers
   11463           12 :     }
   11464              : 
   11465              :     #[cfg(feature = "testing")]
   11466           11 :     fn check_layer_map_key_eq(
   11467           11 :         mut left: Vec<PersistentLayerKey>,
   11468           11 :         mut right: Vec<PersistentLayerKey>,
   11469           11 :     ) {
   11470           11 :         left.sort_by(sort_layer_key);
   11471           11 :         right.sort_by(sort_layer_key);
   11472           11 :         if left != right {
   11473            0 :             eprintln!("---LEFT---");
   11474            0 :             for left in left.iter() {
   11475            0 :                 eprintln!("{left}");
   11476            0 :             }
   11477            0 :             eprintln!("---RIGHT---");
   11478            0 :             for right in right.iter() {
   11479            0 :                 eprintln!("{right}");
   11480            0 :             }
   11481            0 :             assert_eq!(left, right);
   11482           11 :         }
   11483           11 :     }
   11484              : 
   11485              :     #[cfg(feature = "testing")]
   11486              :     #[tokio::test]
   11487            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11488            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11489            1 :         let (tenant, ctx) = harness.load().await;
   11490              : 
   11491           91 :         fn get_key(id: u32) -> Key {
   11492              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11493           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11494           91 :             key.field6 = id;
   11495           91 :             key
   11496           91 :         }
   11497              : 
   11498              :         // img layer at 0x10
   11499            1 :         let img_layer = (0..10)
   11500           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11501            1 :             .collect_vec();
   11502              : 
   11503            1 :         let delta1 = vec![
   11504            1 :             (
   11505            1 :                 get_key(1),
   11506            1 :                 Lsn(0x20),
   11507            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11508            1 :             ),
   11509            1 :             (
   11510            1 :                 get_key(2),
   11511            1 :                 Lsn(0x30),
   11512            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11513            1 :             ),
   11514            1 :             (
   11515            1 :                 get_key(3),
   11516            1 :                 Lsn(0x40),
   11517            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11518            1 :             ),
   11519              :         ];
   11520            1 :         let delta2 = vec![
   11521            1 :             (
   11522            1 :                 get_key(5),
   11523            1 :                 Lsn(0x20),
   11524            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11525            1 :             ),
   11526            1 :             (
   11527            1 :                 get_key(6),
   11528            1 :                 Lsn(0x20),
   11529            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11530            1 :             ),
   11531              :         ];
   11532            1 :         let delta3 = vec![
   11533            1 :             (
   11534            1 :                 get_key(8),
   11535            1 :                 Lsn(0x48),
   11536            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11537            1 :             ),
   11538            1 :             (
   11539            1 :                 get_key(9),
   11540            1 :                 Lsn(0x48),
   11541            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11542            1 :             ),
   11543              :         ];
   11544              : 
   11545            1 :         let tline = tenant
   11546            1 :             .create_test_timeline_with_layers(
   11547            1 :                 TIMELINE_ID,
   11548            1 :                 Lsn(0x10),
   11549            1 :                 DEFAULT_PG_VERSION,
   11550            1 :                 &ctx,
   11551            1 :                 vec![], // in-memory layers
   11552            1 :                 vec![
   11553            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11554            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11555            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11556            1 :                 ], // delta layers
   11557            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11558            1 :                 Lsn(0x50),
   11559            1 :             )
   11560            1 :             .await?;
   11561              : 
   11562              :         {
   11563            1 :             tline
   11564            1 :                 .applied_gc_cutoff_lsn
   11565            1 :                 .lock_for_write()
   11566            1 :                 .store_and_unlock(Lsn(0x30))
   11567            1 :                 .wait()
   11568            1 :                 .await;
   11569              :             // Update GC info
   11570            1 :             let mut guard = tline.gc_info.write().unwrap();
   11571            1 :             *guard = GcInfo {
   11572            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11573            1 :                 cutoffs: GcCutoffs {
   11574            1 :                     time: Some(Lsn(0x30)),
   11575            1 :                     space: Lsn(0x30),
   11576            1 :                 },
   11577            1 :                 leases: Default::default(),
   11578            1 :                 within_ancestor_pitr: false,
   11579            1 :             };
   11580              :         }
   11581              : 
   11582            1 :         let cancel = CancellationToken::new();
   11583              : 
   11584              :         // Do a partial compaction on key range 0..2
   11585            1 :         tline
   11586            1 :             .compact_with_gc(
   11587            1 :                 &cancel,
   11588            1 :                 CompactOptions {
   11589            1 :                     flags: EnumSet::new(),
   11590            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11591            1 :                     ..Default::default()
   11592            1 :                 },
   11593            1 :                 &ctx,
   11594            1 :             )
   11595            1 :             .await
   11596            1 :             .unwrap();
   11597            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11598            1 :         check_layer_map_key_eq(
   11599            1 :             all_layers,
   11600            1 :             vec![
   11601              :                 // newly-generated image layer for the partial compaction range 0-2
   11602            1 :                 PersistentLayerKey {
   11603            1 :                     key_range: get_key(0)..get_key(2),
   11604            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11605            1 :                     is_delta: false,
   11606            1 :                 },
   11607            1 :                 PersistentLayerKey {
   11608            1 :                     key_range: get_key(0)..get_key(10),
   11609            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11610            1 :                     is_delta: false,
   11611            1 :                 },
   11612              :                 // delta1 is split and the second part is rewritten
   11613            1 :                 PersistentLayerKey {
   11614            1 :                     key_range: get_key(2)..get_key(4),
   11615            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11616            1 :                     is_delta: true,
   11617            1 :                 },
   11618            1 :                 PersistentLayerKey {
   11619            1 :                     key_range: get_key(5)..get_key(7),
   11620            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11621            1 :                     is_delta: true,
   11622            1 :                 },
   11623            1 :                 PersistentLayerKey {
   11624            1 :                     key_range: get_key(8)..get_key(10),
   11625            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11626            1 :                     is_delta: true,
   11627            1 :                 },
   11628              :             ],
   11629              :         );
   11630              : 
   11631              :         // Do a partial compaction on key range 2..4
   11632            1 :         tline
   11633            1 :             .compact_with_gc(
   11634            1 :                 &cancel,
   11635            1 :                 CompactOptions {
   11636            1 :                     flags: EnumSet::new(),
   11637            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11638            1 :                     ..Default::default()
   11639            1 :                 },
   11640            1 :                 &ctx,
   11641            1 :             )
   11642            1 :             .await
   11643            1 :             .unwrap();
   11644            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11645            1 :         check_layer_map_key_eq(
   11646            1 :             all_layers,
   11647            1 :             vec![
   11648            1 :                 PersistentLayerKey {
   11649            1 :                     key_range: get_key(0)..get_key(2),
   11650            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11651            1 :                     is_delta: false,
   11652            1 :                 },
   11653            1 :                 PersistentLayerKey {
   11654            1 :                     key_range: get_key(0)..get_key(10),
   11655            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11656            1 :                     is_delta: false,
   11657            1 :                 },
   11658              :                 // image layer generated for the compaction range 2-4
   11659            1 :                 PersistentLayerKey {
   11660            1 :                     key_range: get_key(2)..get_key(4),
   11661            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11662            1 :                     is_delta: false,
   11663            1 :                 },
   11664              :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11665            1 :                 PersistentLayerKey {
   11666            1 :                     key_range: get_key(2)..get_key(4),
   11667            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11668            1 :                     is_delta: true,
   11669            1 :                 },
   11670            1 :                 PersistentLayerKey {
   11671            1 :                     key_range: get_key(5)..get_key(7),
   11672            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11673            1 :                     is_delta: true,
   11674            1 :                 },
   11675            1 :                 PersistentLayerKey {
   11676            1 :                     key_range: get_key(8)..get_key(10),
   11677            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11678            1 :                     is_delta: true,
   11679            1 :                 },
   11680              :             ],
   11681              :         );
   11682              : 
   11683              :         // Do a partial compaction on key range 4..9
   11684            1 :         tline
   11685            1 :             .compact_with_gc(
   11686            1 :                 &cancel,
   11687            1 :                 CompactOptions {
   11688            1 :                     flags: EnumSet::new(),
   11689            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11690            1 :                     ..Default::default()
   11691            1 :                 },
   11692            1 :                 &ctx,
   11693            1 :             )
   11694            1 :             .await
   11695            1 :             .unwrap();
   11696            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11697            1 :         check_layer_map_key_eq(
   11698            1 :             all_layers,
   11699            1 :             vec![
   11700            1 :                 PersistentLayerKey {
   11701            1 :                     key_range: get_key(0)..get_key(2),
   11702            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11703            1 :                     is_delta: false,
   11704            1 :                 },
   11705            1 :                 PersistentLayerKey {
   11706            1 :                     key_range: get_key(0)..get_key(10),
   11707            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11708            1 :                     is_delta: false,
   11709            1 :                 },
   11710            1 :                 PersistentLayerKey {
   11711            1 :                     key_range: get_key(2)..get_key(4),
   11712            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11713            1 :                     is_delta: false,
   11714            1 :                 },
   11715            1 :                 PersistentLayerKey {
   11716            1 :                     key_range: get_key(2)..get_key(4),
   11717            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11718            1 :                     is_delta: true,
   11719            1 :                 },
   11720              :                 // image layer generated for this compaction range
   11721            1 :                 PersistentLayerKey {
   11722            1 :                     key_range: get_key(4)..get_key(9),
   11723            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11724            1 :                     is_delta: false,
   11725            1 :                 },
   11726            1 :                 PersistentLayerKey {
   11727            1 :                     key_range: get_key(8)..get_key(10),
   11728            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11729            1 :                     is_delta: true,
   11730            1 :                 },
   11731              :             ],
   11732              :         );
   11733              : 
   11734              :         // Do a partial compaction on key range 9..10
   11735            1 :         tline
   11736            1 :             .compact_with_gc(
   11737            1 :                 &cancel,
   11738            1 :                 CompactOptions {
   11739            1 :                     flags: EnumSet::new(),
   11740            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11741            1 :                     ..Default::default()
   11742            1 :                 },
   11743            1 :                 &ctx,
   11744            1 :             )
   11745            1 :             .await
   11746            1 :             .unwrap();
   11747            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11748            1 :         check_layer_map_key_eq(
   11749            1 :             all_layers,
   11750            1 :             vec![
   11751            1 :                 PersistentLayerKey {
   11752            1 :                     key_range: get_key(0)..get_key(2),
   11753            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11754            1 :                     is_delta: false,
   11755            1 :                 },
   11756            1 :                 PersistentLayerKey {
   11757            1 :                     key_range: get_key(0)..get_key(10),
   11758            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11759            1 :                     is_delta: false,
   11760            1 :                 },
   11761            1 :                 PersistentLayerKey {
   11762            1 :                     key_range: get_key(2)..get_key(4),
   11763            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11764            1 :                     is_delta: false,
   11765            1 :                 },
   11766            1 :                 PersistentLayerKey {
   11767            1 :                     key_range: get_key(2)..get_key(4),
   11768            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11769            1 :                     is_delta: true,
   11770            1 :                 },
   11771            1 :                 PersistentLayerKey {
   11772            1 :                     key_range: get_key(4)..get_key(9),
   11773            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11774            1 :                     is_delta: false,
   11775            1 :                 },
   11776              :                 // image layer generated for the compaction range
   11777            1 :                 PersistentLayerKey {
   11778            1 :                     key_range: get_key(9)..get_key(10),
   11779            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11780            1 :                     is_delta: false,
   11781            1 :                 },
   11782            1 :                 PersistentLayerKey {
   11783            1 :                     key_range: get_key(8)..get_key(10),
   11784            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11785            1 :                     is_delta: true,
   11786            1 :                 },
   11787              :             ],
   11788              :         );
   11789              : 
   11790              :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11791            1 :         tline
   11792            1 :             .compact_with_gc(
   11793            1 :                 &cancel,
   11794            1 :                 CompactOptions {
   11795            1 :                     flags: EnumSet::new(),
   11796            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11797            1 :                     ..Default::default()
   11798            1 :                 },
   11799            1 :                 &ctx,
   11800            1 :             )
   11801            1 :             .await
   11802            1 :             .unwrap();
   11803            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11804            1 :         check_layer_map_key_eq(
   11805            1 :             all_layers,
   11806            1 :             vec![
   11807              :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11808            1 :                 PersistentLayerKey {
   11809            1 :                     key_range: get_key(0)..get_key(10),
   11810            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11811            1 :                     is_delta: false,
   11812            1 :                 },
   11813            1 :                 PersistentLayerKey {
   11814            1 :                     key_range: get_key(2)..get_key(4),
   11815            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11816            1 :                     is_delta: true,
   11817            1 :                 },
   11818            1 :                 PersistentLayerKey {
   11819            1 :                     key_range: get_key(8)..get_key(10),
   11820            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11821            1 :                     is_delta: true,
   11822            1 :                 },
   11823              :             ],
   11824              :         );
   11825            2 :         Ok(())
   11826            1 :     }
   11827              : 
   11828              :     #[cfg(feature = "testing")]
   11829              :     #[tokio::test]
   11830            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11831            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11832            1 :             .await
   11833            1 :             .unwrap();
   11834            1 :         let (tenant, ctx) = harness.load().await;
   11835            1 :         let tline_parent = tenant
   11836            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11837            1 :             .await
   11838            1 :             .unwrap();
   11839            1 :         let tline_child = tenant
   11840            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11841            1 :             .await
   11842            1 :             .unwrap();
   11843              :         {
   11844            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11845            1 :             assert_eq!(
   11846            1 :                 gc_info_parent.retain_lsns,
   11847            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11848              :             );
   11849              :         }
   11850              :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11851            1 :         tline_child
   11852            1 :             .remote_client
   11853            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11854            1 :             .unwrap();
   11855            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11856            1 :         offload_timeline(&tenant, &tline_child)
   11857            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11858            1 :             .await.unwrap();
   11859            1 :         let child_timeline_id = tline_child.timeline_id;
   11860            1 :         Arc::try_unwrap(tline_child).unwrap();
   11861              : 
   11862              :         {
   11863            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11864            1 :             assert_eq!(
   11865            1 :                 gc_info_parent.retain_lsns,
   11866            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11867              :             );
   11868              :         }
   11869              : 
   11870            1 :         tenant
   11871            1 :             .get_offloaded_timeline(child_timeline_id)
   11872            1 :             .unwrap()
   11873            1 :             .defuse_for_tenant_drop();
   11874              : 
   11875            2 :         Ok(())
   11876            1 :     }
   11877              : 
   11878              :     #[cfg(feature = "testing")]
   11879              :     #[tokio::test]
   11880            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11881            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11882            1 :         let (tenant, ctx) = harness.load().await;
   11883              : 
   11884          148 :         fn get_key(id: u32) -> Key {
   11885              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11886          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11887          148 :             key.field6 = id;
   11888          148 :             key
   11889          148 :         }
   11890              : 
   11891            1 :         let img_layer = (0..10)
   11892           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11893            1 :             .collect_vec();
   11894              : 
   11895            1 :         let delta1 = vec![(
   11896            1 :             get_key(1),
   11897            1 :             Lsn(0x20),
   11898            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11899            1 :         )];
   11900            1 :         let delta4 = vec![(
   11901            1 :             get_key(1),
   11902            1 :             Lsn(0x28),
   11903            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11904            1 :         )];
   11905            1 :         let delta2 = vec![
   11906            1 :             (
   11907            1 :                 get_key(1),
   11908            1 :                 Lsn(0x30),
   11909            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11910            1 :             ),
   11911            1 :             (
   11912            1 :                 get_key(1),
   11913            1 :                 Lsn(0x38),
   11914            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11915            1 :             ),
   11916              :         ];
   11917            1 :         let delta3 = vec![
   11918            1 :             (
   11919            1 :                 get_key(8),
   11920            1 :                 Lsn(0x48),
   11921            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11922            1 :             ),
   11923            1 :             (
   11924            1 :                 get_key(9),
   11925            1 :                 Lsn(0x48),
   11926            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11927            1 :             ),
   11928              :         ];
   11929              : 
   11930            1 :         let tline = tenant
   11931            1 :             .create_test_timeline_with_layers(
   11932            1 :                 TIMELINE_ID,
   11933            1 :                 Lsn(0x10),
   11934            1 :                 DEFAULT_PG_VERSION,
   11935            1 :                 &ctx,
   11936            1 :                 vec![], // in-memory layers
   11937            1 :                 vec![
   11938            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11939            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11940            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11941            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11942            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11943            1 :                 ], // delta layers
   11944            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11945            1 :                 Lsn(0x50),
   11946            1 :             )
   11947            1 :             .await?;
   11948              :         {
   11949            1 :             tline
   11950            1 :                 .applied_gc_cutoff_lsn
   11951            1 :                 .lock_for_write()
   11952            1 :                 .store_and_unlock(Lsn(0x30))
   11953            1 :                 .wait()
   11954            1 :                 .await;
   11955              :             // Update GC info
   11956            1 :             let mut guard = tline.gc_info.write().unwrap();
   11957            1 :             *guard = GcInfo {
   11958            1 :                 retain_lsns: vec![
   11959            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11960            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11961            1 :                 ],
   11962            1 :                 cutoffs: GcCutoffs {
   11963            1 :                     time: Some(Lsn(0x30)),
   11964            1 :                     space: Lsn(0x30),
   11965            1 :                 },
   11966            1 :                 leases: Default::default(),
   11967            1 :                 within_ancestor_pitr: false,
   11968            1 :             };
   11969              :         }
   11970              : 
   11971            1 :         let expected_result = [
   11972            1 :             Bytes::from_static(b"value 0@0x10"),
   11973            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11974            1 :             Bytes::from_static(b"value 2@0x10"),
   11975            1 :             Bytes::from_static(b"value 3@0x10"),
   11976            1 :             Bytes::from_static(b"value 4@0x10"),
   11977            1 :             Bytes::from_static(b"value 5@0x10"),
   11978            1 :             Bytes::from_static(b"value 6@0x10"),
   11979            1 :             Bytes::from_static(b"value 7@0x10"),
   11980            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11981            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11982            1 :         ];
   11983              : 
   11984            1 :         let expected_result_at_gc_horizon = [
   11985            1 :             Bytes::from_static(b"value 0@0x10"),
   11986            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11987            1 :             Bytes::from_static(b"value 2@0x10"),
   11988            1 :             Bytes::from_static(b"value 3@0x10"),
   11989            1 :             Bytes::from_static(b"value 4@0x10"),
   11990            1 :             Bytes::from_static(b"value 5@0x10"),
   11991            1 :             Bytes::from_static(b"value 6@0x10"),
   11992            1 :             Bytes::from_static(b"value 7@0x10"),
   11993            1 :             Bytes::from_static(b"value 8@0x10"),
   11994            1 :             Bytes::from_static(b"value 9@0x10"),
   11995            1 :         ];
   11996              : 
   11997            1 :         let expected_result_at_lsn_20 = [
   11998            1 :             Bytes::from_static(b"value 0@0x10"),
   11999            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12000            1 :             Bytes::from_static(b"value 2@0x10"),
   12001            1 :             Bytes::from_static(b"value 3@0x10"),
   12002            1 :             Bytes::from_static(b"value 4@0x10"),
   12003            1 :             Bytes::from_static(b"value 5@0x10"),
   12004            1 :             Bytes::from_static(b"value 6@0x10"),
   12005            1 :             Bytes::from_static(b"value 7@0x10"),
   12006            1 :             Bytes::from_static(b"value 8@0x10"),
   12007            1 :             Bytes::from_static(b"value 9@0x10"),
   12008            1 :         ];
   12009              : 
   12010            1 :         let expected_result_at_lsn_10 = [
   12011            1 :             Bytes::from_static(b"value 0@0x10"),
   12012            1 :             Bytes::from_static(b"value 1@0x10"),
   12013            1 :             Bytes::from_static(b"value 2@0x10"),
   12014            1 :             Bytes::from_static(b"value 3@0x10"),
   12015            1 :             Bytes::from_static(b"value 4@0x10"),
   12016            1 :             Bytes::from_static(b"value 5@0x10"),
   12017            1 :             Bytes::from_static(b"value 6@0x10"),
   12018            1 :             Bytes::from_static(b"value 7@0x10"),
   12019            1 :             Bytes::from_static(b"value 8@0x10"),
   12020            1 :             Bytes::from_static(b"value 9@0x10"),
   12021            1 :         ];
   12022              : 
   12023            3 :         let verify_result = || async {
   12024            3 :             let gc_horizon = {
   12025            3 :                 let gc_info = tline.gc_info.read().unwrap();
   12026            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   12027              :             };
   12028           33 :             for idx in 0..10 {
   12029           30 :                 assert_eq!(
   12030           30 :                     tline
   12031           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12032           30 :                         .await
   12033           30 :                         .unwrap(),
   12034           30 :                     &expected_result[idx]
   12035              :                 );
   12036           30 :                 assert_eq!(
   12037           30 :                     tline
   12038           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12039           30 :                         .await
   12040           30 :                         .unwrap(),
   12041           30 :                     &expected_result_at_gc_horizon[idx]
   12042              :                 );
   12043           30 :                 assert_eq!(
   12044           30 :                     tline
   12045           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12046           30 :                         .await
   12047           30 :                         .unwrap(),
   12048           30 :                     &expected_result_at_lsn_20[idx]
   12049              :                 );
   12050           30 :                 assert_eq!(
   12051           30 :                     tline
   12052           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12053           30 :                         .await
   12054           30 :                         .unwrap(),
   12055           30 :                     &expected_result_at_lsn_10[idx]
   12056              :                 );
   12057              :             }
   12058            6 :         };
   12059              : 
   12060            1 :         verify_result().await;
   12061              : 
   12062            1 :         let cancel = CancellationToken::new();
   12063            1 :         tline
   12064            1 :             .compact_with_gc(
   12065            1 :                 &cancel,
   12066            1 :                 CompactOptions {
   12067            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   12068            1 :                     ..Default::default()
   12069            1 :                 },
   12070            1 :                 &ctx,
   12071            1 :             )
   12072            1 :             .await
   12073            1 :             .unwrap();
   12074            1 :         verify_result().await;
   12075              : 
   12076            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12077            1 :         check_layer_map_key_eq(
   12078            1 :             all_layers,
   12079            1 :             vec![
   12080              :                 // The original image layer, not compacted
   12081            1 :                 PersistentLayerKey {
   12082            1 :                     key_range: get_key(0)..get_key(10),
   12083            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12084            1 :                     is_delta: false,
   12085            1 :                 },
   12086              :                 // Delta layer below the specified above_lsn not compacted
   12087            1 :                 PersistentLayerKey {
   12088            1 :                     key_range: get_key(1)..get_key(2),
   12089            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   12090            1 :                     is_delta: true,
   12091            1 :                 },
   12092              :                 // Delta layer compacted above the LSN
   12093            1 :                 PersistentLayerKey {
   12094            1 :                     key_range: get_key(1)..get_key(10),
   12095            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   12096            1 :                     is_delta: true,
   12097            1 :                 },
   12098              :             ],
   12099              :         );
   12100              : 
   12101              :         // compact again
   12102            1 :         tline
   12103            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12104            1 :             .await
   12105            1 :             .unwrap();
   12106            1 :         verify_result().await;
   12107              : 
   12108            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12109            1 :         check_layer_map_key_eq(
   12110            1 :             all_layers,
   12111            1 :             vec![
   12112              :                 // The compacted image layer (full key range)
   12113            1 :                 PersistentLayerKey {
   12114            1 :                     key_range: Key::MIN..Key::MAX,
   12115            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12116            1 :                     is_delta: false,
   12117            1 :                 },
   12118              :                 // All other data in the delta layer
   12119            1 :                 PersistentLayerKey {
   12120            1 :                     key_range: get_key(1)..get_key(10),
   12121            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12122            1 :                     is_delta: true,
   12123            1 :                 },
   12124              :             ],
   12125              :         );
   12126              : 
   12127            2 :         Ok(())
   12128            1 :     }
   12129              : 
   12130              :     #[cfg(feature = "testing")]
   12131              :     #[tokio::test]
   12132            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   12133            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   12134            1 :         let (tenant, ctx) = harness.load().await;
   12135              : 
   12136          254 :         fn get_key(id: u32) -> Key {
   12137              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12138          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12139          254 :             key.field6 = id;
   12140          254 :             key
   12141          254 :         }
   12142              : 
   12143            1 :         let img_layer = (0..10)
   12144           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12145            1 :             .collect_vec();
   12146              : 
   12147            1 :         let delta1 = vec![(
   12148            1 :             get_key(1),
   12149            1 :             Lsn(0x20),
   12150            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12151            1 :         )];
   12152            1 :         let delta4 = vec![(
   12153            1 :             get_key(1),
   12154            1 :             Lsn(0x28),
   12155            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   12156            1 :         )];
   12157            1 :         let delta2 = vec![
   12158            1 :             (
   12159            1 :                 get_key(1),
   12160            1 :                 Lsn(0x30),
   12161            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   12162            1 :             ),
   12163            1 :             (
   12164            1 :                 get_key(1),
   12165            1 :                 Lsn(0x38),
   12166            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   12167            1 :             ),
   12168              :         ];
   12169            1 :         let delta3 = vec![
   12170            1 :             (
   12171            1 :                 get_key(8),
   12172            1 :                 Lsn(0x48),
   12173            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12174            1 :             ),
   12175            1 :             (
   12176            1 :                 get_key(9),
   12177            1 :                 Lsn(0x48),
   12178            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12179            1 :             ),
   12180              :         ];
   12181              : 
   12182            1 :         let tline = tenant
   12183            1 :             .create_test_timeline_with_layers(
   12184            1 :                 TIMELINE_ID,
   12185            1 :                 Lsn(0x10),
   12186            1 :                 DEFAULT_PG_VERSION,
   12187            1 :                 &ctx,
   12188            1 :                 vec![], // in-memory layers
   12189            1 :                 vec![
   12190            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12191            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12192            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12193            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12194            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12195            1 :                 ], // delta layers
   12196            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12197            1 :                 Lsn(0x50),
   12198            1 :             )
   12199            1 :             .await?;
   12200              :         {
   12201            1 :             tline
   12202            1 :                 .applied_gc_cutoff_lsn
   12203            1 :                 .lock_for_write()
   12204            1 :                 .store_and_unlock(Lsn(0x30))
   12205            1 :                 .wait()
   12206            1 :                 .await;
   12207              :             // Update GC info
   12208            1 :             let mut guard = tline.gc_info.write().unwrap();
   12209            1 :             *guard = GcInfo {
   12210            1 :                 retain_lsns: vec![
   12211            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12212            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12213            1 :                 ],
   12214            1 :                 cutoffs: GcCutoffs {
   12215            1 :                     time: Some(Lsn(0x30)),
   12216            1 :                     space: Lsn(0x30),
   12217            1 :                 },
   12218            1 :                 leases: Default::default(),
   12219            1 :                 within_ancestor_pitr: false,
   12220            1 :             };
   12221              :         }
   12222              : 
   12223            1 :         let expected_result = [
   12224            1 :             Bytes::from_static(b"value 0@0x10"),
   12225            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12226            1 :             Bytes::from_static(b"value 2@0x10"),
   12227            1 :             Bytes::from_static(b"value 3@0x10"),
   12228            1 :             Bytes::from_static(b"value 4@0x10"),
   12229            1 :             Bytes::from_static(b"value 5@0x10"),
   12230            1 :             Bytes::from_static(b"value 6@0x10"),
   12231            1 :             Bytes::from_static(b"value 7@0x10"),
   12232            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12233            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12234            1 :         ];
   12235              : 
   12236            1 :         let expected_result_at_gc_horizon = [
   12237            1 :             Bytes::from_static(b"value 0@0x10"),
   12238            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12239            1 :             Bytes::from_static(b"value 2@0x10"),
   12240            1 :             Bytes::from_static(b"value 3@0x10"),
   12241            1 :             Bytes::from_static(b"value 4@0x10"),
   12242            1 :             Bytes::from_static(b"value 5@0x10"),
   12243            1 :             Bytes::from_static(b"value 6@0x10"),
   12244            1 :             Bytes::from_static(b"value 7@0x10"),
   12245            1 :             Bytes::from_static(b"value 8@0x10"),
   12246            1 :             Bytes::from_static(b"value 9@0x10"),
   12247            1 :         ];
   12248              : 
   12249            1 :         let expected_result_at_lsn_20 = [
   12250            1 :             Bytes::from_static(b"value 0@0x10"),
   12251            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12252            1 :             Bytes::from_static(b"value 2@0x10"),
   12253            1 :             Bytes::from_static(b"value 3@0x10"),
   12254            1 :             Bytes::from_static(b"value 4@0x10"),
   12255            1 :             Bytes::from_static(b"value 5@0x10"),
   12256            1 :             Bytes::from_static(b"value 6@0x10"),
   12257            1 :             Bytes::from_static(b"value 7@0x10"),
   12258            1 :             Bytes::from_static(b"value 8@0x10"),
   12259            1 :             Bytes::from_static(b"value 9@0x10"),
   12260            1 :         ];
   12261              : 
   12262            1 :         let expected_result_at_lsn_10 = [
   12263            1 :             Bytes::from_static(b"value 0@0x10"),
   12264            1 :             Bytes::from_static(b"value 1@0x10"),
   12265            1 :             Bytes::from_static(b"value 2@0x10"),
   12266            1 :             Bytes::from_static(b"value 3@0x10"),
   12267            1 :             Bytes::from_static(b"value 4@0x10"),
   12268            1 :             Bytes::from_static(b"value 5@0x10"),
   12269            1 :             Bytes::from_static(b"value 6@0x10"),
   12270            1 :             Bytes::from_static(b"value 7@0x10"),
   12271            1 :             Bytes::from_static(b"value 8@0x10"),
   12272            1 :             Bytes::from_static(b"value 9@0x10"),
   12273            1 :         ];
   12274              : 
   12275            5 :         let verify_result = || async {
   12276            5 :             let gc_horizon = {
   12277            5 :                 let gc_info = tline.gc_info.read().unwrap();
   12278            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   12279              :             };
   12280           55 :             for idx in 0..10 {
   12281           50 :                 assert_eq!(
   12282           50 :                     tline
   12283           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12284           50 :                         .await
   12285           50 :                         .unwrap(),
   12286           50 :                     &expected_result[idx]
   12287              :                 );
   12288           50 :                 assert_eq!(
   12289           50 :                     tline
   12290           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12291           50 :                         .await
   12292           50 :                         .unwrap(),
   12293           50 :                     &expected_result_at_gc_horizon[idx]
   12294              :                 );
   12295           50 :                 assert_eq!(
   12296           50 :                     tline
   12297           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12298           50 :                         .await
   12299           50 :                         .unwrap(),
   12300           50 :                     &expected_result_at_lsn_20[idx]
   12301              :                 );
   12302           50 :                 assert_eq!(
   12303           50 :                     tline
   12304           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12305           50 :                         .await
   12306           50 :                         .unwrap(),
   12307           50 :                     &expected_result_at_lsn_10[idx]
   12308              :                 );
   12309              :             }
   12310           10 :         };
   12311              : 
   12312            1 :         verify_result().await;
   12313              : 
   12314            1 :         let cancel = CancellationToken::new();
   12315              : 
   12316            1 :         tline
   12317            1 :             .compact_with_gc(
   12318            1 :                 &cancel,
   12319            1 :                 CompactOptions {
   12320            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12321            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12322            1 :                     ..Default::default()
   12323            1 :                 },
   12324            1 :                 &ctx,
   12325            1 :             )
   12326            1 :             .await
   12327            1 :             .unwrap();
   12328            1 :         verify_result().await;
   12329              : 
   12330            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12331            1 :         check_layer_map_key_eq(
   12332            1 :             all_layers,
   12333            1 :             vec![
   12334              :                 // The original image layer, not compacted
   12335            1 :                 PersistentLayerKey {
   12336            1 :                     key_range: get_key(0)..get_key(10),
   12337            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12338            1 :                     is_delta: false,
   12339            1 :                 },
   12340              :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12341              :                 // the layer 0x28-0x30 into one.
   12342            1 :                 PersistentLayerKey {
   12343            1 :                     key_range: get_key(1)..get_key(2),
   12344            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12345            1 :                     is_delta: true,
   12346            1 :                 },
   12347              :                 // Above the upper bound and untouched
   12348            1 :                 PersistentLayerKey {
   12349            1 :                     key_range: get_key(1)..get_key(2),
   12350            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12351            1 :                     is_delta: true,
   12352            1 :                 },
   12353              :                 // This layer is untouched
   12354            1 :                 PersistentLayerKey {
   12355            1 :                     key_range: get_key(8)..get_key(10),
   12356            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12357            1 :                     is_delta: true,
   12358            1 :                 },
   12359              :             ],
   12360              :         );
   12361              : 
   12362            1 :         tline
   12363            1 :             .compact_with_gc(
   12364            1 :                 &cancel,
   12365            1 :                 CompactOptions {
   12366            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12367            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12368            1 :                     ..Default::default()
   12369            1 :                 },
   12370            1 :                 &ctx,
   12371            1 :             )
   12372            1 :             .await
   12373            1 :             .unwrap();
   12374            1 :         verify_result().await;
   12375              : 
   12376            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12377            1 :         check_layer_map_key_eq(
   12378            1 :             all_layers,
   12379            1 :             vec![
   12380              :                 // The original image layer, not compacted
   12381            1 :                 PersistentLayerKey {
   12382            1 :                     key_range: get_key(0)..get_key(10),
   12383            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12384            1 :                     is_delta: false,
   12385            1 :                 },
   12386              :                 // Not in the compaction key range, uncompacted
   12387            1 :                 PersistentLayerKey {
   12388            1 :                     key_range: get_key(1)..get_key(2),
   12389            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12390            1 :                     is_delta: true,
   12391            1 :                 },
   12392              :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12393            1 :                 PersistentLayerKey {
   12394            1 :                     key_range: get_key(1)..get_key(2),
   12395            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12396            1 :                     is_delta: true,
   12397            1 :                 },
   12398              :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12399              :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12400              :                 // becomes 0x50.
   12401            1 :                 PersistentLayerKey {
   12402            1 :                     key_range: get_key(8)..get_key(10),
   12403            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12404            1 :                     is_delta: true,
   12405            1 :                 },
   12406              :             ],
   12407              :         );
   12408              : 
   12409              :         // compact again
   12410            1 :         tline
   12411            1 :             .compact_with_gc(
   12412            1 :                 &cancel,
   12413            1 :                 CompactOptions {
   12414            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12415            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12416            1 :                     ..Default::default()
   12417            1 :                 },
   12418            1 :                 &ctx,
   12419            1 :             )
   12420            1 :             .await
   12421            1 :             .unwrap();
   12422            1 :         verify_result().await;
   12423              : 
   12424            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12425            1 :         check_layer_map_key_eq(
   12426            1 :             all_layers,
   12427            1 :             vec![
   12428              :                 // The original image layer, not compacted
   12429            1 :                 PersistentLayerKey {
   12430            1 :                     key_range: get_key(0)..get_key(10),
   12431            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12432            1 :                     is_delta: false,
   12433            1 :                 },
   12434              :                 // The range gets compacted
   12435            1 :                 PersistentLayerKey {
   12436            1 :                     key_range: get_key(1)..get_key(2),
   12437            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12438            1 :                     is_delta: true,
   12439            1 :                 },
   12440              :                 // Not touched during this iteration of compaction
   12441            1 :                 PersistentLayerKey {
   12442            1 :                     key_range: get_key(8)..get_key(10),
   12443            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12444            1 :                     is_delta: true,
   12445            1 :                 },
   12446              :             ],
   12447              :         );
   12448              : 
   12449              :         // final full compaction
   12450            1 :         tline
   12451            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12452            1 :             .await
   12453            1 :             .unwrap();
   12454            1 :         verify_result().await;
   12455              : 
   12456            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12457            1 :         check_layer_map_key_eq(
   12458            1 :             all_layers,
   12459            1 :             vec![
   12460              :                 // The compacted image layer (full key range)
   12461            1 :                 PersistentLayerKey {
   12462            1 :                     key_range: Key::MIN..Key::MAX,
   12463            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12464            1 :                     is_delta: false,
   12465            1 :                 },
   12466              :                 // All other data in the delta layer
   12467            1 :                 PersistentLayerKey {
   12468            1 :                     key_range: get_key(1)..get_key(10),
   12469            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12470            1 :                     is_delta: true,
   12471            1 :                 },
   12472              :             ],
   12473              :         );
   12474              : 
   12475            2 :         Ok(())
   12476            1 :     }
   12477              : 
   12478              :     #[cfg(feature = "testing")]
   12479              :     #[tokio::test]
   12480            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12481            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12482            1 :         let (tenant, ctx) = harness.load().await;
   12483              : 
   12484           13 :         fn get_key(id: u32) -> Key {
   12485              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12486           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12487           13 :             key.field6 = id;
   12488           13 :             key
   12489           13 :         }
   12490              : 
   12491            1 :         let img_layer = (0..10)
   12492           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12493            1 :             .collect_vec();
   12494              : 
   12495            1 :         let delta1 = vec![
   12496            1 :             (
   12497            1 :                 get_key(1),
   12498            1 :                 Lsn(0x20),
   12499            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12500            1 :             ),
   12501            1 :             (
   12502            1 :                 get_key(1),
   12503            1 :                 Lsn(0x24),
   12504            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12505            1 :             ),
   12506            1 :             (
   12507            1 :                 get_key(1),
   12508            1 :                 Lsn(0x28),
   12509            1 :                 // This record will fail to redo
   12510            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12511            1 :             ),
   12512              :         ];
   12513              : 
   12514            1 :         let tline = tenant
   12515            1 :             .create_test_timeline_with_layers(
   12516            1 :                 TIMELINE_ID,
   12517            1 :                 Lsn(0x10),
   12518            1 :                 DEFAULT_PG_VERSION,
   12519            1 :                 &ctx,
   12520            1 :                 vec![], // in-memory layers
   12521            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12522            1 :                     Lsn(0x20)..Lsn(0x30),
   12523            1 :                     delta1,
   12524            1 :                 )], // delta layers
   12525            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12526            1 :                 Lsn(0x50),
   12527            1 :             )
   12528            1 :             .await?;
   12529              :         {
   12530            1 :             tline
   12531            1 :                 .applied_gc_cutoff_lsn
   12532            1 :                 .lock_for_write()
   12533            1 :                 .store_and_unlock(Lsn(0x30))
   12534            1 :                 .wait()
   12535            1 :                 .await;
   12536              :             // Update GC info
   12537            1 :             let mut guard = tline.gc_info.write().unwrap();
   12538            1 :             *guard = GcInfo {
   12539            1 :                 retain_lsns: vec![],
   12540            1 :                 cutoffs: GcCutoffs {
   12541            1 :                     time: Some(Lsn(0x30)),
   12542            1 :                     space: Lsn(0x30),
   12543            1 :                 },
   12544            1 :                 leases: Default::default(),
   12545            1 :                 within_ancestor_pitr: false,
   12546            1 :             };
   12547              :         }
   12548              : 
   12549            1 :         let cancel = CancellationToken::new();
   12550              : 
   12551              :         // Compaction will fail, but should not fire any critical error.
   12552              :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12553              :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12554              :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12555            1 :         let res = tline
   12556            1 :             .compact_with_gc(
   12557            1 :                 &cancel,
   12558            1 :                 CompactOptions {
   12559            1 :                     compact_key_range: None,
   12560            1 :                     compact_lsn_range: None,
   12561            1 :                     ..Default::default()
   12562            1 :                 },
   12563            1 :                 &ctx,
   12564            1 :             )
   12565            1 :             .await;
   12566            1 :         assert!(res.is_err());
   12567              : 
   12568            2 :         Ok(())
   12569            1 :     }
   12570              : 
   12571              :     #[cfg(feature = "testing")]
   12572              :     #[tokio::test]
   12573            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12574              :         use pageserver_api::models::TimelineVisibilityState;
   12575              : 
   12576              :         use crate::tenant::size::gather_inputs;
   12577              : 
   12578            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12579            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12580            1 :             pitr_interval: Some(Duration::ZERO),
   12581            1 :             ..Default::default()
   12582            1 :         };
   12583            1 :         let harness = TenantHarness::create_custom(
   12584            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12585            1 :             tenant_conf,
   12586            1 :             TenantId::generate(),
   12587            1 :             ShardIdentity::unsharded(),
   12588            1 :             Generation::new(0xdeadbeef),
   12589            1 :         )
   12590            1 :         .await?;
   12591            1 :         let (tenant, ctx) = harness.load().await;
   12592            1 :         let main_tline = tenant
   12593            1 :             .create_test_timeline_with_layers(
   12594            1 :                 TIMELINE_ID,
   12595            1 :                 Lsn(0x10),
   12596            1 :                 DEFAULT_PG_VERSION,
   12597            1 :                 &ctx,
   12598            1 :                 vec![],
   12599            1 :                 vec![],
   12600            1 :                 vec![],
   12601            1 :                 Lsn(0x100),
   12602            1 :             )
   12603            1 :             .await?;
   12604              : 
   12605            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12606            1 :         tenant
   12607            1 :             .branch_timeline_test_with_layers(
   12608            1 :                 &main_tline,
   12609            1 :                 snapshot1,
   12610            1 :                 Some(Lsn(0x20)),
   12611            1 :                 &ctx,
   12612            1 :                 vec![],
   12613            1 :                 vec![],
   12614            1 :                 Lsn(0x50),
   12615            1 :             )
   12616            1 :             .await?;
   12617            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12618            1 :         tenant
   12619            1 :             .branch_timeline_test_with_layers(
   12620            1 :                 &main_tline,
   12621            1 :                 snapshot2,
   12622            1 :                 Some(Lsn(0x30)),
   12623            1 :                 &ctx,
   12624            1 :                 vec![],
   12625            1 :                 vec![],
   12626            1 :                 Lsn(0x50),
   12627            1 :             )
   12628            1 :             .await?;
   12629            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12630            1 :         tenant
   12631            1 :             .branch_timeline_test_with_layers(
   12632            1 :                 &main_tline,
   12633            1 :                 snapshot3,
   12634            1 :                 Some(Lsn(0x40)),
   12635            1 :                 &ctx,
   12636            1 :                 vec![],
   12637            1 :                 vec![],
   12638            1 :                 Lsn(0x50),
   12639            1 :             )
   12640            1 :             .await?;
   12641            1 :         let limit = Arc::new(Semaphore::new(1));
   12642            1 :         let max_retention_period = None;
   12643            1 :         let mut logical_size_cache = HashMap::new();
   12644            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12645            1 :         let cancel = CancellationToken::new();
   12646              : 
   12647            1 :         let inputs = gather_inputs(
   12648            1 :             &tenant,
   12649            1 :             &limit,
   12650            1 :             max_retention_period,
   12651            1 :             &mut logical_size_cache,
   12652            1 :             cause,
   12653            1 :             &cancel,
   12654            1 :             &ctx,
   12655              :         )
   12656            1 :         .instrument(info_span!(
   12657              :             "gather_inputs",
   12658              :             tenant_id = "unknown",
   12659              :             shard_id = "unknown",
   12660              :         ))
   12661            1 :         .await?;
   12662              :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12663              :         use LsnKind::*;
   12664              :         use tenant_size_model::Segment;
   12665            1 :         let ModelInputs { mut segments, .. } = inputs;
   12666           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12667            6 :         for segment in segments.iter_mut() {
   12668            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12669            6 :             segment.segment.size = None; // We don't care about the size for the test
   12670            6 :         }
   12671            1 :         assert_eq!(
   12672              :             segments,
   12673              :             [
   12674              :                 SegmentMeta {
   12675              :                     segment: Segment {
   12676              :                         parent: None,
   12677              :                         lsn: 0x10,
   12678              :                         size: None,
   12679              :                         needed: false,
   12680              :                     },
   12681              :                     timeline_id: TIMELINE_ID,
   12682              :                     kind: BranchStart,
   12683              :                 },
   12684              :                 SegmentMeta {
   12685              :                     segment: Segment {
   12686              :                         parent: None,
   12687              :                         lsn: 0x20,
   12688              :                         size: None,
   12689              :                         needed: false,
   12690              :                     },
   12691              :                     timeline_id: TIMELINE_ID,
   12692              :                     kind: BranchPoint,
   12693              :                 },
   12694              :                 SegmentMeta {
   12695              :                     segment: Segment {
   12696              :                         parent: None,
   12697              :                         lsn: 0x30,
   12698              :                         size: None,
   12699              :                         needed: false,
   12700              :                     },
   12701              :                     timeline_id: TIMELINE_ID,
   12702              :                     kind: BranchPoint,
   12703              :                 },
   12704              :                 SegmentMeta {
   12705              :                     segment: Segment {
   12706              :                         parent: None,
   12707              :                         lsn: 0x40,
   12708              :                         size: None,
   12709              :                         needed: false,
   12710              :                     },
   12711              :                     timeline_id: TIMELINE_ID,
   12712              :                     kind: BranchPoint,
   12713              :                 },
   12714              :                 SegmentMeta {
   12715              :                     segment: Segment {
   12716              :                         parent: None,
   12717              :                         lsn: 0x100,
   12718              :                         size: None,
   12719              :                         needed: false,
   12720              :                     },
   12721              :                     timeline_id: TIMELINE_ID,
   12722              :                     kind: GcCutOff,
   12723              :                 }, // we need to retain everything above the last branch point
   12724              :                 SegmentMeta {
   12725              :                     segment: Segment {
   12726              :                         parent: None,
   12727              :                         lsn: 0x100,
   12728              :                         size: None,
   12729              :                         needed: true,
   12730              :                     },
   12731              :                     timeline_id: TIMELINE_ID,
   12732              :                     kind: BranchEnd,
   12733              :                 },
   12734              :             ]
   12735              :         );
   12736              : 
   12737            1 :         main_tline
   12738            1 :             .remote_client
   12739            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12740            1 :                 TimelineVisibilityState::Invisible,
   12741            0 :             )?;
   12742            1 :         main_tline.remote_client.wait_completion().await?;
   12743            1 :         let inputs = gather_inputs(
   12744            1 :             &tenant,
   12745            1 :             &limit,
   12746            1 :             max_retention_period,
   12747            1 :             &mut logical_size_cache,
   12748            1 :             cause,
   12749            1 :             &cancel,
   12750            1 :             &ctx,
   12751              :         )
   12752            1 :         .instrument(info_span!(
   12753              :             "gather_inputs",
   12754              :             tenant_id = "unknown",
   12755              :             shard_id = "unknown",
   12756              :         ))
   12757            1 :         .await?;
   12758            1 :         let ModelInputs { mut segments, .. } = inputs;
   12759           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12760            5 :         for segment in segments.iter_mut() {
   12761            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12762            5 :             segment.segment.size = None; // We don't care about the size for the test
   12763            5 :         }
   12764            1 :         assert_eq!(
   12765              :             segments,
   12766              :             [
   12767              :                 SegmentMeta {
   12768              :                     segment: Segment {
   12769              :                         parent: None,
   12770              :                         lsn: 0x10,
   12771              :                         size: None,
   12772              :                         needed: false,
   12773              :                     },
   12774              :                     timeline_id: TIMELINE_ID,
   12775              :                     kind: BranchStart,
   12776              :                 },
   12777              :                 SegmentMeta {
   12778              :                     segment: Segment {
   12779              :                         parent: None,
   12780              :                         lsn: 0x20,
   12781              :                         size: None,
   12782              :                         needed: false,
   12783              :                     },
   12784              :                     timeline_id: TIMELINE_ID,
   12785              :                     kind: BranchPoint,
   12786              :                 },
   12787              :                 SegmentMeta {
   12788              :                     segment: Segment {
   12789              :                         parent: None,
   12790              :                         lsn: 0x30,
   12791              :                         size: None,
   12792              :                         needed: false,
   12793              :                     },
   12794              :                     timeline_id: TIMELINE_ID,
   12795              :                     kind: BranchPoint,
   12796              :                 },
   12797              :                 SegmentMeta {
   12798              :                     segment: Segment {
   12799              :                         parent: None,
   12800              :                         lsn: 0x40,
   12801              :                         size: None,
   12802              :                         needed: false,
   12803              :                     },
   12804              :                     timeline_id: TIMELINE_ID,
   12805              :                     kind: BranchPoint,
   12806              :                 },
   12807              :                 SegmentMeta {
   12808              :                     segment: Segment {
   12809              :                         parent: None,
   12810              :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12811              :                         size: None,
   12812              :                         needed: true,
   12813              :                     },
   12814              :                     timeline_id: TIMELINE_ID,
   12815              :                     kind: BranchEnd,
   12816              :                 },
   12817              :             ]
   12818              :         );
   12819              : 
   12820            2 :         Ok(())
   12821            1 :     }
   12822              : 
   12823              :     #[tokio::test]
   12824            1 :     async fn test_get_force_image_creation_lsn() -> anyhow::Result<()> {
   12825            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12826            1 :             pitr_interval: Some(Duration::from_secs(7 * 3600)),
   12827            1 :             image_layer_force_creation_period: Some(Duration::from_secs(3600)),
   12828            1 :             ..Default::default()
   12829            1 :         };
   12830              : 
   12831            1 :         let tenant_id = TenantId::generate();
   12832              : 
   12833            1 :         let harness = TenantHarness::create_custom(
   12834            1 :             "test_get_force_image_creation_lsn",
   12835            1 :             tenant_conf,
   12836            1 :             tenant_id,
   12837            1 :             ShardIdentity::unsharded(),
   12838            1 :             Generation::new(1),
   12839            1 :         )
   12840            1 :         .await?;
   12841            1 :         let (tenant, ctx) = harness.load().await;
   12842            1 :         let timeline = tenant
   12843            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   12844            1 :             .await?;
   12845            1 :         timeline.gc_info.write().unwrap().cutoffs.time = Some(Lsn(100));
   12846              :         {
   12847            1 :             let writer = timeline.writer().await;
   12848            1 :             writer.finish_write(Lsn(5000));
   12849              :         }
   12850              : 
   12851            1 :         let image_creation_lsn = timeline.get_force_image_creation_lsn().unwrap();
   12852            1 :         assert_eq!(image_creation_lsn, Lsn(4300));
   12853            2 :         Ok(())
   12854            1 :     }
   12855              : }
        

Generated by: LCOV version 2.1-beta